diff --git a/.gitignore b/.gitignore index 896009d10..5a4cf35fb 100644 --- a/.gitignore +++ b/.gitignore @@ -15,3 +15,4 @@ *.log *.exe cover.out +vendor/ diff --git a/.golangci.toml b/.golangci.toml index bdbe5c3b0..35e627aa0 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -37,6 +37,7 @@ "gochecknoinits", "gochecknoglobals", "bodyclose", # Too many false-positive and panics. + "typecheck", # v1.17.1 and Go1.13 => bug ] [issues] @@ -65,7 +66,7 @@ text = "Error return value of `rw.Write` is not checked" [[issues.exclude-rules]] path = "pkg/middlewares/recovery/recovery.go" - text = "`logger` can be `github.com/containous/traefik/vendor/github.com/stretchr/testify/assert.TestingT`" + text = "`logger` can be `github.com/stretchr/testify/assert.TestingT`" [[issues.exclude-rules]] path = "pkg/provider/docker/builder_test.go" text = "(U1000: func )?`(.+)` is unused" diff --git a/.goreleaser.yml b/.goreleaser.yml index b21524285..95086aeb3 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -11,7 +11,7 @@ builds: env: - CGO_ENABLED=0 ldflags: - - -s -w -X github.com/containous/traefik/pkg/version.Version={{.Version}} -X github.com/containous/traefik/pkg/version.Codename={{.Env.CODENAME}} -X github.com/containous/traefik/pkg/version.BuildDate={{.Date}} + - -s -w -X github.com/containous/traefik/v2/pkg/version.Version={{.Version}} -X github.com/containous/traefik/v2/pkg/version.Codename={{.Env.CODENAME}} -X github.com/containous/traefik/v2/pkg/version.BuildDate={{.Date}} goos: - linux @@ -40,16 +40,16 @@ builds: changelog: skip: true -archive: - name_template: '{{ .ProjectName }}_v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm - }}v{{ .Arm }}{{ end }}' - format: tar.gz - format_overrides: - - goos: windows - format: zip - files: - - LICENSE.md - - CHANGELOG.md +archives: + - id: traefik + name_template: '{{ .ProjectName }}_v{{ .Version }}_{{ .Os }}_{{ .Arch }}{{ if .Arm }}v{{ .Arm }}{{ end }}' + format: tar.gz + format_overrides: + - goos: windows + format: zip + files: + - LICENSE.md + - CHANGELOG.md checksum: name_template: "{{ .ProjectName }}_v{{ .Version }}_checksums.txt" diff --git a/.semaphoreci/golang.sh b/.semaphoreci/golang.sh index ec24aac57..c275de34b 100755 --- a/.semaphoreci/golang.sh +++ b/.semaphoreci/golang.sh @@ -2,19 +2,19 @@ set -e -curl -O https://dl.google.com/go/go1.12.linux-amd64.tar.gz +curl -O https://dl.google.com/go/go"${GO_VERSION}".linux-amd64.tar.gz -tar -xvf go1.12.linux-amd64.tar.gz -rm -rf go1.12.linux-amd64.tar.gz +tar -xvf go"${GO_VERSION}".linux-amd64.tar.gz +rm -rf go"${GO_VERSION}".linux-amd64.tar.gz -sudo mkdir -p /usr/local/golang/1.12/go -sudo mv go /usr/local/golang/1.12/ +sudo mkdir -p /usr/local/golang/"${GO_VERSION}"/go +sudo mv go /usr/local/golang/"${GO_VERSION}"/ sudo rm /usr/local/bin/go -sudo chmod +x /usr/local/golang/1.12/go/bin/go -sudo ln -s /usr/local/golang/1.12/go/bin/go /usr/local/bin/go +sudo chmod +x /usr/local/golang/"${GO_VERSION}"/go/bin/go +sudo ln -s /usr/local/golang/"${GO_VERSION}"/go/bin/go /usr/local/bin/go -export GOROOT="/usr/local/golang/1.12/go" -export GOTOOLDIR="/usr/local/golang/1.12/go/pkg/tool/linux_amd64" +export GOROOT="/usr/local/golang/${GO_VERSION}/go" +export GOTOOLDIR="/usr/local/golang/${GO_VERSION}/go/pkg/tool/linux_amd64" go version diff --git a/.semaphoreci/setup.sh b/.semaphoreci/setup.sh index af0878c0e..568eea2fc 100755 --- a/.semaphoreci/setup.sh +++ b/.semaphoreci/setup.sh @@ -1,12 +1,13 @@ -#!/usr/bin/env bash -set -e - +# For personnal CI +# mv /home/runner/workspace/src/github.com// /home/runner/workspace/src/github.com/containous/ +# cd /home/runner/workspace/src/github.com/containous/traefik/ for s in apache2 cassandra elasticsearch memcached mysql mongod postgresql sphinxsearch rethinkdb rabbitmq-server redis-server; do sudo service $s stop; done sudo swapoff -a sudo dd if=/dev/zero of=/swapfile bs=1M count=3072 sudo mkswap /swapfile sudo swapon /swapfile sudo rm -rf /home/runner/.rbenv +sudo rm -rf /usr/local/golang/{1.4.3,1.5.4,1.6.4,1.7.6,1.8.6,1.9.7,1.10.3,1.11} #export DOCKER_VERSION=18.06.3 source .semaphoreci/vars if [ -z "${PULL_REQUEST_NUMBER}" ]; then SHOULD_TEST="-*-"; else TEMP_STORAGE=$(curl --silent https://patch-diff.githubusercontent.com/raw/containous/traefik/pull/${PULL_REQUEST_NUMBER}.diff | patch --dry-run -p1 -R || true); fi @@ -16,7 +17,22 @@ echo ${TEMP_STORAGE} echo ${SHOULD_TEST} #if [ -n "$SHOULD_TEST" ]; then sudo -E apt-get -yq update; fi #if [ -n "$SHOULD_TEST" ]; then sudo -E apt-get -yq --no-install-suggests --no-install-recommends --force-yes install docker-ce=${DOCKER_VERSION}*; fi -if [ -n "$SHOULD_TEST" ]; then docker version; fi +if [ -n "$SHOULD_TEST" ]; then docker version; fi + +export GO_VERSION=1.12 +if [ -f "./go.mod" ]; then GO_VERSION="$(grep '^go .*' go.mod | awk '{print $2}')"; export GO_VERSION; fi +if [ "${GO_VERSION}" == '1.13' ]; then export GO_VERSION=1.13rc1; fi +echo "Selected Go version: ${GO_VERSION}" + if [ -f "./.semaphoreci/golang.sh" ]; then ./.semaphoreci/golang.sh; fi -if [ -f "./.semaphoreci/golang.sh" ]; then export GOROOT="/usr/local/golang/1.12/go"; fi -if [ -f "./.semaphoreci/golang.sh" ]; then export GOTOOLDIR="/usr/local/golang/1.12/go/pkg/tool/linux_amd64"; fi +if [ -f "./.semaphoreci/golang.sh" ]; then export GOROOT="/usr/local/golang/${GO_VERSION}/go"; fi +if [ -f "./.semaphoreci/golang.sh" ]; then export GOTOOLDIR="/usr/local/golang/${GO_VERSION}/go/pkg/tool/linux_amd64"; fi +go version + +if [ -f "./go.mod" ]; then export GO111MODULE=on; fi +if [ -f "./go.mod" ]; then export GOPROXY=https://proxy.golang.org; fi +if [ -f "./go.mod" ]; then go mod download; fi + +df + + diff --git a/.semaphoreci/vars b/.semaphoreci/vars index 631289c78..e80364665 100644 --- a/.semaphoreci/vars +++ b/.semaphoreci/vars @@ -10,7 +10,7 @@ else export VERSION='' fi -export CODENAME=faisselle +export CODENAME=montdor export N_MAKE_JOBS=2 diff --git a/.travis.yml b/.travis.yml index 45c8eb33e..f3f7d4d61 100644 --- a/.travis.yml +++ b/.travis.yml @@ -9,9 +9,10 @@ services: env: global: - - REPO: $TRAVIS_REPO_SLUG - - VERSION: $TRAVIS_TAG - - CODENAME: faisselle + - REPO=$TRAVIS_REPO_SLUG + - VERSION=$TRAVIS_TAG + - CODENAME=montdor + - GO111MODULE=on script: - echo "Skipping tests... (Tests are executed on SemaphoreCI)" diff --git a/CHANGELOG.md b/CHANGELOG.md index d88dc0328..39faf0a9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,68 @@ # Change Log +## [v2.0.0-rc1](https://github.com/containous/traefik/tree/v2.0.0-rc1) (2019-08-26) +[All Commits](https://github.com/containous/traefik/compare/v2.0.0-beta1...v2.0.0-rc1) + +**Enhancements:** +- **[acme]** Improve acme logs. ([#5139](https://github.com/containous/traefik/pull/5139) by [ldez](https://github.com/ldez)) +- **[docker,k8s,k8s/crd,k8s/ingress]** chore: update docker and k8s ([#5174](https://github.com/containous/traefik/pull/5174) by [ldez](https://github.com/ldez)) +- **[k8s,k8s/crd,k8s/ingress]** Correct Kubernetes Ingress and IngressRoute port heuristic for choosing HTTPS ([#5167](https://github.com/containous/traefik/pull/5167) by [seh](https://github.com/seh)) +- **[k8s,k8s/ingress]** Add TLS-enabled Router ([#5162](https://github.com/containous/traefik/pull/5162) by [dtomcej](https://github.com/dtomcej)) +- **[middleware,provider]** Add Feature-Policy header support ([#5156](https://github.com/containous/traefik/pull/5156) by [dtomcej](https://github.com/dtomcej)) +- **[middleware]** Add rate limiter, rename maxConn into inFlightReq ([#5246](https://github.com/containous/traefik/pull/5246) by [mpl](https://github.com/mpl)) +- **[server]** WeightedRoundRobin load balancer ([#5237](https://github.com/containous/traefik/pull/5237) by [juliens](https://github.com/juliens)) +- **[server]** Adds mirroring service ([#5251](https://github.com/containous/traefik/pull/5251) by [juliens](https://github.com/juliens)) +- **[server]** Add support proxyprotocol v2 ([#4755](https://github.com/containous/traefik/pull/4755) by [c0va23](https://github.com/c0va23)) +- **[webui]** Add a new dashboard page ([#5249](https://github.com/containous/traefik/pull/5249) by [Basgrani](https://github.com/Basgrani)) +- **[webui]** Add doc and version in navbar ([#5137](https://github.com/containous/traefik/pull/5137) by [Slashgear](https://github.com/Slashgear)) +- **[webui]** Use components to split Home concerns ([#5136](https://github.com/containous/traefik/pull/5136) by [Slashgear](https://github.com/Slashgear)) +- Bump x/sys to support Risc-V architecture ([#5245](https://github.com/containous/traefik/pull/5245) by [carlosedp](https://github.com/carlosedp)) + +**Bug fixes:** +- **[cli]** Apply the case of the CLI flags for the configuration ([#5153](https://github.com/containous/traefik/pull/5153) by [jbdoumenjou](https://github.com/jbdoumenjou)) +- **[metrics]** Fix prometheus metrics ([#5152](https://github.com/containous/traefik/pull/5152) by [mmatur](https://github.com/mmatur)) +- **[middleware]** Fix `url.Parse` due to go1.12.8 changes. ([#5207](https://github.com/containous/traefik/pull/5207) by [ldez](https://github.com/ldez)) +- Ensure WaitGroup.Done() is always called ([#5026](https://github.com/containous/traefik/pull/5026) by [bsdelf](https://github.com/bsdelf)) + +**Documentation:** +- **[acme,docker]** Add a docker-compose & let's encrypt user-guide ([#5121](https://github.com/containous/traefik/pull/5121) by [pbenefice](https://github.com/pbenefice)) +- **[acme,docker]** Removed extra colon before the 8080 docker port ([#5209](https://github.com/containous/traefik/pull/5209) by [fairwood136](https://github.com/fairwood136)) +- **[acme,k8s/crd]** Fix: CRD user guide ([#5244](https://github.com/containous/traefik/pull/5244) by [ldez](https://github.com/ldez)) +- **[acme]** Fix acme example ([#5130](https://github.com/containous/traefik/pull/5130) by [jamct](https://github.com/jamct)) +- **[middleware]** docker-compose labels require $'s to be escaped ([#5225](https://github.com/containous/traefik/pull/5225) by [Makeshift](https://github.com/Makeshift)) +- AML indent for domains under TLS documentation section ([#5173](https://github.com/containous/traefik/pull/5173) by [edvincent](https://github.com/edvincent)) +- Fix malformed rule ([#5133](https://github.com/containous/traefik/pull/5133) by [dtomcej](https://github.com/dtomcej)) +- doc: improve examples. ([#5132](https://github.com/containous/traefik/pull/5132) by [ldez](https://github.com/ldez)) + +**Misc:** +- Cherry pick v1.7 into v2.0 ([#5192](https://github.com/containous/traefik/pull/5192) by [ldez](https://github.com/ldez)) + +## [v1.7.13](https://github.com/containous/traefik/tree/v1.7.13) (2019-08-07) +[All Commits](https://github.com/containous/traefik/compare/v1.7.12...v1.7.13) + +**Bug fixes:** +- **[acme]** Update lego ([#5166](https://github.com/containous/traefik/pull/5166) by [dabeck](https://github.com/dabeck)) +- **[consulcatalog]** warning should not be a fail status ([#4537](https://github.com/containous/traefik/pull/4537) by [saez0pub](https://github.com/saez0pub)) +- **[docker]** Update docker api version ([#4909](https://github.com/containous/traefik/pull/4909) by [dtomcej](https://github.com/dtomcej)) +- **[dynamodb]** Use dynamodbav tags to override json tags. ([#5002](https://github.com/containous/traefik/pull/5002) by [ldez](https://github.com/ldez)) +- **[healthcheck]** Wrr loadbalancer honors old weight on recovered servers ([#5051](https://github.com/containous/traefik/pull/5051) by [DougWagner](https://github.com/DougWagner)) +- **[k8s]** Check for multiport services on Global Backend Ingress ([#5021](https://github.com/containous/traefik/pull/5021) by [dtomcej](https://github.com/dtomcej)) +- **[logs]** Allows logs to use local time zone instead of UTC ([#4954](https://github.com/containous/traefik/pull/4954) by [dduportal](https://github.com/dduportal)) +- **[middleware]** Clear TLS client headers if TLSMutualAuth is optional ([#4963](https://github.com/containous/traefik/pull/4963) by [stffabi](https://github.com/stffabi)) +- **[tls]** Add missing KeyUsages for default generated certificate ([#5150](https://github.com/containous/traefik/pull/5150) by [dtomcej](https://github.com/dtomcej)) + +**Documentation:** +- **[acme]** Fixed doc link for AlibabaCloud ([#5109](https://github.com/containous/traefik/pull/5109) by [ddymko](https://github.com/ddymko)) +- **[docker]** Add example for CLI ([#5131](https://github.com/containous/traefik/pull/5131) by [alvarezbruned](https://github.com/alvarezbruned)) +- **[docker]** Use the latest stable version of traefik in the docs ([#4927](https://github.com/containous/traefik/pull/4927) by [kolaente](https://github.com/kolaente)) +- **[logs]** Update documentation to clarify the default format for logs ([#4953](https://github.com/containous/traefik/pull/4953) by [dduportal](https://github.com/dduportal)) +- **[rancher]** Add remarks about Rancher 2 ([#4999](https://github.com/containous/traefik/pull/4999) by [ldez](https://github.com/ldez)) +- **[tls]** Fixes the TLS Mutual Authentication documentation ([#5085](https://github.com/containous/traefik/pull/5085) by [jbdoumenjou](https://github.com/jbdoumenjou)) +- Format YAML example on user guide ([#5067](https://github.com/containous/traefik/pull/5067) by [gurayyildirim](https://github.com/gurayyildirim)) +- Update Slack support channel references to Discourse community forum ([#5014](https://github.com/containous/traefik/pull/5014) by [dduportal](https://github.com/dduportal)) +- Updating Service Fabric documentation ([#5160](https://github.com/containous/traefik/pull/5160) by [gheibia](https://github.com/gheibia)) +- Improve API / Dashboard wording in documentation ([#4929](https://github.com/containous/traefik/pull/4929) by [dduportal](https://github.com/dduportal)) + ## [v2.0.0-beta1](https://github.com/containous/traefik/tree/v2.0.0-beta1) (2019-07-19) [All Commits](https://github.com/containous/traefik/compare/v2.0.0-alpha8...v2.0.0-beta1) diff --git a/Gopkg.lock b/Gopkg.lock deleted file mode 100644 index e01810680..000000000 --- a/Gopkg.lock +++ /dev/null @@ -1,2402 +0,0 @@ -# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. - - -[[projects]] - digest = "1:f8ad8a53fa865a70efbe215b0ca34735523f50ea39e0efde319ab6fc80089b44" - name = "cloud.google.com/go" - packages = ["compute/metadata"] - pruneopts = "NUT" - revision = "056a55f54a6cc77b440b31a56a5e7c3982d32811" - version = "v0.22.0" - -[[projects]] - digest = "1:59f6c2fd10ad014d2907eaa48a19070d5e7af35624328a4fbbf93b7b1c4a19e8" - name = "github.com/Azure/azure-sdk-for-go" - packages = [ - "services/dns/mgmt/2017-09-01/dns", - "version", - ] - pruneopts = "NUT" - revision = "068ec4d616be5b2175509bf1fb3e4c8ea160d5c8" - version = "v15.0.1" - -[[projects]] - branch = "master" - digest = "1:81f8c061c3d18ed1710957910542bc17d2b789c6cd19e0f654c30b35fd255ca5" - name = "github.com/Azure/go-ansiterm" - packages = [ - ".", - "winterm", - ] - pruneopts = "NUT" - revision = "d6e3b3328b783f23731bc4d058875b0371ff8109" - -[[projects]] - digest = "1:2526235ff8cae0162b34e8af3779621de71b3a020dead9bcce74d3f43a18c988" - name = "github.com/Azure/go-autorest" - packages = [ - "autorest", - "autorest/adal", - "autorest/azure", - "autorest/azure/auth", - "autorest/date", - "autorest/to", - ] - pruneopts = "NUT" - revision = "9ad9326b278af8fa5cc67c30c0ce9a58cc0862b2" - version = "v10.6.0" - -[[projects]] - branch = "master" - digest = "1:be3ccd9f881604e4dd6d15cccfa126aa309232f0ba075ae5f92d3ef729a62758" - name = "github.com/BurntSushi/toml" - packages = ["."] - pruneopts = "NUT" - revision = "a368813c5e648fee92e5f6c30e3944ff9d5e8895" - -[[projects]] - digest = "1:be4a03871fbc5250d19bcbc2d2b21c3c58fd97b048de64ec1ff4c8e3890d4f1b" - name = "github.com/ExpediaDotCom/haystack-client-go" - packages = ["."] - pruneopts = "NUT" - revision = "e7edbdf53a61a82ed143809088ed582312ff7e36" - version = "0.2.3" - -[[projects]] - digest = "1:ab7fee312bbdc8070d0325d841de8704cc78bf032b076200f1458659b74b8ed6" - name = "github.com/JamesClonk/vultr" - packages = ["lib"] - pruneopts = "NUT" - revision = "2fd0705ce648e602e6c9c57329a174270a4f6688" - -[[projects]] - digest = "1:25870183293a3fb61cc9afd060a61d63a486f091db72af01a8ea3449f5ca530d" - name = "github.com/Masterminds/goutils" - packages = ["."] - pruneopts = "NUT" - revision = "41ac8693c5c10a92ea1ff5ac3a7f95646f6123b0" - version = "v1.1.0" - -[[projects]] - digest = "1:0ce2a409217f52078c6b8642993deb1025940cded6d5054047c1d5c7379f753c" - name = "github.com/Masterminds/semver" - packages = ["."] - pruneopts = "NUT" - revision = "59c29afe1a994eacb71c833025ca7acf874bb1da" - version = "v1.2.2" - -[[projects]] - digest = "1:876a1121171c083c4e3a4789683d02a40c0f644c8190da521d15b59799f556d6" - name = "github.com/Masterminds/sprig" - packages = ["."] - pruneopts = "NUT" - revision = "9f8fceff796fb9f4e992cd2bece016be0121ab74" - version = "2.19.0" - -[[projects]] - digest = "1:915c86626dfd65f8105c48b2972d29f34fd77ff16b31157147cb8ebbddeebbe3" - name = "github.com/Microsoft/go-winio" - packages = ["."] - pruneopts = "NUT" - revision = "f533f7a102197536779ea3a8cb881d639e21ec5a" - version = "v0.4.2" - -[[projects]] - digest = "1:6b6d999be55cc0e0704ed0ac4532175f1f71639fbda6d143dc86ac5a5d3bc87f" - name = "github.com/Microsoft/hcsshim" - packages = ["osversion"] - pruneopts = "NUT" - revision = "f92b8fb9c92e17da496af5a69e3ee13fbe9916e1" - version = "v0.8.6" - -[[projects]] - branch = "master" - digest = "1:d484472e9af62758e3963ee4d8112d5da58cd61833d71e3c1d25165a96d4518a" - name = "github.com/NYTimes/gziphandler" - packages = ["."] - pruneopts = "NUT" - revision = "289a3b81f5aedc99f8d6eb0f67827c142f1310d8" - -[[projects]] - branch = "master" - digest = "1:a4068a93355ba3cff0a719425713123d23c90010cb4d023b40c679a22465736d" - name = "github.com/OpenDNS/vegadns2client" - packages = ["."] - pruneopts = "NUT" - revision = "a3fa4a771d87bda2514a90a157e1fed1b6897d2e" - -[[projects]] - digest = "1:e3fc14e683e391975da7c151bd49b968977a6d83244dda5d0a5d0f171a1c23fd" - name = "github.com/Shopify/sarama" - packages = ["."] - pruneopts = "NUT" - revision = "70f6a705d4a17af059acbc6946fb2bd30762acd7" - -[[projects]] - digest = "1:bad93311d7294e3916fd50a744e5185afcbe64716dde7734353ed0ccf96b6f14" - name = "github.com/VividCortex/gohistogram" - packages = ["."] - pruneopts = "NUT" - revision = "51564d9861991fb0ad0f531c99ef602d0f9866e6" - version = "v1.0.0" - -[[projects]] - branch = "containous-fork" - digest = "1:265000efd882e993b73fec0dcb0c24f0c4d5bd18a9e3a6ed7fb7db1682f47e16" - name = "github.com/abbot/go-http-auth" - packages = ["."] - pruneopts = "NUT" - revision = "65b0cdae8d7fe5c05c7430e055938ef6d24a66c9" - source = "github.com/containous/go-http-auth" - -[[projects]] - branch = "master" - digest = "1:d37d0fa13c422a0b85981fe42ff8f176885921294cf0c3ce585c160669cc32bb" - name = "github.com/abronan/valkeyrie" - packages = ["store"] - pruneopts = "NUT" - revision = "063d875e3c5fd734fa2aa12fac83829f62acfc70" - -[[projects]] - digest = "1:47071ecf8d840dd357ede1b2aed46576bdd0a866adecef3c9e85a00db9672202" - name = "github.com/akamai/AkamaiOPEN-edgegrid-golang" - packages = [ - "client-v1", - "configdns-v1", - "edgegrid", - "jsonhooks-v1", - ] - pruneopts = "NUT" - revision = "1471ce9c14c6d8c007516e129262962a628fecdf" - version = "v0.7.3" - -[[projects]] - digest = "1:823e87ae25170339e2bfd1d6f7c2e27554c6bb5655f91c67b37bd5be45bb6b32" - name = "github.com/aliyun/alibaba-cloud-sdk-go" - packages = [ - "sdk", - "sdk/auth", - "sdk/auth/credentials", - "sdk/auth/signers", - "sdk/endpoints", - "sdk/errors", - "sdk/requests", - "sdk/responses", - "sdk/utils", - "services/alidns", - ] - pruneopts = "NUT" - revision = "cad214d7d71fba7883fcf3b7e550ba782c15b400" - version = "1.27.7" - -[[projects]] - digest = "1:b39cf81d5f440b9c0757a25058432d33af867e5201109bf53621356d9dab4b73" - name = "github.com/apache/thrift" - packages = ["lib/go/thrift"] - pruneopts = "NUT" - revision = "384647d290e2e4a55a14b1b7ef1b7e66293a2c33" - version = "v0.12.0" - -[[projects]] - branch = "master" - digest = "1:35d20140aeb30f9ae04b481f20020fd06c9742339a64a55c1a5a5bfddd740564" - name = "github.com/armon/go-proxyproto" - packages = ["."] - pruneopts = "NUT" - revision = "48572f11356f1843b694f21a290d4f1006bc5e47" - -[[projects]] - digest = "1:9991a3fc14d9de52a55cdb5a5f1f237140684eab050251ecfaaafa239a8ab5c9" - name = "github.com/aws/aws-sdk-go" - packages = [ - "aws", - "aws/awserr", - "aws/awsutil", - "aws/client", - "aws/client/metadata", - "aws/corehandlers", - "aws/credentials", - "aws/credentials/ec2rolecreds", - "aws/credentials/endpointcreds", - "aws/credentials/stscreds", - "aws/defaults", - "aws/ec2metadata", - "aws/endpoints", - "aws/request", - "aws/session", - "aws/signer/v4", - "internal/sdkio", - "internal/sdkrand", - "internal/shareddefaults", - "private/protocol", - "private/protocol/json/jsonutil", - "private/protocol/jsonrpc", - "private/protocol/query", - "private/protocol/query/queryutil", - "private/protocol/rest", - "private/protocol/restxml", - "private/protocol/xml/xmlutil", - "service/lightsail", - "service/route53", - "service/sts", - ] - pruneopts = "NUT" - revision = "fad131ddc707880428615dc8bc1587b55fb46d74" - version = "v1.13.54" - -[[projects]] - branch = "master" - digest = "1:cb0535f5823b47df7dcb9768ebb6c000b79ad115472910c70efe93c9ed9b2315" - name = "github.com/beorn7/perks" - packages = ["quantile"] - pruneopts = "NUT" - revision = "4c0e84591b9aa9e6dcfdf3e020114cd81f89d5f9" - -[[projects]] - digest = "1:cdee563173093e5ae7ab2a19c298e0904129719e1919a3c532b7bb0c3398b818" - name = "github.com/cenkalti/backoff" - packages = ["."] - pruneopts = "NUT" - revision = "1e4cf3da559842a91afcb6ea6141451e6c30c618" - version = "v2.1.1" - -[[projects]] - digest = "1:03cfacdc6bfd46007c15786c1ece3fa074f89e5193a292f0f26d9e98c99c7cc2" - name = "github.com/cloudflare/cloudflare-go" - packages = ["."] - pruneopts = "NUT" - revision = "1f9007fbecae20711133c60519338c41cef1ffb4" - version = "v0.8.5" - -[[projects]] - branch = "master" - digest = "1:8ecb89af7dfe3ac401bdb0c9390b134ef96a97e85f732d2b0604fb7b3977839f" - name = "github.com/codahale/hdrhistogram" - packages = ["."] - pruneopts = "NUT" - revision = "3a0bb77429bd3a61596f5e8a3172445844342120" - -[[projects]] - branch = "master" - digest = "1:835fc727705e8cf858ea44ad9bd872ff826d1c6b019598e0f9a64c9b942a947b" - name = "github.com/containerd/continuity" - packages = [ - "fs", - "pathdriver", - "syscallx", - "sysx", - ] - pruneopts = "NUT" - revision = "aaeac12a7ffcd198ae25440a9dff125c2e2703a7" - -[[projects]] - branch = "containous-fork" - digest = "1:9587a8a4fd4f872f2a1983297f144e8cdbc86664482e74bf91f1d6d8e43f7120" - name = "github.com/containous/alice" - packages = ["."] - pruneopts = "NUT" - revision = "d83ebdd94cbdbcd9c6c6a22e1a0cde05e55d9d90" - -[[projects]] - branch = "master" - digest = "1:3a789aa5487458c1fc913b47be763e5906e1524f1143acb8617287866184f9a7" - name = "github.com/containous/mux" - packages = ["."] - pruneopts = "NUT" - revision = "c33f32e268983f989290677351b871b65da75ba5" - -[[projects]] - digest = "1:fa91847d50d3f656fc2d2d608b9749b97d77528e8988ad8001f957640545e91e" - name = "github.com/coreos/go-systemd" - packages = ["daemon"] - pruneopts = "NUT" - revision = "48702e0da86bd25e76cfef347e2adeb434a0d0a6" - version = "v14" - -[[projects]] - branch = "master" - digest = "1:2a7013a7e8cfec93dd725f95ea0c4b390d7d71f8a8bc3dbde05cfc9524ba5ea8" - name = "github.com/cpu/goacmedns" - packages = ["."] - pruneopts = "NUT" - revision = "565ecf2a84df654865cc102705ac160a3b04fc01" - -[[projects]] - digest = "1:a2c1d0e43bd3baaa071d1b9ed72c27d78169b2b269f71c105ac4ba34b1be4a39" - name = "github.com/davecgh/go-spew" - packages = ["spew"] - pruneopts = "NUT" - revision = "346938d642f2ec3594ed81d874461961cd0faa76" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:d3972abc351cd5578e3281d332ac9e7a04dafc6e5af97c064fe396c4f90ee769" - name = "github.com/decker502/dnspod-go" - packages = ["."] - pruneopts = "NUT" - revision = "f33a2c6040fc2550a631de7b3a53bddccdcd73fb" - -[[projects]] - digest = "1:7a6852b35eb5bbc184561443762d225116ae630c26a7c4d90546619f1e7d2ad2" - name = "github.com/dgrijalva/jwt-go" - packages = ["."] - pruneopts = "NUT" - revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" - version = "v3.2.0" - -[[projects]] - branch = "master" - digest = "1:f9adc21a937e5da643ea14a3488cb7506788876737a5e205394e508627a6eec8" - name = "github.com/dimchansky/utfbom" - packages = ["."] - pruneopts = "NUT" - revision = "d2133a1ce379ef6fa992b0514a77146c60db9d1c" - -[[projects]] - digest = "1:e856fc44ab196970612bdc8c15e65ccf92ed8d4ccb3a2e65b88dc240a2fe5d0b" - name = "github.com/dnsimple/dnsimple-go" - packages = ["dnsimple"] - pruneopts = "NUT" - revision = "f5ead9c20763fd925dea1362f2af5d671ed2a459" - version = "v0.21.0" - -[[projects]] - digest = "1:067906552492b3c4a94057ba33279ad1af906a701be3b7d6a92a9478c25fc24f" - name = "github.com/docker/cli" - packages = [ - "cli/command/image/build", - "cli/config", - "cli/config/configfile", - "cli/config/credentials", - "cli/config/types", - "opts", - ] - pruneopts = "NUT" - revision = "5b38d82aa0767e32f53b5821a9a5044f20eeef29" - version = "v19.03.1" - -[[projects]] - digest = "1:26a1d70717dac8c37ae869d86103b9d72b71a6faf383a5e9b5b7e602c9b9743b" - name = "github.com/docker/distribution" - packages = [ - ".", - "digestset", - "metrics", - "reference", - "registry/api/errcode", - "registry/api/v2", - "registry/client", - "registry/client/auth", - "registry/client/auth/challenge", - "registry/client/transport", - "registry/storage/cache", - "registry/storage/cache/memory", - ] - pruneopts = "NUT" - revision = "2461543d988979529609e8cb6fca9ca190dc48da" - version = "v2.7.1" - -[[projects]] - digest = "1:c2ec28361058cb8c28c4a9b9a505fb403e227b1476f24a3006de5135643dd0bb" - name = "github.com/docker/docker" - packages = [ - "api", - "api/types", - "api/types/blkiodev", - "api/types/container", - "api/types/events", - "api/types/filters", - "api/types/image", - "api/types/mount", - "api/types/network", - "api/types/registry", - "api/types/strslice", - "api/types/swarm", - "api/types/swarm/runtime", - "api/types/time", - "api/types/versions", - "api/types/volume", - "builder/dockerignore", - "builder/remotecontext/git", - "client", - "errdefs", - "pkg/archive", - "pkg/fileutils", - "pkg/homedir", - "pkg/idtools", - "pkg/ioutils", - "pkg/jsonmessage", - "pkg/longpath", - "pkg/mount", - "pkg/namesgenerator", - "pkg/pools", - "pkg/progress", - "pkg/stdcopy", - "pkg/streamformatter", - "pkg/stringid", - "pkg/symlink", - "pkg/system", - "pkg/tarsum", - "pkg/term", - "pkg/term/windows", - "pkg/urlutil", - "registry", - "registry/resumable", - ] - pruneopts = "NUT" - revision = "fa8dd90ceb7bcb9d554d27e0b9087ab83e54bd2b" - source = "github.com/docker/engine" - version = "v19.03.1" - -[[projects]] - digest = "1:8866486038791fe65ea1abf660041423954b1f3fb99ea6a0ad8424422e943458" - name = "github.com/docker/docker-credential-helpers" - packages = [ - "client", - "credentials", - ] - pruneopts = "NUT" - revision = "d68f9aeca33f5fd3f08eeae5e9d175edf4e731d1" - version = "v0.6.0" - -[[projects]] - digest = "1:f133477f38c590bdcd6fc534617df17983f7a21e5b686d4a3495abeb21c631ec" - name = "github.com/docker/go-connections" - packages = [ - "nat", - "sockets", - "tlsconfig", - ] - pruneopts = "NUT" - revision = "3ede32e2033de7505e6500d6c868c2b9ed9f169d" - version = "v0.3.0" - -[[projects]] - branch = "master" - digest = "1:c49ecccb8abda39a5a48a99267d6abfdf37f59f1c7fdbcbe04b3b9afc3ab625d" - name = "github.com/docker/go-metrics" - packages = ["."] - pruneopts = "NUT" - revision = "b84716841b82eab644a0c64fc8b42d480e49add5" - -[[projects]] - digest = "1:9d8fe33c2e1aa01c76db67f285ffdb7dbdb5c5d90d9deb296526d67b9798ce7b" - name = "github.com/docker/go-units" - packages = ["."] - pruneopts = "NUT" - revision = "9e638d38cf6977a37a8ea0078f3ee75a7cdb2dd1" - -[[projects]] - branch = "master" - digest = "1:374db732c8336336840f94794cb57aa9bb55d5840e76dae8142a7d15272cc126" - name = "github.com/docker/libcompose" - packages = [ - "config", - "docker", - "docker/auth", - "docker/builder", - "docker/client", - "docker/container", - "docker/ctx", - "docker/image", - "docker/network", - "docker/service", - "docker/volume", - "labels", - "logger", - "lookup", - "project", - "project/events", - "project/options", - "utils", - "version", - "yaml", - ] - pruneopts = "NUT" - revision = "eac9fe1b8b032d757f9e281a19a62195622a5a11" - -[[projects]] - digest = "1:5f4c34ef3ef56be4a7f57cc43d8d219930cbcc82fdff174518703200ad165c0e" - name = "github.com/donovanhide/eventsource" - packages = ["."] - pruneopts = "NUT" - revision = "b8f31a59085e69dd2678cf51840db2ac625cb741" - -[[projects]] - digest = "1:4f0ac2a7cc350b14c72a9de0de046b908482d6f16183c8570ee4d6e17adc6a94" - name = "github.com/eapache/channels" - packages = ["."] - pruneopts = "NUT" - revision = "47238d5aae8c0fefd518ef2bee46290909cf8263" - version = "v1.1.0" - -[[projects]] - digest = "1:08143362be979b087c2c1bae5dde986e988d3d5d4dc661727cbe436411b3f33a" - name = "github.com/eapache/go-resiliency" - packages = ["breaker"] - pruneopts = "NUT" - revision = "b1fe83b5b03f624450823b751b662259ffc6af70" - -[[projects]] - branch = "master" - digest = "1:0b70d299db64766a4ee7128f0f94944f2356ca9d3499c79123dbc3a1d2ba803e" - name = "github.com/eapache/go-xerial-snappy" - packages = ["."] - pruneopts = "NUT" - revision = "bb955e01b9346ac19dc29eb16586c90ded99a98c" - -[[projects]] - digest = "1:0d36a2b325b9e75f8057f7f9fbe778d348d70ba652cb9335485b69d1a5c4e038" - name = "github.com/eapache/queue" - packages = ["."] - pruneopts = "NUT" - revision = "44cc805cf13205b55f69e14bcb69867d1ae92f98" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:d612f023556888f38ccbaf22cde164f88a23619d5877fcd34a707c6b021ae6da" - name = "github.com/elazarl/go-bindata-assetfs" - packages = ["."] - pruneopts = "NUT" - revision = "30f82fa23fd844bd5bb1e5f216db87fd77b5eb43" - -[[projects]] - digest = "1:4304cca260ab815326ca42d9c28fb843342748267034c51963e13f5e54e727d1" - name = "github.com/evanphx/json-patch" - packages = ["."] - pruneopts = "NUT" - revision = "026c730a0dcc5d11f93f1cf1cc65b01247ea7b6f" - version = "v4.5.0" - -[[projects]] - digest = "1:6f26e34204ddad638d25456c6443c2763aa38954558226722c253e08e9f491fa" - name = "github.com/exoscale/egoscale" - packages = ["."] - pruneopts = "NUT" - revision = "0a91ac8209d6a805f259ff881d0c2654221d0346" - version = "v0.14.3" - -[[projects]] - digest = "1:aa3ed0a71c4e66e4ae6486bf97a3f4cab28edc78df2e50c5ad01dc7d91604b88" - name = "github.com/fatih/structs" - packages = ["."] - pruneopts = "NUT" - revision = "4966fc68f5b7593aafa6cbbba2d65ec6e1416047" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:1ccd7321e62f680a988bba496f0f5a9c80410b8104d55b0f6b8ecf84ad328476" - name = "github.com/flynn/go-shlex" - packages = ["."] - pruneopts = "NUT" - revision = "3f9db97f856818214da2e1057f8ad84803971cff" - -[[projects]] - digest = "1:b92ce13c2d8a2b958d600ef1e737f6dea919e53c931477d2cb5109da71377b81" - name = "github.com/gambol99/go-marathon" - packages = ["."] - pruneopts = "NUT" - revision = "99a156b96fb2f9dbe6465affa51bbdccdd37174d" - -[[projects]] - digest = "1:d82b2dc81c551e7c15f31523a2cc8ee9121b39cfbf63174d98a0bc8edf2d3c5e" - name = "github.com/go-acme/lego" - packages = [ - "acme", - "acme/api", - "acme/api/internal/nonces", - "acme/api/internal/secure", - "acme/api/internal/sender", - "certcrypto", - "certificate", - "challenge", - "challenge/dns01", - "challenge/http01", - "challenge/resolver", - "challenge/tlsalpn01", - "lego", - "log", - "platform/config/env", - "platform/wait", - "providers/dns", - "providers/dns/acmedns", - "providers/dns/alidns", - "providers/dns/auroradns", - "providers/dns/azure", - "providers/dns/bindman", - "providers/dns/bluecat", - "providers/dns/cloudflare", - "providers/dns/cloudns", - "providers/dns/cloudns/internal", - "providers/dns/cloudxns", - "providers/dns/cloudxns/internal", - "providers/dns/conoha", - "providers/dns/conoha/internal", - "providers/dns/designate", - "providers/dns/digitalocean", - "providers/dns/dnsimple", - "providers/dns/dnsmadeeasy", - "providers/dns/dnsmadeeasy/internal", - "providers/dns/dnspod", - "providers/dns/dode", - "providers/dns/dreamhost", - "providers/dns/duckdns", - "providers/dns/dyn", - "providers/dns/easydns", - "providers/dns/exec", - "providers/dns/exoscale", - "providers/dns/fastdns", - "providers/dns/gandi", - "providers/dns/gandiv5", - "providers/dns/gcloud", - "providers/dns/glesys", - "providers/dns/godaddy", - "providers/dns/hostingde", - "providers/dns/httpreq", - "providers/dns/iij", - "providers/dns/inwx", - "providers/dns/joker", - "providers/dns/lightsail", - "providers/dns/linode", - "providers/dns/linodev4", - "providers/dns/mydnsjp", - "providers/dns/namecheap", - "providers/dns/namedotcom", - "providers/dns/netcup", - "providers/dns/netcup/internal", - "providers/dns/nifcloud", - "providers/dns/nifcloud/internal", - "providers/dns/ns1", - "providers/dns/oraclecloud", - "providers/dns/otc", - "providers/dns/ovh", - "providers/dns/pdns", - "providers/dns/rackspace", - "providers/dns/rfc2136", - "providers/dns/route53", - "providers/dns/sakuracloud", - "providers/dns/selectel", - "providers/dns/selectel/internal", - "providers/dns/stackpath", - "providers/dns/transip", - "providers/dns/vegadns", - "providers/dns/vscale", - "providers/dns/vscale/internal", - "providers/dns/vultr", - "providers/dns/zoneee", - "registration", - ] - pruneopts = "NUT" - revision = "01903cdfb9869df45cf5274c53226823a2532f2d" - version = "v2.6.0" - -[[projects]] - branch = "fork-containous" - digest = "1:8292ab171d5fe91cd39fa4888157dd7bb485b07928231b06ffed4ecaae59ec39" - name = "github.com/go-check/check" - packages = ["."] - pruneopts = "NUT" - revision = "ca0bf163426aa183d03fd4949101785c0347f273" - source = "github.com/containous/check" - -[[projects]] - digest = "1:ea1d5bfdb4ec5c2ee48c97865e6de1a28fa8c4849a3f56b27d521aa619038e06" - name = "github.com/go-errors/errors" - packages = ["."] - pruneopts = "NUT" - revision = "a6af135bd4e28680facf08a3d206b454abc877a4" - version = "v1.0.1" - -[[projects]] - digest = "1:5e92676b56ce4c69edf9ee1f6343c56f637e30af11b9d8b5edd1b6530f3fbc3d" - name = "github.com/go-ini/ini" - packages = ["."] - pruneopts = "NUT" - revision = "6ed8d5f64cd79a498d1f3fab5880cc376ce41bbe" - version = "v1.41.0" - -[[projects]] - digest = "1:bed40e7a58536b77890de9fc4911a1322a31cd2495bbcad8446d182063eb1ae4" - name = "github.com/go-kit/kit" - packages = [ - "log", - "metrics", - "metrics/dogstatsd", - "metrics/generic", - "metrics/influx", - "metrics/internal/lv", - "metrics/internal/ratemap", - "metrics/multi", - "metrics/statsd", - "util/conn", - ] - pruneopts = "NUT" - revision = "150a65a7ec6156b4b640c1fd55f26fd3d475d656" - version = "v0.9.0" - -[[projects]] - digest = "1:341a7df38da99fe91ed40e4008c13cc5d02dcc98ed1a094360cb7d5df26d6d26" - name = "github.com/go-logfmt/logfmt" - packages = ["."] - pruneopts = "NUT" - revision = "390ab7935ee28ec6b286364bba9b4dd6410cb3d5" - version = "v0.3.0" - -[[projects]] - digest = "1:00f1b1d722a012f54670ecc09ee92557d7314bfd9152a085ce91933c1c14b026" - name = "github.com/go-resty/resty" - packages = ["."] - pruneopts = "NUT" - revision = "d4920dcf5b7689548a6db640278a9b35a5b48ec6" - version = "v1.9.1" - -[[projects]] - digest = "1:6689652ec1f6e30455551da19c707f2bfac75e4df5c7bbe3f0ad7b49b9aa2cfc" - name = "github.com/gogo/protobuf" - packages = [ - "proto", - "sortkeys", - ] - pruneopts = "NUT" - revision = "909568be09de550ed094403c2bf8a261b5bb730a" - version = "v0.3" - -[[projects]] - digest = "1:2d0636a8c490d2272dd725db26f74a537111b99b9dbdda0d8b98febe63702aa4" - name = "github.com/golang/protobuf" - packages = [ - "proto", - "ptypes", - "ptypes/any", - "ptypes/duration", - "ptypes/timestamp", - ] - pruneopts = "NUT" - revision = "b5d812f8a3706043e23a9cd5babf2e5423744d30" - version = "v1.3.1" - -[[projects]] - branch = "master" - digest = "1:9413ddbde906f91f062fda0dfa9a7cff43458cd1b2282c0fa25c61d89300b116" - name = "github.com/golang/snappy" - packages = ["."] - pruneopts = "NUT" - revision = "553a641470496b2327abcac10b36396bd98e45c9" - -[[projects]] - digest = "1:bf40199583e5143d1472fc34d10d6f4b69d97572142acf343b3e43136da40823" - name = "github.com/google/go-cmp" - packages = [ - "cmp", - "cmp/internal/diff", - "cmp/internal/flags", - "cmp/internal/function", - "cmp/internal/value", - ] - pruneopts = "NUT" - revision = "6f77996f0c42f7b84e5a2b252227263f93432e9b" - version = "v0.3.0" - -[[projects]] - digest = "1:7e49319ff995ba7b1c89845b02908d609db90879192e0f24d6338fd715043e50" - name = "github.com/google/go-github" - packages = ["github"] - pruneopts = "NUT" - revision = "fe7d11f8add400587b6718d9f39a62e42cb04c28" - -[[projects]] - branch = "master" - digest = "1:a63cff6b5d8b95638bfe300385d93b2a6d9d687734b863da8e09dc834510a690" - name = "github.com/google/go-querystring" - packages = ["query"] - pruneopts = "NUT" - revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a" - -[[projects]] - digest = "1:213c59d423da6fade65d445133228942c3916925204f2f78caec6ae6755f1809" - name = "github.com/google/gofuzz" - packages = ["."] - pruneopts = "NUT" - revision = "bbcb9da2d746f8bdbd6a936686a0a6067ada0ec5" - -[[projects]] - digest = "1:1bb197a3b5db4e06e00b7560f8e89836c486627f2a0338332ed37daa003d259e" - name = "github.com/google/uuid" - packages = ["."] - pruneopts = "NUT" - revision = "064e2069ce9c359c118179501254f67d7d37ba24" - version = "0.2" - -[[projects]] - digest = "1:3d7c1446fc5c710351b246c0dc6700fae843ca27f5294d0bd9f68bab2a810c44" - name = "github.com/googleapis/gnostic" - packages = [ - "OpenAPIv2", - "compiler", - "extensions", - ] - pruneopts = "NUT" - revision = "ee43cbb60db7bd22502942cccbc39059117352ab" - version = "v0.1.0" - -[[projects]] - branch = "master" - digest = "1:31a16fabf629bd7e0e6ad92939f31847cc57f3fe08898d3c31333da817196c72" - name = "github.com/gophercloud/gophercloud" - packages = [ - ".", - "openstack", - "openstack/dns/v2/recordsets", - "openstack/dns/v2/zones", - "openstack/identity/v2/tenants", - "openstack/identity/v2/tokens", - "openstack/identity/v3/tokens", - "openstack/utils", - "pagination", - ] - pruneopts = "NUT" - revision = "892256c468586d66a6864daeee52441afc0f7e38" - -[[projects]] - digest = "1:dbd86d229eacaa86a98b10f8fb3e3fc69a1913e0f4e010e7cc1f92bf12edca92" - name = "github.com/gorilla/context" - packages = ["."] - pruneopts = "NUT" - revision = "215affda49addc4c8ef7e2534915df2c8c35c6cd" - -[[projects]] - digest = "1:e59480f8a4ce09dd48cc75c0d20ea09f4231484d8e07a5d7f4a068c886c0e166" - name = "github.com/gorilla/mux" - packages = ["."] - pruneopts = "NUT" - revision = "e444e69cbd2e2e3e0749a2f3c717cec491552bbf" - -[[projects]] - branch = "master" - digest = "1:4a0c072e44da763409da72d41492373a034baf2e6d849c76d239b4abdfbb6c49" - name = "github.com/gorilla/websocket" - packages = ["."] - pruneopts = "NUT" - revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d" - -[[projects]] - digest = "1:071be2dd0487f3a8a150c06f3cbd87e3ddcfb9a443bfe78ebe7565408ee5eafa" - name = "github.com/gravitational/trace" - packages = ["."] - pruneopts = "NUT" - revision = "0bd13642feb8f57acc0d8e3a568edc34e05a74b9" - version = "1.1.3" - -[[projects]] - digest = "1:f7b3db9cb74d13f6a7cf84b3801e68585745eacaf7d40cc10ecc4734c30503d3" - name = "github.com/hashicorp/go-version" - packages = ["."] - pruneopts = "NUT" - revision = "03c5bf6be031b6dd45afec16b1cf94fc8938bc77" - -[[projects]] - branch = "master" - digest = "1:13e2fa5735a82a5fb044f290cfd0dba633d1c5e516b27da0509e0dbb3515a18e" - name = "github.com/hashicorp/golang-lru" - packages = [ - ".", - "simplelru", - ] - pruneopts = "NUT" - revision = "0fb14efe8c47ae851c0034ed7a448854d3d34cf3" - -[[projects]] - digest = "1:dc54242755f5b6721dd880843de6e45fe234838ea9149ec8249951880fd5802f" - name = "github.com/huandu/xstrings" - packages = ["."] - pruneopts = "NUT" - revision = "f02667b379e2fb5916c3cda2cf31e0eb885d79f8" - version = "v1.2.0" - -[[projects]] - branch = "master" - digest = "1:c45e4f1755487478216e06437e161d56299d963282ce109555091bc4c7a57343" - name = "github.com/iij/doapi" - packages = [ - ".", - "protocol", - ] - pruneopts = "NUT" - revision = "8803795a9b7b938fa88ddbd63a77893beee14cd8" - -[[projects]] - digest = "1:9b9758cc00f332bd95147c2e343dccd662ab02cb716a50a89e6b6563ea2df314" - name = "github.com/imdario/mergo" - packages = ["."] - pruneopts = "NUT" - revision = "7fe0c75c13abdee74b09fcacef5ea1c6bba6a874" - version = "0.2.4" - -[[projects]] - branch = "master" - digest = "1:50708c8fc92aec981df5c446581cf9f90ba9e2a5692118e0ce75d4534aaa14a2" - name = "github.com/influxdata/influxdb1-client" - packages = [ - "models", - "pkg/escape", - "v2", - ] - pruneopts = "NUT" - revision = "8ff2fc3824fcb533795f9a2f233275f0bb18d6c5" - -[[projects]] - digest = "1:78efd72f12ed0244e5fbe82bd0ecdbaf3e21402ee9176525ef1138a2fc0d3b17" - name = "github.com/instana/go-sensor" - packages = ["."] - pruneopts = "NUT" - revision = "493edb42228321483dd4d59ade71ca93fa89d66b" - version = "1.4.12" - -[[projects]] - digest = "1:ac6d01547ec4f7f673311b4663909269bfb8249952de3279799289467837c3cc" - name = "github.com/jmespath/go-jmespath" - packages = ["."] - pruneopts = "NUT" - revision = "0b12d6b5" - -[[projects]] - digest = "1:273d270076cfc02c2d481b187203ebb3891825f46fe78b925141a22631c52503" - name = "github.com/jonboulle/clockwork" - packages = ["."] - pruneopts = "NUT" - revision = "72f9bd7c4e0c2a40055ab3d0f09654f730cce982" - -[[projects]] - digest = "1:4e903242fe176238aaa469f59d7035f5abf2aa9acfefb8964ddd203651b574e9" - name = "github.com/json-iterator/go" - packages = ["."] - pruneopts = "NUT" - revision = "0ff49de124c6f76f8494e194af75bde0f1a49a29" - version = "v1.1.6" - -[[projects]] - digest = "1:8b3234b10eacd5edea45bf0c13a585b608749da23f94aaf29b46d9ef8a8babf4" - name = "github.com/juju/ratelimit" - packages = ["."] - pruneopts = "NUT" - revision = "59fac5042749a5afb9af70e813da1dd5474f0167" - version = "1.0.1" - -[[projects]] - branch = "master" - digest = "1:ec142582cd3bb5cc29a2bc7181a6e67367b90b19f6a957ce506dcd7d1500bf95" - name = "github.com/kolo/xmlrpc" - packages = ["."] - pruneopts = "NUT" - revision = "16bdd962781df9696f40cc2bab924f1a855a7f89" - -[[projects]] - branch = "master" - digest = "1:c8a452cc8dd4ef9f857570ce2be31ca257a0928bf3c2b08cd7e11972b985c6d7" - name = "github.com/konsorten/go-windows-terminal-sequences" - packages = ["."] - pruneopts = "NUT" - revision = "b729f2633dfe35f4d1d8a32385f6685610ce1cb5" - -[[projects]] - branch = "master" - digest = "1:f91bb67d051a94cf6ab2cf07eee0550432afc31655838d42cdec258db4b348f0" - name = "github.com/kr/logfmt" - packages = ["."] - pruneopts = "NUT" - revision = "b84e30acd515aadc4b783ad4ff83aff3299bdfe0" - -[[projects]] - digest = "1:1082aeb059ff66b4fb6da53f9e7591726c6a81901f05ce48a470091784b23914" - name = "github.com/labbsr0x/bindman-dns-webhook" - packages = [ - "src/client", - "src/types", - ] - pruneopts = "NUT" - revision = "234ca2a50eebc2095f42a884709a6e9013366d86" - version = "v1.0.0" - -[[projects]] - branch = "master" - digest = "1:ad2a63b2d6dfe7d66bf14c01f1171a3951abef6e0fb136170359c3f7c4f51615" - name = "github.com/labbsr0x/goh" - packages = ["gohclient"] - pruneopts = "NUT" - revision = "60aa50bcbca768de1b8d37d7185daab4cf023ed2" - -[[projects]] - branch = "master" - digest = "1:5a96e1f04259484b3dd183ca95d1e7bff768b1bab36c530e308a8d56243b50c7" - name = "github.com/libkermit/compose" - packages = [ - ".", - "check", - ] - pruneopts = "NUT" - revision = "c04e39c026ad1c76c027d6780150c8f7dec0a610" - -[[projects]] - branch = "master" - digest = "1:7f3a571fba08dc670f9b3acf24caff7d2c8c00aafde10fe3a817ec3147a7fda2" - name = "github.com/libkermit/docker" - packages = ["."] - pruneopts = "NUT" - revision = "e6674d32b80712b563ed8a0187af2bc93448b82f" - -[[projects]] - branch = "master" - digest = "1:1987b554ea37321e1275269ca47cb56fd1f6e670492805ef196bebe4b6ae29a3" - name = "github.com/libkermit/docker-check" - packages = ["."] - pruneopts = "NUT" - revision = "1113af38e5916529ad7317b0fe12e273e6e92af5" - -[[projects]] - digest = "1:111ff5a09a32895248270bfaef9b8b6ac163a8cde9cdd603fed64b3e4b59e8ab" - name = "github.com/linode/linodego" - packages = ["."] - pruneopts = "NUT" - revision = "d0d31d8ca62fa3f7e4526ca0ce95de81e4ed001e" - version = "v0.5.1" - -[[projects]] - digest = "1:8520e78cbe9878f6bf0cfdcfaed5761cd575b3568c260a1c891ac1f5c5c6a726" - name = "github.com/looplab/fsm" - packages = ["."] - pruneopts = "NUT" - revision = "84b5307469f859464403f80919467950a79de1b1" - version = "v0.1.0" - -[[projects]] - digest = "1:196b0d7580e898df15a7cc5371cbfe2b8e22904f5c6c883ed5db0130e551c8fb" - name = "github.com/mailgun/minheap" - packages = ["."] - pruneopts = "NUT" - revision = "7c28d80e2ada649fc8ab1a37b86d30a2633bd47c" - -[[projects]] - branch = "master" - digest = "1:bd9618077195021656e90e536f0bde5a80aefe4f86791946df83ef6620b9deee" - name = "github.com/mailgun/multibuf" - packages = ["."] - pruneopts = "NUT" - revision = "565402cd71fbd9c12aa7e295324ea357e970a61e" - -[[projects]] - digest = "1:2d880776e6ef411cc199a4c9812daeb54ba887995573c4083015a8d8e64c42a7" - name = "github.com/mailgun/timetools" - packages = ["."] - pruneopts = "NUT" - revision = "7e6055773c5137efbeb3bd2410d705fe10ab6bfd" - -[[projects]] - branch = "master" - digest = "1:ad4115a2ef97a6d9007fb7cae7c639844944993d7426ff8d864127ba47f4cec9" - name = "github.com/mailgun/ttlmap" - packages = ["."] - pruneopts = "NUT" - revision = "c1c17f74874f2a5ea48bfb06b5459d4ef2689749" - -[[projects]] - branch = "master" - digest = "1:5985ef4caf91ece5d54817c11ea25f182697534f8ae6521eadcd628c142ac4b6" - name = "github.com/matttproud/golang_protobuf_extensions" - packages = ["pbutil"] - pruneopts = "NUT" - revision = "c12348ce28de40eed0136aa2b644d0ee0650e56c" - -[[projects]] - digest = "1:b83995756f9b1a24c518d40052d80f524f0a9024ee0479d8a8e91ec2548074d1" - name = "github.com/miekg/dns" - packages = ["."] - pruneopts = "NUT" - revision = "7586a3cbe8ccfc63f82de3ab2ceeb08c9939af72" - version = "v1.1.1" - -[[projects]] - branch = "master" - digest = "1:1e5a8bf6fb005f1808852ad1a4bedb7b4b3291af90dec12c4c9e4a955a42c9b2" - name = "github.com/mitchellh/copystructure" - packages = ["."] - pruneopts = "NUT" - revision = "d23ffcb85de31694d6ccaa23ccb4a03e55c1303f" - -[[projects]] - branch = "master" - digest = "1:b62c4f18ad6eb454ac5253e7791ded3d7867330015ca4b37b6336e57f514585e" - name = "github.com/mitchellh/go-homedir" - packages = ["."] - pruneopts = "NUT" - revision = "b8bc1bf767474819792c23f32d8286a45736f1c6" - -[[projects]] - branch = "master" - digest = "1:e34decedbcec12332c5836d16a6838f864e0b43c5b4f9aa9d9a85101015f87c2" - name = "github.com/mitchellh/hashstructure" - packages = ["."] - pruneopts = "NUT" - revision = "2bca23e0e452137f789efbc8610126fd8b94f73b" - -[[projects]] - digest = "1:a45ae66dea4c899d79fceb116accfa1892105c251f0dcd9a217ddc276b42ec68" - name = "github.com/mitchellh/mapstructure" - packages = ["."] - pruneopts = "NUT" - revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe" - version = "v1.1.2" - -[[projects]] - branch = "master" - digest = "1:44e35ced240c6d8316dc8d604a73774ab052d40ebe636fd8f2ba5934f6329034" - name = "github.com/mitchellh/reflectwalk" - packages = ["."] - pruneopts = "NUT" - revision = "63d60e9d0dbc60cf9164e6510889b0db6683d98c" - -[[projects]] - digest = "1:2f42fa12d6911c7b7659738758631bec870b7e9b4c6be5444f963cdcfccc191f" - name = "github.com/modern-go/concurrent" - packages = ["."] - pruneopts = "NUT" - revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" - version = "1.0.3" - -[[projects]] - digest = "1:c6aca19413b13dc59c220ad7430329e2ec454cc310bc6d8de2c7e2b93c18a0f6" - name = "github.com/modern-go/reflect2" - packages = ["."] - pruneopts = "NUT" - revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" - version = "1.0.1" - -[[projects]] - branch = "master" - digest = "1:946bf1e858c4884cc82907463b0579dfd3b84e1b541bd49808d2bcfcb9452be0" - name = "github.com/morikuni/aec" - packages = ["."] - pruneopts = "NUT" - revision = "39771216ff4c63d11f5e604076f9c45e8be1067b" - -[[projects]] - digest = "1:7bb97a5f80a2429fa605e176e16cf682cbb5ac681f421a06efb4e3b8efae6e5f" - name = "github.com/mvdan/xurls" - packages = ["."] - pruneopts = "NUT" - revision = "db96455566f05ffe42bd6ac671f05eeb1152b45d" - -[[projects]] - branch = "master" - digest = "1:9991da8d42da9b213f2890a05ecbe0fad7325ac216ca3bd6ae30921457971fa9" - name = "github.com/namedotcom/go" - packages = ["namecom"] - pruneopts = "NUT" - revision = "08470befbe04613bd4b44cb6978b05d50294c4d4" - -[[projects]] - digest = "1:417193ba917954c4837c6fc48c6ac241b3fefd13fc0889367b4a7e43b69d582c" - name = "github.com/nrdcg/auroradns" - packages = ["."] - pruneopts = "NUT" - revision = "750ca8603f9f2cca2457acb22ea6e44d3f05358c" - version = "v1.0.0" - -[[projects]] - digest = "1:78bc7967454f8c2a1257b3fe4ed1d57227fb1dff46fd74d38b91bd0d0cc2620a" - name = "github.com/nrdcg/goinwx" - packages = ["."] - pruneopts = "NUT" - revision = "d8152159450570012552f924a0ae6ab3d8c617e0" - version = "v0.6.0" - -[[projects]] - digest = "1:69e47979091e47a10e5ff0e2776ca71aa3e884238ce446bd71e246878ba0858d" - name = "github.com/opencontainers/go-digest" - packages = ["."] - pruneopts = "NUT" - revision = "a6d0ee40d4207ea02364bd3b9e8e77b9159ba1eb" - -[[projects]] - digest = "1:30ba354a819750364d8676f6ce7ffe1a4af1e1ca9ae62d85f6ca62ffe55603fa" - name = "github.com/opencontainers/image-spec" - packages = [ - "specs-go", - "specs-go/v1", - ] - pruneopts = "NUT" - revision = "f03dbe35d449c54915d235f1a3cf8f585a24babe" - -[[projects]] - digest = "1:58f92c360d803e14a97832d08d31de8993e6240268bac7d5c096dd74dd96f4ac" - name = "github.com/opencontainers/runc" - packages = [ - "libcontainer/system", - "libcontainer/user", - ] - pruneopts = "NUT" - revision = "b6b70e53451794e8333e9b602cc096b47a20bd0f" - -[[projects]] - branch = "master" - digest = "1:b4f46325dbc2a7489ba33b4bd3cce542a1721611e857c1cb0b0c57775b2ad130" - name = "github.com/opentracing-contrib/go-observer" - packages = ["."] - pruneopts = "NUT" - revision = "a52f2342449246d5bcc273e65cbdcfa5f7d6c63c" - -[[projects]] - digest = "1:cc405544fecfb5a8e0c409127ef67ce3b91d11143a00121e5b822e4f8eabe7d2" - name = "github.com/opentracing/basictracer-go" - packages = [ - ".", - "wire", - ] - pruneopts = "NUT" - revision = "1b32af207119a14b1b231d451df3ed04a72efebf" - version = "v1.0.0" - -[[projects]] - digest = "1:6846140b3f116579680eefdc17145f2bcf064b68deb9febf86b4419a454049af" - name = "github.com/opentracing/opentracing-go" - packages = [ - ".", - "ext", - "log", - ] - pruneopts = "NUT" - revision = "659c90643e714681897ec2521c60567dd21da733" - version = "v1.1.0" - -[[projects]] - digest = "1:0f4793617dc898d3ee99fe1abab076d3976a9d17d14f8327af2dc3f1ec0fd92c" - name = "github.com/openzipkin-contrib/zipkin-go-opentracing" - packages = [ - ".", - "flag", - "thrift/gen-go/scribe", - "thrift/gen-go/zipkincore", - "types", - "wire", - ] - pruneopts = "NUT" - revision = "f0f479ad013a498e4cbfb369414e5d3880903779" - version = "v0.3.5" - -[[projects]] - digest = "1:b52f6b7059f06a11ab6ab039714dda0d93878d9227f84c84ca9b6f046bfb5fef" - name = "github.com/oracle/oci-go-sdk" - packages = [ - "common", - "dns", - ] - pruneopts = "NUT" - revision = "0306ff0303b6c9f6ea6458021adc9f8f09f562b0" - version = "v4.2.0" - -[[projects]] - branch = "master" - digest = "1:4e9d94fd7812a4c41e403796decb682a8f18fa50fa1f48532967dddc279303f5" - name = "github.com/ovh/go-ovh" - packages = ["ovh"] - pruneopts = "NUT" - revision = "91b7eb631d2eced3e706932a0b36ee8b5ee22e92" - -[[projects]] - digest = "1:748946761cf99c8b73cef5a3c0ee3e040859dd713a20cece0d0e0dc04e6ceca7" - name = "github.com/patrickmn/go-cache" - packages = ["."] - pruneopts = "NUT" - revision = "a3647f8e31d79543b2d0f0ae2fe5c379d72cedc0" - version = "v2.1.0" - -[[projects]] - digest = "1:44c66ad69563dbe3f8e76d7d6cad21a03626e53f1875b5ab163ded419e01ca7a" - name = "github.com/philhofer/fwd" - packages = ["."] - pruneopts = "NUT" - revision = "bb6d471dc95d4fe11e432687f8b70ff496cf3136" - version = "v1.0.0" - -[[projects]] - digest = "1:2e9ddd742d87f1ab60fed796af61d9dafb9c18e6246db8b5d70599bbd4667613" - name = "github.com/pierrec/lz4" - packages = ["."] - pruneopts = "NUT" - revision = "08c27939df1bd95e881e2c2367a749964ad1fceb" - version = "v1.0.1" - -[[projects]] - branch = "master" - digest = "1:5272d5bcf91d1db46fc9528f706019533f1b390b94b122cff427162bc5009e40" - name = "github.com/pierrec/xxHash" - packages = ["xxHash32"] - pruneopts = "NUT" - revision = "a0006b13c722f7f12368c00a3d3c2ae8a999a0c6" - -[[projects]] - digest = "1:074bc35ec6969d7603de3cffb5bb9dc3b6fb694745a9837942fa9b1670e511e6" - name = "github.com/pkg/errors" - packages = ["."] - pruneopts = "NUT" - revision = "c605e284fe17294bda444b34710735b29d1a9d90" - -[[projects]] - digest = "1:0028cb19b2e4c3112225cd871870f2d9cf49b9b4276531f03438a88e94be86fe" - name = "github.com/pmezard/go-difflib" - packages = ["difflib"] - pruneopts = "NUT" - revision = "792786c7400a136282c1664665ae0a8db921c6c2" - version = "v1.0.0" - -[[projects]] - digest = "1:097cc61836050f45cbb712ae3bb45d66fba464c16b8fac09907fa3c1f753eff6" - name = "github.com/prometheus/client_golang" - packages = [ - "prometheus", - "prometheus/internal", - "prometheus/promhttp", - ] - pruneopts = "NUT" - revision = "4ab88e80c249ed361d3299e2930427d9ac43ef8d" - version = "v1.0.0" - -[[projects]] - digest = "1:32d10bdfa8f09ecf13598324dba86ab891f11db3c538b6a34d1c3b5b99d7c36b" - name = "github.com/prometheus/client_model" - packages = ["go"] - pruneopts = "NUT" - revision = "6f3806018612930941127f2a7c6c453ba2c527d2" - -[[projects]] - digest = "1:d03ca24670416dc8fccc78b05d6736ec655416ca7db0a028e8fb92cfdfe3b55e" - name = "github.com/prometheus/common" - packages = [ - "expfmt", - "internal/bitbucket.org/ww/goautoneg", - "model", - ] - pruneopts = "NUT" - revision = "31bed53e4047fd6c510e43a941f90cb31be0972a" - version = "v0.6.0" - -[[projects]] - digest = "1:19305fc369377c111c865a7a01e11c675c57c52a932353bbd4ea360bd5b72d99" - name = "github.com/prometheus/procfs" - packages = [ - ".", - "internal/fs", - ] - pruneopts = "NUT" - revision = "3f98efb27840a48a7a2898ec80be07674d19f9c8" - version = "v0.0.3" - -[[projects]] - branch = "containous-fork" - digest = "1:f103263e55945772fcb058736a03dfc2796c6a14b99b1684b8e88327c0fa0f75" - name = "github.com/rancher/go-rancher-metadata" - packages = ["metadata"] - pruneopts = "NUT" - revision = "c6a65f8b7a28edc424e85732df4cd1c215843a99" - source = "github.com/containous/go-rancher-metadata" - -[[projects]] - digest = "1:0d095d4b1220902aec6896e23808fbcdfa5192dab96d5a31a443a8c47eabc326" - name = "github.com/rcrowley/go-metrics" - packages = ["."] - pruneopts = "NUT" - revision = "1f30fe9094a513ce4c700b9a54458bbb0c96996c" - -[[projects]] - digest = "1:253f275bd72c42f8d234712d1574c8b222fe9b72838bfaca11b21ace9c0e3d0a" - name = "github.com/sacloud/libsacloud" - packages = [ - ".", - "api", - "sacloud", - "sacloud/ostype", - "utils/mutexkv", - ] - pruneopts = "NUT" - revision = "41c392dee98a83260abbe0fcd5c13beb7c75d103" - version = "v1.21.1" - -[[projects]] - digest = "1:6bc0652ea6e39e22ccd522458b8bdd8665bf23bdc5a20eec90056e4dc7e273ca" - name = "github.com/satori/go.uuid" - packages = ["."] - pruneopts = "NUT" - revision = "f58768cc1a7a7e77a3bd49e98cdd21419399b6a3" - version = "v1.2.0" - -[[projects]] - digest = "1:bb9033d47c116ea3b981ff159bdef73df8351b0b9700da2066339b97211b1bf0" - name = "github.com/sirupsen/logrus" - packages = ["."] - pruneopts = "NUT" - revision = "dae0fa8d5b0c810a8ab733fbd5510c7cae84eca4" - version = "v1.4.0" - -[[projects]] - digest = "1:9d8420bbf131d1618bde6530af37c3799340d3762cc47210c1d9532a4c3a2779" - name = "github.com/spf13/pflag" - packages = ["."] - pruneopts = "NUT" - revision = "298182f68c66c05229eb03ac171abe6e309ee79a" - version = "v1.0.3" - -[[projects]] - digest = "1:10301358a67805684f6b525cba6ad7ec014dbd56cccc2926fadc9189faa7889a" - name = "github.com/stretchr/objx" - packages = ["."] - pruneopts = "NUT" - revision = "facf9a85c22f48d2f52f2380e4efce1768749a89" - version = "v0.1" - -[[projects]] - digest = "1:d4de0b9ca757efa67bf8f0f0ee664ad4dc7e11fbad7dd38db4e403ad9b92fe3c" - name = "github.com/stretchr/testify" - packages = [ - "assert", - "mock", - "require", - ] - pruneopts = "NUT" - revision = "12b6f73e6084dad08a7c6e575284b177ecafbc71" - version = "v1.2.1" - -[[projects]] - branch = "master" - digest = "1:9a7f071b0fb18609a16db01a3e98dbc7d423b34f121be3fe8cce7d78159c1164" - name = "github.com/stvp/go-udp-testing" - packages = ["."] - pruneopts = "NUT" - revision = "c4434f09ec131ecf30f986d5dcb1636508bfa49a" - -[[projects]] - branch = "master" - digest = "1:99ce99ce6d6d0cbc5f822cda92095906e01d5546d60999ac839ab008938e4e17" - name = "github.com/timewasted/linode" - packages = [ - ".", - "dns", - ] - pruneopts = "NUT" - revision = "37e84520dcf74488f67654f9c775b9752c232dc1" - -[[projects]] - digest = "1:eaa6698f44de8f2977e93c9b946e60a8af75f565058658aad2df8032b55c84e5" - name = "github.com/tinylib/msgp" - packages = ["msgp"] - pruneopts = "NUT" - revision = "b2b6a672cf1e5b90748f79b8b81fc8c5cf0571a1" - version = "1.0.2" - -[[projects]] - branch = "master" - digest = "1:3b236e8930d31aeb375fe405c15c2afc581e04bd6cb68da4723e1aa8d2e2da37" - name = "github.com/transip/gotransip" - packages = [ - ".", - "domain", - "util", - ] - pruneopts = "NUT" - revision = "1dc93a7db3567a5ccf865106afac88278ba940cf" - -[[projects]] - digest = "1:dc5b63bdf6fd3b22c970e06ad4fb686f6d08104f50f414644d5ac5e267a7934a" - name = "github.com/uber/jaeger-client-go" - packages = [ - ".", - "config", - "internal/baggage", - "internal/baggage/remote", - "internal/spanlog", - "internal/throttler", - "internal/throttler/remote", - "log", - "rpcmetrics", - "thrift", - "thrift-gen/agent", - "thrift-gen/baggage", - "thrift-gen/jaeger", - "thrift-gen/sampling", - "thrift-gen/zipkincore", - "transport", - "utils", - "zipkin", - ] - pruneopts = "NUT" - revision = "2f47546e3facd43297739439600bcf43f44cce5d" - source = "github.com/jaegertracing/jaeger-client-go" - version = "v2.16.0" - -[[projects]] - digest = "1:c9d69a04f7fa171f50360bbcc32196b4de8ab8837ef772f6302d0140a1e3e7f6" - name = "github.com/uber/jaeger-lib" - packages = ["metrics"] - pruneopts = "NUT" - revision = "0e30338a695636fe5bcf7301e8030ce8dd2a8530" - source = "github.com/jaegertracing/jaeger-lib" - version = "v2.0.0" - -[[projects]] - digest = "1:fb6d90081ae53fdb35d0fffa7d82a555df936bbc6db9a93126795655b2317604" - name = "github.com/unrolled/render" - packages = ["."] - pruneopts = "NUT" - revision = "50716a0a853771bb36bfce61a45cdefdb98c2e6e" - -[[projects]] - branch = "v1" - digest = "1:ca2fa30e83e743bf24f13fbfa883e228955748ab59785b6ae9bd8a55a05bd157" - name = "github.com/unrolled/secure" - packages = ["."] - pruneopts = "NUT" - revision = "716474489ad3d350e961ec6de19a6ab24e40f006" - -[[projects]] - digest = "1:a68c3f55d44d225da4f22ffbed2d8572d267cb19aaa1d60537769034ac66bc01" - name = "github.com/vdemeester/shakers" - packages = ["."] - pruneopts = "NUT" - revision = "24d7f1d6a71aa5d9cbe7390e4afb66b7eef9e1b3" - version = "v0.1.0" - -[[projects]] - branch = "master" - digest = "1:d7ace03de79a9cec30e7a55cc16160602760470c5fe031b780dc2d84234d7f5a" - name = "github.com/vulcand/oxy" - packages = [ - "buffer", - "cbreaker", - "connlimit", - "forward", - "memmetrics", - "ratelimit", - "roundrobin", - "utils", - ] - pruneopts = "NUT" - revision = "3d629cff40b7040e0519628e7774ed11a95d9aff" - -[[projects]] - digest = "1:b9d8cc221fb40078c7eb78d73b1702b5b548511b3d62bbd56b2f8180089c79af" - name = "github.com/vulcand/predicate" - packages = ["."] - pruneopts = "NUT" - revision = "8fbfb3ab0e94276b6b58bec378600829adc7a203" - version = "v1.1.0" - -[[projects]] - branch = "master" - digest = "1:669d39abbe79469bb50e32a26541026fd91326ac0ca56a9ad83be5b9887e5a8c" - name = "github.com/xeipuuv/gojsonpointer" - packages = ["."] - pruneopts = "NUT" - revision = "6fe8760cad3569743d51ddbb243b26f8456742dc" - -[[projects]] - branch = "master" - digest = "1:dffaacd300adca64381977995d07e91b53a55330ecd6835d9fa9947b7a4c0460" - name = "github.com/xeipuuv/gojsonreference" - packages = ["."] - pruneopts = "NUT" - revision = "e02fc20de94c78484cd5ffb007f8af96be030a45" - -[[projects]] - digest = "1:5185937abbca299da07bcbeb4e38dfa186c09fbf60042c3d07e0073a0634a78f" - name = "github.com/xeipuuv/gojsonschema" - packages = ["."] - pruneopts = "NUT" - revision = "f971f3cd73b2899de6923801c147f075263e0c50" - version = "v1.1.0" - -[[projects]] - digest = "1:aafe0319af5410fb19a23a575ea6ee4b14253e122ef87f936bac65ea1e6b280c" - name = "go.opencensus.io" - packages = [ - ".", - "internal", - "internal/tagencoding", - "metric/metricdata", - "metric/metricproducer", - "plugin/ochttp", - "plugin/ochttp/propagation/b3", - "resource", - "stats", - "stats/internal", - "stats/view", - "tag", - "trace", - "trace/internal", - "trace/propagation", - "trace/tracestate", - ] - pruneopts = "NUT" - revision = "df6e2001952312404b06f5f6f03fcb4aec1648e5" - version = "v0.21.0" - -[[projects]] - branch = "master" - digest = "1:02fe59517e10f9b400b500af8ac228c74cecb0cba7a5f438d8283edb97e14270" - name = "go.uber.org/ratelimit" - packages = [ - ".", - "internal/clock", - ] - pruneopts = "NUT" - revision = "c15da02342779cb6dc027fc95ee2277787698f36" - -[[projects]] - branch = "master" - digest = "1:30c1930f8c9fee79f3af60c8b7cd92edd12a4f22187f5527d53509b1a794f555" - name = "golang.org/x/crypto" - packages = [ - "bcrypt", - "blowfish", - "ed25519", - "ed25519/internal/edwards25519", - "ocsp", - "pbkdf2", - "pkcs12", - "pkcs12/internal/rc2", - "scrypt", - "ssh/terminal", - ] - pruneopts = "NUT" - revision = "505ab145d0a99da450461ae2c1a9f6cd10d1f447" - -[[projects]] - branch = "master" - digest = "1:4d0fb9f19b2af3461e900a526395330403b39d839f126b66312215f153892ccc" - name = "golang.org/x/net" - packages = [ - "bpf", - "context", - "context/ctxhttp", - "http/httpguts", - "http2", - "http2/h2c", - "http2/hpack", - "idna", - "internal/iana", - "internal/socket", - "internal/socks", - "internal/timeseries", - "ipv4", - "ipv6", - "proxy", - "publicsuffix", - "trace", - "websocket", - ] - pruneopts = "NUT" - revision = "da137c7871d730100384dbcf36e6f8fa493aef5b" - -[[projects]] - branch = "master" - digest = "1:7468367d51c1434860fbfcde70f755fff634afce4090bbbba1abac2909d3f5cb" - name = "golang.org/x/oauth2" - packages = [ - ".", - "clientcredentials", - "google", - "internal", - "jws", - "jwt", - ] - pruneopts = "NUT" - revision = "ec22f46f877b4505e0117eeaab541714644fdd28" - -[[projects]] - branch = "master" - digest = "1:b521f10a2d8fa85c04a8ef4e62f2d1e14d303599a55d64dabf9f5a02f84d35eb" - name = "golang.org/x/sync" - packages = ["errgroup"] - pruneopts = "NUT" - revision = "112230192c580c3556b8cee6403af37a4fc5f28c" - -[[projects]] - digest = "1:51bfac9fe01b6a949bfed6db70b00bada281f0d64e5296ec644163aa977bfee0" - name = "golang.org/x/sys" - packages = [ - "unix", - "windows", - ] - pruneopts = "NUT" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[projects]] - digest = "1:ca9ebfc1200ca7423d9778dba9cdd463704753541c99dc4896f15e0b8b2bf1e8" - name = "golang.org/x/text" - packages = [ - "internal/gen", - "internal/triegen", - "internal/ucd", - "secure/bidirule", - "transform", - "unicode/bidi", - "unicode/cldr", - "unicode/norm", - "unicode/rangetable", - ] - pruneopts = "NUT" - revision = "4ee4af566555f5fbe026368b75596286a312663a" - -[[projects]] - digest = "1:51a479a09b7ed06b7be5a854e27fcc328718ae0e5ad159f9ddeef12d0326c2e7" - name = "golang.org/x/time" - packages = ["rate"] - pruneopts = "NUT" - revision = "8be79e1e0910c292df4e79c241bb7e8f7e725959" - -[[projects]] - branch = "master" - digest = "1:e46d8e20161401a9cf8765dfa428494a3492a0b56fe114156b7da792bf41ba78" - name = "golang.org/x/tools" - packages = [ - "go/ast/astutil", - "go/gcexportdata", - "go/internal/cgo", - "go/internal/gcimporter", - "go/internal/packagesdriver", - "go/packages", - "go/types/typeutil", - "imports", - "internal/fastwalk", - "internal/gopathwalk", - "internal/module", - "internal/semver", - ] - pruneopts = "NUT" - revision = "589c23e65e65055d47b9ad4a99723bc389136265" - -[[projects]] - branch = "master" - digest = "1:70c173b8ecc111dd01dc07f0ada72c076e4ed91618ee559312ef8adf154cc539" - name = "google.golang.org/api" - packages = [ - "dns/v1", - "gensupport", - "googleapi", - "googleapi/internal/uritemplates", - "googleapi/transport", - "internal", - "option", - "transport/http", - "transport/http/internal/propagation", - ] - pruneopts = "NUT" - revision = "067bed655e9cbc26f4dbac8f8897b30756d90990" - -[[projects]] - digest = "1:7206d98ec77c90c72ec2c405181a1dcf86965803b6dbc4f98ceab7a5047c37a9" - name = "google.golang.org/appengine" - packages = [ - ".", - "internal", - "internal/app_identity", - "internal/base", - "internal/datastore", - "internal/log", - "internal/modules", - "internal/remote_api", - "internal/urlfetch", - "urlfetch", - ] - pruneopts = "NUT" - revision = "4f7eeb5305a4ba1966344836ba4af9996b7b4e05" - -[[projects]] - digest = "1:93180612a69db36a06d801302b867d53a50a8a5f0943b34db66adc0574ea57df" - name = "google.golang.org/genproto" - packages = ["googleapis/rpc/status"] - pruneopts = "NUT" - revision = "09f6ed296fc66555a25fe4ce95173148778dfa85" - -[[projects]] - digest = "1:ffb498178a6bbe5a877e715cc85a40d5a712883d85f5bf05acf26dbd6c8f71e2" - name = "google.golang.org/grpc" - packages = [ - ".", - "balancer", - "balancer/base", - "balancer/roundrobin", - "binarylog/grpc_binarylog_v1", - "codes", - "connectivity", - "credentials", - "credentials/internal", - "encoding", - "encoding/proto", - "grpclog", - "internal", - "internal/backoff", - "internal/balancerload", - "internal/binarylog", - "internal/channelz", - "internal/envconfig", - "internal/grpcrand", - "internal/grpcsync", - "internal/syscall", - "internal/transport", - "keepalive", - "metadata", - "naming", - "peer", - "resolver", - "resolver/dns", - "resolver/passthrough", - "stats", - "status", - "tap", - ] - pruneopts = "NUT" - revision = "25c4f928eaa6d96443009bd842389fb4fa48664e" - version = "v1.20.1" - -[[projects]] - digest = "1:d732242a429138da899dfecea82b3c65b4157bdf0b5317c229d9c559b6c3450e" - name = "gopkg.in/DataDog/dd-trace-go.v1" - packages = [ - "ddtrace", - "ddtrace/ext", - "ddtrace/internal", - "ddtrace/opentracer", - "ddtrace/tracer", - "internal/globalconfig", - "internal/log", - "internal/version", - ] - pruneopts = "NUT" - revision = "8d2998bc69008aa4553846ac9a044aa730bd4ce4" - version = "v1.15.0" - -[[projects]] - digest = "1:c970218a20933dd0a2eb2006de922217fa9276f57d25009b2a934eb1c50031cc" - name = "gopkg.in/fsnotify.v1" - packages = ["."] - pruneopts = "NUT" - revision = "629574ca2a5df945712d3079857300b5e4da0236" - source = "github.com/fsnotify/fsnotify" - version = "v1.4.2" - -[[projects]] - digest = "1:ef72505cf098abdd34efeea032103377bec06abb61d8a06f002d5d296a4b1185" - name = "gopkg.in/inf.v0" - packages = ["."] - pruneopts = "NUT" - revision = "3887ee99ecf07df5b447e9b00d9c0b2adaa9f3e4" - version = "v0.9.0" - -[[projects]] - digest = "1:007a90eec366dd24a5a0c0d3f83d4019bf895774255e769421ec954ff1465b6e" - name = "gopkg.in/ini.v1" - packages = ["."] - pruneopts = "NUT" - revision = "5b3e00af70a9484542169a976dcab8d03e601a17" - version = "v1.30.0" - -[[projects]] - branch = "v2" - digest = "1:f57d15cb0f61c985f61fd2c529245debb439128ecc8c44c06251900d281c68fc" - name = "gopkg.in/ns1/ns1-go.v2" - packages = [ - "rest", - "rest/model/account", - "rest/model/data", - "rest/model/dns", - "rest/model/filter", - "rest/model/monitor", - ] - pruneopts = "NUT" - revision = "a5bcac82d3f637d3928d30476610891935b2d691" - -[[projects]] - digest = "1:85a9c61c8d566fbbb108da8714893e6fc892fdb7a2910612a27f551ce30a0dd3" - name = "gopkg.in/square/go-jose.v2" - packages = [ - ".", - "cipher", - "json", - ] - pruneopts = "NUT" - revision = "6ee92191fea850cdcab9a18867abf5f521cdbadb" - version = "v2.1.4" - -[[projects]] - digest = "1:18108594151654e9e696b27b181b953f9a90b16bf14d253dd1b397b025a1487f" - name = "gopkg.in/yaml.v2" - packages = ["."] - pruneopts = "NUT" - revision = "51d6538a90f86fe93ac480b35f37b2be17fef232" - version = "v2.2.2" - -[[projects]] - digest = "1:759855d98a898d7d6a091b89b9c85c03d6efd673c44e15561d716543f4e88f31" - name = "k8s.io/api" - packages = [ - "admissionregistration/v1beta1", - "apps/v1", - "apps/v1beta1", - "apps/v1beta2", - "auditregistration/v1alpha1", - "authentication/v1", - "authentication/v1beta1", - "authorization/v1", - "authorization/v1beta1", - "autoscaling/v1", - "autoscaling/v2beta1", - "autoscaling/v2beta2", - "batch/v1", - "batch/v1beta1", - "batch/v2alpha1", - "certificates/v1beta1", - "coordination/v1", - "coordination/v1beta1", - "core/v1", - "events/v1beta1", - "extensions/v1beta1", - "networking/v1", - "networking/v1beta1", - "node/v1alpha1", - "node/v1beta1", - "policy/v1beta1", - "rbac/v1", - "rbac/v1alpha1", - "rbac/v1beta1", - "scheduling/v1", - "scheduling/v1alpha1", - "scheduling/v1beta1", - "settings/v1alpha1", - "storage/v1", - "storage/v1alpha1", - "storage/v1beta1", - ] - pruneopts = "NUT" - revision = "b59d8169aab578b59c8d331a0e8cf6c56fae5fa0" - version = "kubernetes-1.15.1" - -[[projects]] - digest = "1:155388665cbca8ef2eea33692deacce31f5ee2029a1e5c50a83908e4e2fafc4f" - name = "k8s.io/apimachinery" - packages = [ - "pkg/api/errors", - "pkg/api/meta", - "pkg/api/resource", - "pkg/apis/meta/internalversion", - "pkg/apis/meta/v1", - "pkg/apis/meta/v1/unstructured", - "pkg/apis/meta/v1beta1", - "pkg/conversion", - "pkg/conversion/queryparams", - "pkg/fields", - "pkg/labels", - "pkg/runtime", - "pkg/runtime/schema", - "pkg/runtime/serializer", - "pkg/runtime/serializer/json", - "pkg/runtime/serializer/protobuf", - "pkg/runtime/serializer/recognizer", - "pkg/runtime/serializer/streaming", - "pkg/runtime/serializer/versioning", - "pkg/selection", - "pkg/types", - "pkg/util/cache", - "pkg/util/clock", - "pkg/util/diff", - "pkg/util/errors", - "pkg/util/framer", - "pkg/util/intstr", - "pkg/util/json", - "pkg/util/mergepatch", - "pkg/util/naming", - "pkg/util/net", - "pkg/util/runtime", - "pkg/util/sets", - "pkg/util/strategicpatch", - "pkg/util/validation", - "pkg/util/validation/field", - "pkg/util/wait", - "pkg/util/yaml", - "pkg/version", - "pkg/watch", - "third_party/forked/golang/json", - "third_party/forked/golang/reflect", - ] - pruneopts = "NUT" - revision = "1799e75a07195de9460b8ef7300883499f12127b" - version = "kubernetes-1.15.1" - -[[projects]] - digest = "1:dca55f4df9d801b3ed52459f9df1d4def74e5a5c55a3f976c614bd972913a56d" - name = "k8s.io/client-go" - packages = [ - "discovery", - "discovery/fake", - "informers", - "informers/admissionregistration", - "informers/admissionregistration/v1beta1", - "informers/apps", - "informers/apps/v1", - "informers/apps/v1beta1", - "informers/apps/v1beta2", - "informers/auditregistration", - "informers/auditregistration/v1alpha1", - "informers/autoscaling", - "informers/autoscaling/v1", - "informers/autoscaling/v2beta1", - "informers/autoscaling/v2beta2", - "informers/batch", - "informers/batch/v1", - "informers/batch/v1beta1", - "informers/batch/v2alpha1", - "informers/certificates", - "informers/certificates/v1beta1", - "informers/coordination", - "informers/coordination/v1", - "informers/coordination/v1beta1", - "informers/core", - "informers/core/v1", - "informers/events", - "informers/events/v1beta1", - "informers/extensions", - "informers/extensions/v1beta1", - "informers/internalinterfaces", - "informers/networking", - "informers/networking/v1", - "informers/networking/v1beta1", - "informers/node", - "informers/node/v1alpha1", - "informers/node/v1beta1", - "informers/policy", - "informers/policy/v1beta1", - "informers/rbac", - "informers/rbac/v1", - "informers/rbac/v1alpha1", - "informers/rbac/v1beta1", - "informers/scheduling", - "informers/scheduling/v1", - "informers/scheduling/v1alpha1", - "informers/scheduling/v1beta1", - "informers/settings", - "informers/settings/v1alpha1", - "informers/storage", - "informers/storage/v1", - "informers/storage/v1alpha1", - "informers/storage/v1beta1", - "kubernetes", - "kubernetes/scheme", - "kubernetes/typed/admissionregistration/v1beta1", - "kubernetes/typed/apps/v1", - "kubernetes/typed/apps/v1beta1", - "kubernetes/typed/apps/v1beta2", - "kubernetes/typed/auditregistration/v1alpha1", - "kubernetes/typed/authentication/v1", - "kubernetes/typed/authentication/v1beta1", - "kubernetes/typed/authorization/v1", - "kubernetes/typed/authorization/v1beta1", - "kubernetes/typed/autoscaling/v1", - "kubernetes/typed/autoscaling/v2beta1", - "kubernetes/typed/autoscaling/v2beta2", - "kubernetes/typed/batch/v1", - "kubernetes/typed/batch/v1beta1", - "kubernetes/typed/batch/v2alpha1", - "kubernetes/typed/certificates/v1beta1", - "kubernetes/typed/coordination/v1", - "kubernetes/typed/coordination/v1beta1", - "kubernetes/typed/core/v1", - "kubernetes/typed/events/v1beta1", - "kubernetes/typed/extensions/v1beta1", - "kubernetes/typed/networking/v1", - "kubernetes/typed/networking/v1beta1", - "kubernetes/typed/node/v1alpha1", - "kubernetes/typed/node/v1beta1", - "kubernetes/typed/policy/v1beta1", - "kubernetes/typed/rbac/v1", - "kubernetes/typed/rbac/v1alpha1", - "kubernetes/typed/rbac/v1beta1", - "kubernetes/typed/scheduling/v1", - "kubernetes/typed/scheduling/v1alpha1", - "kubernetes/typed/scheduling/v1beta1", - "kubernetes/typed/settings/v1alpha1", - "kubernetes/typed/storage/v1", - "kubernetes/typed/storage/v1alpha1", - "kubernetes/typed/storage/v1beta1", - "listers/admissionregistration/v1beta1", - "listers/apps/v1", - "listers/apps/v1beta1", - "listers/apps/v1beta2", - "listers/auditregistration/v1alpha1", - "listers/autoscaling/v1", - "listers/autoscaling/v2beta1", - "listers/autoscaling/v2beta2", - "listers/batch/v1", - "listers/batch/v1beta1", - "listers/batch/v2alpha1", - "listers/certificates/v1beta1", - "listers/coordination/v1", - "listers/coordination/v1beta1", - "listers/core/v1", - "listers/events/v1beta1", - "listers/extensions/v1beta1", - "listers/networking/v1", - "listers/networking/v1beta1", - "listers/node/v1alpha1", - "listers/node/v1beta1", - "listers/policy/v1beta1", - "listers/rbac/v1", - "listers/rbac/v1alpha1", - "listers/rbac/v1beta1", - "listers/scheduling/v1", - "listers/scheduling/v1alpha1", - "listers/scheduling/v1beta1", - "listers/settings/v1alpha1", - "listers/storage/v1", - "listers/storage/v1alpha1", - "listers/storage/v1beta1", - "pkg/apis/clientauthentication", - "pkg/apis/clientauthentication/v1alpha1", - "pkg/apis/clientauthentication/v1beta1", - "pkg/version", - "plugin/pkg/client/auth/exec", - "rest", - "rest/watch", - "testing", - "tools/auth", - "tools/cache", - "tools/clientcmd", - "tools/clientcmd/api", - "tools/clientcmd/api/latest", - "tools/clientcmd/api/v1", - "tools/metrics", - "tools/pager", - "tools/reference", - "transport", - "util/cert", - "util/connrotation", - "util/flowcontrol", - "util/homedir", - "util/keyutil", - "util/retry", - ] - pruneopts = "NUT" - revision = "8e956561bbf57253b1d19c449d0f24e8cb18d467" - version = "kubernetes-1.15.1" - -[[projects]] - digest = "1:f41480fd8c5f54b13326ee0f2ee398d5734789b790dbc4db57f9b08a0d63139a" - name = "k8s.io/code-generator" - packages = [ - "cmd/client-gen", - "cmd/client-gen/args", - "cmd/client-gen/generators", - "cmd/client-gen/generators/fake", - "cmd/client-gen/generators/scheme", - "cmd/client-gen/generators/util", - "cmd/client-gen/path", - "cmd/client-gen/types", - "cmd/deepcopy-gen", - "cmd/deepcopy-gen/args", - "cmd/defaulter-gen", - "cmd/defaulter-gen/args", - "cmd/informer-gen", - "cmd/informer-gen/args", - "cmd/informer-gen/generators", - "cmd/lister-gen", - "cmd/lister-gen/args", - "cmd/lister-gen/generators", - "pkg/namer", - "pkg/util", - ] - pruneopts = "T" - revision = "18da4a14b22b17d2fa761e50037fabfbacec225b" - version = "kubernetes-1.15.1" - -[[projects]] - branch = "master" - digest = "1:61024ed77a53ac618effed55043bf6a9afbdeb64136bd6a5b0c992d4c0363766" - name = "k8s.io/gengo" - packages = [ - "args", - "examples/deepcopy-gen/generators", - "examples/defaulter-gen/generators", - "examples/set-gen/sets", - "generator", - "namer", - "parser", - "types", - ] - pruneopts = "NUT" - revision = "0689ccc1d7d65d9dd1bedcc3b0b1ed7df91ba266" - -[[projects]] - digest = "1:c263611800c3a97991dbcf9d3bc4de390f6224aaa8ca0a7226a9d734f65a416a" - name = "k8s.io/klog" - packages = ["."] - pruneopts = "NUT" - revision = "71442cd4037d612096940ceb0f3fec3f7fff66e0" - version = "v0.2.0" - -[[projects]] - branch = "master" - digest = "1:03a96603922fc1f6895ae083e1e16d943b55ef0656b56965351bd87e7d90485f" - name = "k8s.io/kube-openapi" - packages = ["pkg/util/proto"] - pruneopts = "NUT" - revision = "15615b16d372105f0c69ff47dfe7402926a65aaa" - -[[projects]] - branch = "master" - digest = "1:2d3f59daa4b479ff4e100a2e1d8fea6780040fdadc177869531fe4cc29407f55" - name = "k8s.io/utils" - packages = [ - "buffer", - "integer", - "trace", - ] - pruneopts = "NUT" - revision = "581e00157fb1a0435d4fac54a52d1ca1e481d60e" - -[[projects]] - digest = "1:8730e0150dfb2b7e173890c8b9868e7a273082ef8e39f4940e3506a481cf895c" - name = "sigs.k8s.io/yaml" - packages = ["."] - pruneopts = "NUT" - revision = "fd68e9863619f6ec2fdd8625fe1f02e7c877e480" - version = "v1.1.0" - -[solve-meta] - analyzer-name = "dep" - analyzer-version = 1 - input-imports = [ - "github.com/BurntSushi/toml", - "github.com/ExpediaDotCom/haystack-client-go", - "github.com/Masterminds/sprig", - "github.com/NYTimes/gziphandler", - "github.com/abbot/go-http-auth", - "github.com/abronan/valkeyrie/store", - "github.com/armon/go-proxyproto", - "github.com/cenkalti/backoff", - "github.com/containous/alice", - "github.com/containous/mux", - "github.com/coreos/go-systemd/daemon", - "github.com/davecgh/go-spew/spew", - "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/network", - "github.com/docker/docker/api/types/swarm", - "github.com/docker/docker/api/types/versions", - "github.com/docker/docker/client", - "github.com/docker/docker/pkg/namesgenerator", - "github.com/docker/go-connections/nat", - "github.com/docker/go-connections/sockets", - "github.com/eapache/channels", - "github.com/elazarl/go-bindata-assetfs", - "github.com/fatih/structs", - "github.com/gambol99/go-marathon", - "github.com/go-acme/lego/certcrypto", - "github.com/go-acme/lego/certificate", - "github.com/go-acme/lego/challenge", - "github.com/go-acme/lego/challenge/dns01", - "github.com/go-acme/lego/challenge/http01", - "github.com/go-acme/lego/challenge/tlsalpn01", - "github.com/go-acme/lego/lego", - "github.com/go-acme/lego/log", - "github.com/go-acme/lego/providers/dns", - "github.com/go-acme/lego/registration", - "github.com/go-check/check", - "github.com/go-kit/kit/log", - "github.com/go-kit/kit/metrics", - "github.com/go-kit/kit/metrics/dogstatsd", - "github.com/go-kit/kit/metrics/influx", - "github.com/go-kit/kit/metrics/multi", - "github.com/go-kit/kit/metrics/statsd", - "github.com/golang/protobuf/proto", - "github.com/google/go-github/github", - "github.com/gorilla/websocket", - "github.com/hashicorp/go-version", - "github.com/influxdata/influxdb1-client/v2", - "github.com/instana/go-sensor", - "github.com/libkermit/compose/check", - "github.com/libkermit/docker", - "github.com/libkermit/docker-check", - "github.com/miekg/dns", - "github.com/mitchellh/copystructure", - "github.com/mitchellh/hashstructure", - "github.com/mvdan/xurls", - "github.com/opentracing/opentracing-go", - "github.com/opentracing/opentracing-go/ext", - "github.com/opentracing/opentracing-go/log", - "github.com/openzipkin-contrib/zipkin-go-opentracing", - "github.com/patrickmn/go-cache", - "github.com/pmezard/go-difflib/difflib", - "github.com/prometheus/client_golang/prometheus", - "github.com/prometheus/client_golang/prometheus/promhttp", - "github.com/prometheus/client_model/go", - "github.com/rancher/go-rancher-metadata/metadata", - "github.com/sirupsen/logrus", - "github.com/stretchr/testify/assert", - "github.com/stretchr/testify/mock", - "github.com/stretchr/testify/require", - "github.com/stvp/go-udp-testing", - "github.com/uber/jaeger-client-go", - "github.com/uber/jaeger-client-go/config", - "github.com/uber/jaeger-client-go/zipkin", - "github.com/uber/jaeger-lib/metrics", - "github.com/unrolled/render", - "github.com/unrolled/secure", - "github.com/vdemeester/shakers", - "github.com/vulcand/oxy/buffer", - "github.com/vulcand/oxy/cbreaker", - "github.com/vulcand/oxy/connlimit", - "github.com/vulcand/oxy/forward", - "github.com/vulcand/oxy/ratelimit", - "github.com/vulcand/oxy/roundrobin", - "github.com/vulcand/oxy/utils", - "github.com/vulcand/predicate", - "golang.org/x/net/http2", - "golang.org/x/net/http2/h2c", - "golang.org/x/net/websocket", - "google.golang.org/grpc", - "google.golang.org/grpc/credentials", - "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/opentracer", - "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer", - "gopkg.in/fsnotify.v1", - "gopkg.in/yaml.v2", - "k8s.io/api/core/v1", - "k8s.io/api/extensions/v1beta1", - "k8s.io/apimachinery/pkg/api/errors", - "k8s.io/apimachinery/pkg/apis/meta/v1", - "k8s.io/apimachinery/pkg/labels", - "k8s.io/apimachinery/pkg/runtime", - "k8s.io/apimachinery/pkg/runtime/schema", - "k8s.io/apimachinery/pkg/runtime/serializer", - "k8s.io/apimachinery/pkg/types", - "k8s.io/apimachinery/pkg/util/intstr", - "k8s.io/apimachinery/pkg/util/runtime", - "k8s.io/apimachinery/pkg/watch", - "k8s.io/client-go/discovery", - "k8s.io/client-go/discovery/fake", - "k8s.io/client-go/informers", - "k8s.io/client-go/kubernetes", - "k8s.io/client-go/kubernetes/scheme", - "k8s.io/client-go/rest", - "k8s.io/client-go/testing", - "k8s.io/client-go/tools/cache", - "k8s.io/client-go/tools/clientcmd", - "k8s.io/client-go/util/flowcontrol", - "k8s.io/code-generator/cmd/client-gen", - "k8s.io/code-generator/cmd/deepcopy-gen", - "k8s.io/code-generator/cmd/defaulter-gen", - "k8s.io/code-generator/cmd/informer-gen", - "k8s.io/code-generator/cmd/lister-gen", - ] - solver-name = "gps-cdcl" - solver-version = 1 diff --git a/Gopkg.toml b/Gopkg.toml deleted file mode 100644 index be87bbbab..000000000 --- a/Gopkg.toml +++ /dev/null @@ -1,289 +0,0 @@ -# Gopkg.toml example -# -# Refer to https://github.com/golang/dep/blob/master/docs/Gopkg.toml.md -# for detailed Gopkg.toml documentation. -# -# required = ["github.com/user/thing/cmd/thing"] -# ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] -# -# [[constraint]] -# name = "github.com/user/project" -# version = "1.0.0" -# -# [[constraint]] -# name = "github.com/user/project2" -# branch = "dev" -# source = "github.com/myfork/project2" -# -# [[override]] -# name = "github.com/x/y" -# version = "2.4.0" - -required = [ - "k8s.io/code-generator/cmd/client-gen", - "k8s.io/code-generator/cmd/deepcopy-gen", - "k8s.io/code-generator/cmd/defaulter-gen", - "k8s.io/code-generator/cmd/lister-gen", - "k8s.io/code-generator/cmd/informer-gen", -] - -[prune] - non-go = true - go-tests = true - unused-packages = true - [[prune.project]] - name = "k8s.io/code-generator" - non-go = false - unused-packages = false - -#[[constraint]] -# branch = "master" -# name = "github.com/ArthurHlt/go-eureka-client" - -[[constraint]] - branch = "master" - name = "github.com/BurntSushi/toml" - -#[[constraint]] -# branch = "master" -# name = "github.com/BurntSushi/ty" - -[[constraint]] - branch = "master" - name = "github.com/NYTimes/gziphandler" - -[[constraint]] - branch = "containous-fork" - name = "github.com/abbot/go-http-auth" - source = "github.com/containous/go-http-auth" - -[[constraint]] - branch = "master" - name = "github.com/armon/go-proxyproto" - -#[[constraint]] -# name = "github.com/aws/aws-sdk-go" -# version = "1.13.11" - -[[constraint]] - name = "github.com/cenkalti/backoff" - version = "2.1.1" - -[[constraint]] - branch = "master" - name = "github.com/containous/mux" - -[[constraint]] - branch = "containous-fork" - name = "github.com/containous/alice" - -#[[constraint]] -# name = "github.com/thoas/stats" -# # related to https://github.com/thoas/stats/pull/32 -# revision = "4975baf6a358ed3ddaa42133996e1959f96c9300" - -[[constraint]] - name = "github.com/coreos/go-systemd" - version = "14.0.0" - -#[[constraint]] -# branch = "master" -# name = "github.com/docker/leadership" -# source = "github.com/containous/leadership" - -[[constraint]] - name = "github.com/eapache/channels" - version = "1.1.0" - -[[constraint]] - branch = "master" - name = "github.com/elazarl/go-bindata-assetfs" - -[[constraint]] - branch = "fork-containous" - name = "github.com/go-check/check" - source = "github.com/containous/check" - -[[override]] - branch = "fork-containous" - name = "github.com/go-check/check" - source = "github.com/containous/check" - -[[constraint]] - name = "github.com/go-kit/kit" - version = "v0.9.0" - -[[constraint]] - name = "github.com/prometheus/client_golang" - version = "v1.0.0" - -[[constraint]] - branch = "master" - name = "github.com/gorilla/websocket" - -#[[constraint]] -# name = "github.com/hashicorp/consul" -# version = "1.0.6" - -#[[constraint]] -# branch = "master" -# name = "github.com/jjcollinge/servicefabric" - -#[[constraint]] -# branch = "master" -# name = "github.com/abronan/valkeyrie" - -#[[constraint]] -# name = "github.com/mesosphere/mesos-dns" -# source = "https://github.com/containous/mesos-dns.git" - -[[constraint]] - name = "github.com/opentracing/opentracing-go" - version = "1.0.2" - -[[constraint]] - branch = "containous-fork" - name = "github.com/rancher/go-rancher-metadata" - source = "github.com/containous/go-rancher-metadata" - -[[constraint]] - name = "github.com/Masterminds/sprig" - version = "2.19.0" - -[[constraint]] - branch = "master" - name = "github.com/stvp/go-udp-testing" - -[[constraint]] - name = "github.com/stretchr/testify" - version = "1.2.1" - -[[constraint]] - name = "github.com/uber/jaeger-client-go" - source = "github.com/jaegertracing/jaeger-client-go" - version = "2.16.0" - -[[constraint]] - name = "github.com/uber/jaeger-lib" - source = "github.com/jaegertracing/jaeger-lib" - version = "2.0.0" - -[[constraint]] - branch = "v1" - name = "github.com/unrolled/secure" - -[[constraint]] - name = "github.com/vdemeester/shakers" - version = "0.1.0" - -[[constraint]] - branch = "master" - name = "github.com/vulcand/oxy" - -[[constraint]] - name = "github.com/go-acme/lego" - version = "2.6.0" - -[[constraint]] - name = "google.golang.org/grpc" - version = "1.13.0" - -[[override]] - name = "golang.org/x/sys" - revision = "1c9583448a9c3aa0f9a6a5241bf73c0bd8aafded" - -[[constraint]] - name = "github.com/golang/protobuf" - version = "v1.3.0" - -[[constraint]] - name = "gopkg.in/fsnotify.v1" - source = "github.com/fsnotify/fsnotify" - version = "1.4.2" - -[[constraint]] - name = "k8s.io/client-go" - version = "kubernetes-1.15.1" # kubernetes-1.15.1 - -[[constraint]] - name = "k8s.io/code-generator" - version = "kubernetes-1.15.1" # "kubernetes-1.15.1" - -[[constraint]] - name = "k8s.io/api" - version = "kubernetes-1.15.1" # "kubernetes-1.15.1" - -[[constraint]] - name = "k8s.io/apimachinery" - version = "kubernetes-1.15.1" # "kubernetes-1.15.1" - -[[override]] - name = "github.com/json-iterator/go" - version = "1.1.6" - -[[constraint]] - branch = "master" - name = "github.com/libkermit/docker" - -[[constraint]] - branch = "master" - name = "github.com/libkermit/docker-check" - -[[constraint]] - branch = "master" - name = "github.com/libkermit/compose" - -[[constraint]] - name = "github.com/docker/docker" - source = "github.com/docker/engine" - version = "v19.03.1" - -[[override]] - name = "github.com/docker/docker" - source = "github.com/docker/engine" - version = "v19.03.1" - -[[override]] - name = "github.com/docker/cli" - version = "v19.03.1" - -[[override]] - name = "github.com/docker/distribution" - version = "v2.7.1" - -[[override]] - branch = "master" - name = "github.com/docker/libcompose" - -[[override]] - name = "github.com/xeipuuv/gojsonschema" - version = "v1.1.0" - -[[override]] - # ALWAYS keep this override - name = "github.com/mailgun/timetools" - revision = "7e6055773c5137efbeb3bd2410d705fe10ab6bfd" - -[[override]] - version = "v1.1.1" - name = "github.com/miekg/dns" - -[[constraint]] - name = "github.com/patrickmn/go-cache" - version = "2.1.0" - -[[constraint]] - name = "gopkg.in/DataDog/dd-trace-go.v1" - version = "1.15.0" - -[[constraint]] - name = "github.com/instana/go-sensor" - version = "1.4.12" - -[[constraint]] - name = "github.com/ExpediaDotCom/haystack-client-go" - version = "0.2.3" - -[[constraint]] - name = "gopkg.in/yaml.v2" - version = "v2.2.2" diff --git a/Makefile b/Makefile index 08d1abeb4..daf2cbae3 100644 --- a/Makefile +++ b/Makefile @@ -128,15 +128,6 @@ docs-serve: generate-crd: ./script/update-generated-crd-code.sh -## Download dependencies -dep-ensure: - dep ensure -v - ./script/prune-dep.sh - -## Clean vendor directory -dep-prune: - ./script/prune-dep.sh - ## Create packages for the release release-packages: generate-webui build-dev-image rm -rf dist @@ -156,5 +147,5 @@ fmt: run-dev: go generate - go build ./cmd/traefik + GO111MODULE=on go build ./cmd/traefik ./traefik diff --git a/build.Dockerfile b/build.Dockerfile index c3ff44b5f..27c308562 100644 --- a/build.Dockerfile +++ b/build.Dockerfile @@ -1,35 +1,37 @@ -FROM golang:1.12-alpine +FROM golang:1.13rc1-alpine RUN apk --update upgrade \ && apk --no-cache --no-progress add git mercurial bash gcc musl-dev curl tar ca-certificates tzdata \ && update-ca-certificates \ && rm -rf /var/cache/apk/* -# Download golangci-lint and misspell binary to bin folder in $GOPATH -RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.17.1 \ - && go get github.com/client9/misspell/cmd/misspell - -# Download goreleaser binary to bin folder in $GOPATH -RUN curl -sfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh - # Which docker version to test on ARG DOCKER_VERSION=18.09.7 -ARG DEP_VERSION=0.5.4 - -# Download go-bindata binary to bin folder in $GOPATH -RUN mkdir -p /usr/local/bin \ - && curl -fsSL -o /usr/local/bin/go-bindata https://github.com/containous/go-bindata/releases/download/v1.0.0/go-bindata \ - && chmod +x /usr/local/bin/go-bindata - -# Download dep binary to bin folder in $GOPATH -RUN mkdir -p /usr/local/bin \ - && curl -fsSL -o /usr/local/bin/dep https://github.com/golang/dep/releases/download/v${DEP_VERSION}/dep-linux-amd64 \ - && chmod +x /usr/local/bin/dep # Download docker RUN mkdir -p /usr/local/bin \ && curl -fL https://download.docker.com/linux/static/stable/x86_64/docker-${DOCKER_VERSION}.tgz \ | tar -xzC /usr/local/bin --transform 's#^.+/##x' +# Download go-bindata binary to bin folder in $GOPATH +RUN mkdir -p /usr/local/bin \ + && curl -fsSL -o /usr/local/bin/go-bindata https://github.com/containous/go-bindata/releases/download/v1.0.0/go-bindata \ + && chmod +x /usr/local/bin/go-bindata + +# Download golangci-lint binary to bin folder in $GOPATH +RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.17.1 + +# Download golangci-lint and misspell binary to bin folder in $GOPATH +RUN GO111MODULE=off go get github.com/client9/misspell/cmd/misspell + +# Download goreleaser binary to bin folder in $GOPATH +RUN curl -sfL https://install.goreleaser.com/github.com/goreleaser/goreleaser.sh | sh + WORKDIR /go/src/github.com/containous/traefik + +# Download go modules +COPY go.mod . +COPY go.sum . +RUN GO111MODULE=on GOPROXY=https://proxy.golang.org go mod download + COPY . /go/src/github.com/containous/traefik diff --git a/cmd/configuration.go b/cmd/configuration.go index 795026e7a..31e730e12 100644 --- a/cmd/configuration.go +++ b/cmd/configuration.go @@ -3,8 +3,8 @@ package cmd import ( "time" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/types" ) // TraefikCmdConfiguration wraps the static configuration and extra parameters. diff --git a/cmd/healthcheck/healthcheck.go b/cmd/healthcheck/healthcheck.go index 36dcc9c5e..829e473aa 100644 --- a/cmd/healthcheck/healthcheck.go +++ b/cmd/healthcheck/healthcheck.go @@ -7,8 +7,8 @@ import ( "os" "time" - "github.com/containous/traefik/pkg/cli" - "github.com/containous/traefik/pkg/config/static" + "github.com/containous/traefik/v2/pkg/cli" + "github.com/containous/traefik/v2/pkg/config/static" ) // NewCmd builds a new HealthCheck command. diff --git a/cmd/traefik/traefik.go b/cmd/traefik/traefik.go index f41b74ffd..6c46fef78 100644 --- a/cmd/traefik/traefik.go +++ b/cmd/traefik/traefik.go @@ -11,36 +11,28 @@ import ( "strings" "time" - "github.com/containous/traefik/autogen/genstatic" - "github.com/containous/traefik/cmd" - "github.com/containous/traefik/cmd/healthcheck" - cmdVersion "github.com/containous/traefik/cmd/version" - "github.com/containous/traefik/pkg/cli" - "github.com/containous/traefik/pkg/collector" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider/acme" - "github.com/containous/traefik/pkg/provider/aggregator" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/server" - "github.com/containous/traefik/pkg/server/router" - traefiktls "github.com/containous/traefik/pkg/tls" - "github.com/containous/traefik/pkg/version" + "github.com/containous/traefik/v2/autogen/genstatic" + "github.com/containous/traefik/v2/cmd" + "github.com/containous/traefik/v2/cmd/healthcheck" + cmdVersion "github.com/containous/traefik/v2/cmd/version" + "github.com/containous/traefik/v2/pkg/cli" + "github.com/containous/traefik/v2/pkg/collector" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider/acme" + "github.com/containous/traefik/v2/pkg/provider/aggregator" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/server" + "github.com/containous/traefik/v2/pkg/server/router" + traefiktls "github.com/containous/traefik/v2/pkg/tls" + "github.com/containous/traefik/v2/pkg/version" "github.com/coreos/go-systemd/daemon" assetfs "github.com/elazarl/go-bindata-assetfs" "github.com/sirupsen/logrus" "github.com/vulcand/oxy/roundrobin" ) -func init() { - goDebug := os.Getenv("GODEBUG") - if len(goDebug) > 0 { - goDebug += "," - } - os.Setenv("GODEBUG", goDebug+"tls13=1") -} - func main() { // traefik config inits tConfig := cmd.NewTraefikConfiguration() diff --git a/cmd/version/version.go b/cmd/version/version.go index cf1f9bcf7..756306ad7 100644 --- a/cmd/version/version.go +++ b/cmd/version/version.go @@ -7,8 +7,8 @@ import ( "runtime" "text/template" - "github.com/containous/traefik/pkg/cli" - "github.com/containous/traefik/pkg/version" + "github.com/containous/traefik/v2/pkg/cli" + "github.com/containous/traefik/v2/pkg/version" ) var versionTemplate = `Version: {{.Version}} diff --git a/docs/content/assets/img/middleware/maxconnection.png b/docs/content/assets/img/middleware/inflightreq.png similarity index 100% rename from docs/content/assets/img/middleware/maxconnection.png rename to docs/content/assets/img/middleware/inflightreq.png diff --git a/docs/content/assets/styles/extra.css b/docs/content/assets/styles/extra.css index 4498eacf1..f865034b0 100644 --- a/docs/content/assets/styles/extra.css +++ b/docs/content/assets/styles/extra.css @@ -34,6 +34,10 @@ h3 { font-weight: bold !important; } +.md-typeset h5 { + text-transform: none; +} + figcaption { text-align: center; font-size: 0.8em; diff --git a/docs/content/contributing/building-testing.md b/docs/content/contributing/building-testing.md index e607511d9..95b713490 100644 --- a/docs/content/contributing/building-testing.md +++ b/docs/content/contributing/building-testing.md @@ -28,7 +28,7 @@ Successfully tagged traefik-webui:latest [...] docker build -t "traefik-dev:4475--feature-documentation" -f build.Dockerfile . Sending build context to Docker daemon 279MB -Step 1/10 : FROM golang:1.12-alpine +Step 1/10 : FROM golang:1.13rc1-alpine ---> f4bfb3d22bda [...] Successfully built 5c3c1a911277 @@ -58,7 +58,10 @@ PRE_TARGET= make test-unit ### Method 2: Using `go` -You need `go` v1.12+. +Requirements: + +- `go` v1.13+ +- environment variable `GO111MODULE=on` !!! tip "Source Directory" @@ -100,7 +103,7 @@ Beforehand, you need to get `go-bindata` (the first time) in order to be able to cd ~/go/src/github.com/containous/traefik # Get go-bindata. (Important: the ellipses are required.) -go get github.com/containous/go-bindata/... +GO111MODULE=off go get github.com/containous/go-bindata/... # Let's build @@ -118,29 +121,6 @@ You will find the Traefik executable (`traefik`) in the `~/go/src/github.com/con If you happen to update the provider's templates (located in `/templates`), you must run `go generate` to update the `autogen` package. -### Setting up dependency management - -The [dep](https://github.com/golang/dep) command is not required for building; -however, it is necessary if you need to update the dependencies (i.e., add, update, or remove third-party packages). - -You need [dep](https://github.com/golang/dep) >= 0.5.4. - -If you want to add a dependency, use `dep ensure -add` to have [dep](https://github.com/golang/dep) put it into the vendor folder and update the dep manifest/lock files (`Gopkg.toml` and `Gopkg.lock`, respectively). - -A following `make dep-prune` run should be triggered to trim down the size of the vendor folder. -The final result must be committed into VCS. - -Here's a full example using dep to add a new dependency: - -```bash -# install the new main dependency github.com/foo/bar and minimize vendor size -$ dep ensure -add github.com/foo/bar -# generate (Only required to integrate other components such as web dashboard) -$ go generate -# Standard go build -$ go build ./cmd/traefik -``` - ## Testing ### Method 1: `Docker` and `make` diff --git a/docs/content/https/acme.md b/docs/content/https/acme.md index eed817ece..7a03295ae 100644 --- a/docs/content/https/acme.md +++ b/docs/content/https/acme.md @@ -212,6 +212,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [Alibaba Cloud](https://www.alibabacloud.com) | `alidns` | `ALICLOUD_ACCESS_KEY`, `ALICLOUD_SECRET_KEY`, `ALICLOUD_REGION_ID` | [Additional configuration](https://go-acme.github.io/lego/dns/alidns) | | [Auroradns](https://www.pcextreme.com/aurora/dns) | `auroradns` | `AURORA_USER_ID`, `AURORA_KEY`, `AURORA_ENDPOINT` | [Additional configuration](https://go-acme.github.io/lego/dns/auroradns) | | [Azure](https://azure.microsoft.com/services/dns/) | `azure` | `AZURE_CLIENT_ID`, `AZURE_CLIENT_SECRET`, `AZURE_SUBSCRIPTION_ID`, `AZURE_TENANT_ID`, `AZURE_RESOURCE_GROUP`, `[AZURE_METADATA_ENDPOINT]` | [Additional configuration](https://go-acme.github.io/lego/dns/azure) | +| [Bindman](https://github.com/labbsr0x/bindman-dns-webhook) | `bindman` | `BINDMAN_MANAGER_ADDRESS` | [Additional configuration](https://go-acme.github.io/lego/dns/bindman) | | [Blue Cat](https://www.bluecatnetworks.com/) | `bluecat` | `BLUECAT_SERVER_URL`, `BLUECAT_USER_NAME`, `BLUECAT_PASSWORD`, `BLUECAT_CONFIG_NAME`, `BLUECAT_DNS_VIEW` | [Additional configuration](https://go-acme.github.io/lego/dns/bluecat) | | [ClouDNS](https://www.cloudns.net/) | `cloudns` | `CLOUDNS_AUTH_ID`, `CLOUDNS_AUTH_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudns) | | [Cloudflare](https://www.cloudflare.com) | `cloudflare` | `CF_API_EMAIL`, `CF_API_KEY` - The `Global API Key` needs to be used, not the `Origin CA Key` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudflare) | @@ -225,6 +226,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [DreamHost](https://www.dreamhost.com/) | `dreamhost` | `DREAMHOST_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/dreamhost) | | [Duck DNS](https://www.duckdns.org/) | `duckdns` | `DUCKDNS_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/duckdns) | | [Dyn](https://dyn.com) | `dyn` | `DYN_CUSTOMER_NAME`, `DYN_USER_NAME`, `DYN_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/dyn) | +| [EasyDNS](https://easydns.com/) | `easydns` | `EASYDNS_TOKEN`, `EASYDNS_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/easydns) | | External Program | `exec` | `EXEC_PATH` | [Additional configuration](https://go-acme.github.io/lego/dns/exec) | | [Exoscale](https://www.exoscale.com) | `exoscale` | `EXOSCALE_API_KEY`, `EXOSCALE_API_SECRET`, `EXOSCALE_ENDPOINT` | [Additional configuration](https://go-acme.github.io/lego/dns/exoscale) | | [Fast DNS](https://www.akamai.com/) | `fastdns` | `AKAMAI_CLIENT_TOKEN`, `AKAMAI_CLIENT_SECRET`, `AKAMAI_ACCESS_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/fastdns) | @@ -237,13 +239,15 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | HTTP request | `httpreq` | `HTTPREQ_ENDPOINT`, `HTTPREQ_MODE`, `HTTPREQ_USERNAME`, `HTTPREQ_PASSWORD` [^1] | [Additional configuration](https://go-acme.github.io/lego/dns/httpreq) | | [IIJ](https://www.iij.ad.jp/) | `iij` | `IIJ_API_ACCESS_KEY`, `IIJ_API_SECRET_KEY`, `IIJ_DO_SERVICE_CODE` | [Additional configuration](https://go-acme.github.io/lego/dns/iij) | | [INWX](https://www.inwx.de/en) | `inwx` | `INWX_USERNAME`, `INWX_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/inwx) | +| [Joker.com](https://joker.com) | `joker` | `JOKER_API_KEY` or `JOKER_USERNAME`, `JOKER_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/joker) | | [Lightsail](https://aws.amazon.com/lightsail/) | `lightsail` | `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, `DNS_ZONE` | [Additional configuration](https://go-acme.github.io/lego/dns/lightsail) | | [Linode](https://www.linode.com) | `linode` | `LINODE_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/linode) | | [Linode v4](https://www.linode.com) | `linodev4` | `LINODE_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/linodev4) | -| manual | - | none, but you need to run Traefik interactively [^4], turn on debug log to see instructions and press Enter. | | +| manual | - | none, but you need to run Traefik interactively [^4], turn on debug log to see instructions and press Enter. | | | [MyDNS.jp](https://www.mydns.jp/) | `mydnsjp` | `MYDNSJP_MASTER_ID`, `MYDNSJP_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/mydnsjp) | | [Namecheap](https://www.namecheap.com) | `namecheap` | `NAMECHEAP_API_USER`, `NAMECHEAP_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/namecheap) | | [name.com](https://www.name.com/) | `namedotcom` | `NAMECOM_USERNAME`, `NAMECOM_API_TOKEN`, `NAMECOM_SERVER` | [Additional configuration](https://go-acme.github.io/lego/dns/namedotcom) | +| [Namesilo](https://www.namesilo.com/) | `namesilo` | `NAMESILO_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/namesilo) | | [Netcup](https://www.netcup.eu/) | `netcup` | `NETCUP_CUSTOMER_NUMBER`, `NETCUP_API_KEY`, `NETCUP_API_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/netcup) | | [NIFCloud](https://cloud.nifty.com/service/dns.htm) | `nifcloud` | `NIFCLOUD_ACCESS_KEY_ID`, `NIFCLOUD_SECRET_ACCESS_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/nifcloud) | | [Ns1](https://ns1.com/) | `ns1` | `NS1_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/ns1) | @@ -260,6 +264,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [Stackpath](https://www.stackpath.com/) | `stackpath` | `STACKPATH_CLIENT_ID`, `STACKPATH_CLIENT_SECRET`, `STACKPATH_STACK_ID` | [Additional configuration](https://go-acme.github.io/lego/dns/stackpath) | | [TransIP](https://www.transip.nl/) | `transip` | `TRANSIP_ACCOUNT_NAME`, `TRANSIP_PRIVATE_KEY_PATH` | [Additional configuration](https://go-acme.github.io/lego/dns/transip) | | [VegaDNS](https://github.com/shupp/VegaDNS-API) | `vegadns` | `SECRET_VEGADNS_KEY`, `SECRET_VEGADNS_SECRET`, `VEGADNS_URL` | [Additional configuration](https://go-acme.github.io/lego/dns/vegadns) | +| [Versio](https://www.versio.nl/domeinnamen) | `versio` | `VERSIO_USERNAME`, `VERSIO_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/versio) | | [Vscale](https://vscale.io/) | `vscale` | `VSCALE_API_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/vscale) | | [VULTR](https://www.vultr.com) | `vultr` | `VULTR_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/vultr) | | [Zone.ee](https://www.zone.ee) | `zoneee` | `ZONEEE_API_USER`, `ZONEEE_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/zoneee) | diff --git a/docs/content/middlewares/inflightreq.md b/docs/content/middlewares/inflightreq.md new file mode 100644 index 000000000..9b07b7a82 --- /dev/null +++ b/docs/content/middlewares/inflightreq.md @@ -0,0 +1,247 @@ +# InFlightReq + +Limiting the Number of Simultaneous In-Flight Requests +{: .subtitle } + +![InFlightReq](../assets/img/middleware/inflightreq.png) + +To proactively prevent services from being overwhelmed with high load, a limit on the number of simultaneous in-flight requests can be applied. + +## Configuration Examples + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.amount=10" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-inflightreq +spec: + inFlightReq: + amount: 10 +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-inflightreq.inflightreq.amount": "10" +} +``` + +```yaml tab="Rancher" +# Limiting to 10 simultaneous connections +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.amount=10" +``` + +```toml tab="File (TOML)" +# Limiting to 10 simultaneous connections +[http.middlewares] + [http.middlewares.test-inflightreq.inFlightReq] + amount = 10 +``` + +```yaml tab="File (YAML)" +# Limiting to 10 simultaneous connections +http: + middlewares: + test-inflightreq: + inFlightReq: + amount: 10 +``` + +## Configuration Options + +### `amount` + +The `amount` option defines the maximum amount of allowed simultaneous in-flight request. +The middleware will return an `HTTP 429 Too Many Requests` if there are already `amount` requests in progress (based on the same `sourceCriterion` strategy). + +### `sourceCriterion` + +SourceCriterion defines what criterion is used to group requests as originating from a common source. +The precedence order is `ipStrategy`, then `requestHeaderName`, then `requestHost`. +If none are set, the default is to use the `requestHost`. + +#### `sourceCriterion.ipStrategy` + +The `ipStrategy` option defines two parameters that sets how Traefik will determine the client IP: `depth`, and `excludedIPs`. + +##### `ipStrategy.depth` + +The `depth` option tells Traefik to use the `X-Forwarded-For` header and take the IP located at the `depth` position (starting from the right). + +- If `depth` is greater than the total number of IPs in `X-Forwarded-For`, then the client IP will be empty. +- `depth` is ignored if its value is is lesser than or equal to 0. + +!!! note "Example of Depth & X-Forwarded-For" + + If `depth` was equal to 2, and the request `X-Forwarded-For` header was `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` then the "real" client IP would be `"10.0.0.1"` (at depth 4) but the IP used as the criterion would be `"12.0.0.1"` (`depth=2`). + + | `X-Forwarded-For` | `depth` | clientIP | + |-----------------------------------------|---------|--------------| + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `1` | `"13.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `3` | `"11.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `5` | `""` | + +##### `ipStrategy.excludedIPs` + +`excludedIPs` tells Traefik to scan the `X-Forwarded-For` header and pick the first IP not in the list. + +!!! important + If `depth` is specified, `excludedIPs` is ignored. + +!!! note "Example of ExcludedIPs & X-Forwarded-For" + + | `X-Forwarded-For` | `excludedIPs` | clientIP | + |-----------------------------------------|-----------------------|--------------| + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"12.0.0.1,13.0.0.1"` | `"11.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"15.0.0.1,13.0.0.1"` | `"12.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"10.0.0.1,13.0.0.1"` | `"12.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"15.0.0.1,16.0.0.1"` | `"13.0.0.1"` | + | `"10.0.0.1,11.0.0.1"` | `"10.0.0.1,11.0.0.1"` | `""` | + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.ipstrategy.excludedips=127.0.0.1/32, 192.168.1.7" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-inflightreq +spec: + inFlightReq: + sourceCriterion: + ipStrategy: + excludedIPs: + - 127.0.0.1/32 + - 192.168.1.7 +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.ipstrategy.excludedips=127.0.0.1/32, 192.168.1.7" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.ipstrategy.excludedips": "127.0.0.1/32, 192.168.1.7" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-inflightreq.inflightreq] + [http.middlewares.test-inflightreq.inFlightReq.sourceCriterion.ipStrategy] + excludedIPs = ["127.0.0.1/32", "192.168.1.7"] +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-inflightreq: + inFlightReq: + sourceCriterion: + ipStrategy: + excludedIPs: + - "127.0.0.1/32" + - "192.168.1.7" +``` + +#### `sourceCriterion.requestHeaderName` + +Requests having the same value for the given header are grouped as coming from the same source. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requestheadername=username" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-inflightreq +spec: + inFlightReq: + sourceCriterion: + requestHeaderName: username +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requestheadername=username" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requestheadername": "username" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-inflightreq.inflightreq] + [http.middlewares.test-inflightreq.inFlightReq.sourceCriterion] + requestHeaderName = "username" +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-inflightreq: + inFlightReq: + sourceCriterion: + requestHeaderName: username +``` + +#### `sourceCriterion.requestHost` + +Whether to consider the request host as the source. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requesthost=true" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-inflightreq +spec: + inFlightReq: + sourceCriterion: + requestHost: true +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requesthost=true" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-inflightreq.inflightreq.sourcecriterion.requesthost": "true" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-inflightreq.inflightreq] + [http.middlewares.test-inflightreq.inFlightReq.sourceCriterion] + requestHost = true +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-inflightreq: + inFlightReq: + sourceCriterion: + requestHost: true +``` diff --git a/docs/content/middlewares/maxconnection.md b/docs/content/middlewares/maxconnection.md deleted file mode 100644 index bfddf30d9..000000000 --- a/docs/content/middlewares/maxconnection.md +++ /dev/null @@ -1,71 +0,0 @@ -# MaxConnection - -Limiting the Number of Simultaneous Clients -{: .subtitle } - -![MaxConnection](../assets/img/middleware/maxconnection.png) - -To proactively prevent services from being overwhelmed with high load, a maximum connection limit can be applied. - -## Configuration Examples - -```yaml tab="Docker" -# Limiting to 10 simultaneous connections -labels: -- "traefik.http.middlewares.test-maxconn.maxconn.amount=10" -``` - -```yaml tab="Kubernetes" -apiVersion: traefik.containo.us/v1alpha1 -kind: Middleware -metadata: - name: test-maxconn -spec: - maxConn: - amount: 10 -``` - -```json tab="Marathon" -"labels": { - "traefik.http.middlewares.test-maxconn.maxconn.amount": "10" -} -``` - -```yaml tab="Rancher" -# Limiting to 10 simultaneous connections -labels: -- "traefik.http.middlewares.test-maxconn.maxconn.amount=10" -``` - -```toml tab="File (TOML)" -# Limiting to 10 simultaneous connections -[http.middlewares] - [http.middlewares.test-maxconn.maxConn] - amount = 10 -``` - -```yaml tab="File (YAML)" -# Limiting to 10 simultaneous connections -http: - middlewares: - test-maxconn: - maxConn: - amount: 10 -``` - -## Configuration Options - -### `amount` - -The `amount` option defines the maximum amount of allowed simultaneous connections. -The middleware will return an `HTTP 429 Too Many Requests` if there are already `amount` requests in progress (based on the same `extractorFunc` strategy). - -### `extractorFunc` - -The `extractorFunc` defines the strategy used to categorize requests. - -The possible values are: - -- `request.host` categorizes requests based on the request host. -- `client.ip` categorizes requests based on the client ip. -- `request.header.ANY_HEADER` categorizes requests based on the provided `ANY_HEADER` value. diff --git a/docs/content/middlewares/overview.md b/docs/content/middlewares/overview.md index 91740e41f..a69ccddca 100644 --- a/docs/content/middlewares/overview.md +++ b/docs/content/middlewares/overview.md @@ -208,7 +208,7 @@ and therefore this specification would be ignored even if present. | [ForwardAuth](forwardauth.md) | Authentication delegation | Security, Authentication | | [Headers](headers.md) | Add / Update headers | Security | | [IPWhiteList](ipwhitelist.md) | Limit the allowed client IPs | Security, Request lifecycle | -| [MaxConnection](maxconnection.md) | Limit the number of simultaneous connections | Security, Request lifecycle | +| [InFlightReq](inflightreq.md) | Limit the number of simultaneous connections | Security, Request lifecycle | | [PassTLSClientCert](passtlsclientcert.md) | Adding Client Certificates in a Header | Security | | [RateLimit](ratelimit.md) | Limit the call frequency | Security, Request lifecycle | | [RedirectScheme](redirectscheme.md) | Redirect easily the client elsewhere | Request lifecycle | diff --git a/docs/content/middlewares/ratelimit.md b/docs/content/middlewares/ratelimit.md index fa3856df5..058c67b27 100644 --- a/docs/content/middlewares/ratelimit.md +++ b/docs/content/middlewares/ratelimit.md @@ -1,9 +1,6 @@ # RateLimit -!!! warning - This middleware is disable for now. - -Protection from Too Many Calls +To Control the Number of Requests Going to a Service {: .subtitle } ![RateLimit](../assets/img/middleware/ratelimit.png) @@ -13,124 +10,337 @@ The RateLimit middleware ensures that services will receive a _fair_ number of r ## Configuration Example ```yaml tab="Docker" -# Here, an average of 5 requests every 3 seconds is allowed and an average of 100 requests every 10 seconds. -# These can "burst" up to 10 and 200 in each period, respectively. +# Here, an average of 100 requests per second is allowed. +# In addition, a burst of 50 requests is allowed. labels: -- "traefik.http.middlewares.test-ratelimit.ratelimit.extractorfunc=client.ip" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.period=10s" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.average=100" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.burst=200" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.period=3s" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.average=5" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.burst=10" - +- "traefik.http.middlewares.test-ratelimit.ratelimit.average=100" +- "traefik.http.middlewares.test-ratelimit.ratelimit.burst=50" ``` ```yaml tab="Kubernetes" -# Here, an average of 5 requests every 3 seconds is allowed and an average of 100 requests every 10 seconds. -# These can "burst" up to 10 and 200 in each period, respectively. +# Here, an average of 100 requests per second is allowed. +# In addition, a burst of 50 requests is allowed. apiVersion: traefik.containo.us/v1alpha1 kind: Middleware metadata: name: test-ratelimit spec: rateLimit: - extractorFunc: client.ip - rateSet: - rate0: - period: 10s - average: 100 - burst: 200 - rate1: - period: 3s - average: 5 - burst: 10 + average: 100 + burst: 50 ``` ```json tab="Marathon" "labels": { - "traefik.http.middlewares.test-ratelimit.ratelimit.extractorfunc": "client.ip", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.period": "10s", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.average": "100", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.burst": "200", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.period": "3s", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.average": "5", - "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.burst": "10" + "traefik.http.middlewares.test-ratelimit.ratelimit.average": "100", + "traefik.http.middlewares.test-ratelimit.ratelimit.burst": "50" } ``` ```yaml tab="Rancher" -# Here, an average of 5 requests every 3 seconds is allowed and an average of 100 requests every 10 seconds. -# These can "burst" up to 10 and 200 in each period, respectively. +# Here, an average of 100 requests per second is allowed. +# In addition, a burst of 50 requests is allowed. labels: -- "traefik.http.middlewares.test-ratelimit.ratelimit.extractorfunc=client.ip" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.period=10s" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.average=100" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate0.burst=200" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.period=3s" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.average=5" -- "traefik.http.middlewares.test-ratelimit.ratelimit.rateset.rate1.burst=10" - +- "traefik.http.middlewares.test-ratelimit.ratelimit.average=100" +- "traefik.http.middlewares.test-ratelimit.ratelimit.burst=50" ``` ```toml tab="File (TOML)" -# Here, an average of 5 requests every 3 seconds is allowed and an average of 100 requests every 10 seconds. -# These can "burst" up to 10 and 200 in each period, respectively. +# Here, an average of 100 requests per second is allowed. +# In addition, a burst of 50 requests is allowed. [http.middlewares] [http.middlewares.test-ratelimit.rateLimit] - extractorFunc = "client.ip" - - [http.middlewares.test-ratelimit.rateLimit.rateSet.rate0] - period = "10s" - average = 100 - burst = 200 - - [http.middlewares.test-ratelimit.rateLimit.rateSet.rate1] - period = "3s" - average = 5 - burst = 10 + average = 100 + burst = 50 ``` ```yaml tab="File (YAML)" -# Here, an average of 5 requests every 3 seconds is allowed and an average of 100 requests every 10 seconds. -# These can "burst" up to 10 and 200 in each period, respectively. +# Here, an average of 100 requests per second is allowed. +# In addition, a burst of 50 requests is allowed. http: middlewares: test-ratelimit: rateLimit: - extractorFunc: "client.ip" - rateSet: - rate0: - period: "10s" - average: 100 - burst: 200 - rate1: - period: "3s" - average: 5 - burst: 10 + average: 100 + burst: 50 ``` ## Configuration Options -### `extractorFunc` +### `average` + +Average is the maximum rate, in requests/s, allowed for the given source. +It defaults to 0, which means no rate limiting. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.average=100" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-ratelimit +spec: + rateLimit: + average: 100 +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-ratelimit.ratelimit.average": "100", +} +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.average=100" +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-ratelimit.rateLimit] + average = 100 +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-ratelimit: + rateLimit: + average: 100 +``` + +### `burst` + +Burst is the maximum number of requests allowed to go through in the same arbitrarily small period of time. +It defaults to 1. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.burst=100" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-ratelimit +spec: + rateLimit: + burst: 100 +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-ratelimit.ratelimit.burst": "100", +} +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.burst=100" + +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-ratelimit.rateLimit] + burst = 100 +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-ratelimit: + rateLimit: + burst: 100 +``` + +### `sourceCriterion` -The `extractorFunc` option defines the strategy used to categorize requests. +SourceCriterion defines what criterion is used to group requests as originating from a common source. +The precedence order is `ipStrategy`, then `requestHeaderName`, then `requestHost`. +If none are set, the default is to use the request's remote address field (as an `ipStrategy`). -The possible values are: +#### `sourceCriterion.ipStrategy` -- `request.host` categorizes requests based on the request host. -- `client.ip` categorizes requests based on the client ip. -- `request.header.ANY_HEADER` categorizes requests based on the provided `ANY_HEADER` value. +The `ipStrategy` option defines two parameters that sets how Traefik will determine the client IP: `depth`, and `excludedIPs`. -### `rateSet` +##### `ipStrategy.depth` -You can combine multiple rate limits. -The rate limit will trigger with the first reached limit. +The `depth` option tells Traefik to use the `X-Forwarded-For` header and take the IP located at the `depth` position (starting from the right). -Each rate limit has 3 options, `period`, `average`, and `burst`. +- If `depth` is greater than the total number of IPs in `X-Forwarded-For`, then the client IP will be empty. +- `depth` is ignored if its value is is lesser than or equal to 0. -The rate limit will allow an average of `average` requests every `period`, with a maximum of `burst` request on that period. +!!! note "Example of Depth & X-Forwarded-For" -!!! note "Period Format" + If `depth` was equal to 2, and the request `X-Forwarded-For` header was `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` then the "real" client IP would be `"10.0.0.1"` (at depth 4) but the IP used as the criterion would be `"12.0.0.1"` (`depth=2`). - Period is to be given in a format understood by [time.ParseDuration](https://golang.org/pkg/time/#ParseDuration). + | `X-Forwarded-For` | `depth` | clientIP | + |-----------------------------------------|---------|--------------| + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `1` | `"13.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `3` | `"11.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `5` | `""` | + +##### `ipStrategy.excludedIPs` + +`excludedIPs` tells Traefik to scan the `X-Forwarded-For` header and pick the first IP not in the list. + +!!! important + If `depth` is specified, `excludedIPs` is ignored. + +!!! note "Example of ExcludedIPs & X-Forwarded-For" + + | `X-Forwarded-For` | `excludedIPs` | clientIP | + |-----------------------------------------|-----------------------|--------------| + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"12.0.0.1,13.0.0.1"` | `"11.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"15.0.0.1,13.0.0.1"` | `"12.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"10.0.0.1,13.0.0.1"` | `"12.0.0.1"` | + | `"10.0.0.1,11.0.0.1,12.0.0.1,13.0.0.1"` | `"15.0.0.1,16.0.0.1"` | `"13.0.0.1"` | + | `"10.0.0.1,11.0.0.1"` | `"10.0.0.1,11.0.0.1"` | `""` | + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.ipstrategy.excludedips=127.0.0.1/32, 192.168.1.7" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-ratelimit +spec: + rateLimit: + sourceCriterion: + ipStrategy: + excludedIPs: + - 127.0.0.1/32 + - 192.168.1.7 +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.ipstrategy.excludedips=127.0.0.1/32, 192.168.1.7" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.ipstrategy.excludedips": "127.0.0.1/32, 192.168.1.7" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-ratelimit.rateLimit] + [http.middlewares.test-ratelimit.rateLimit.sourceCriterion.ipStrategy] + excludedIPs = ["127.0.0.1/32", "192.168.1.7"] +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-ratelimit: + rateLimit: + sourceCriterion: + ipStrategy: + excludedIPs: + - "127.0.0.1/32" + - "192.168.1.7" +``` + +#### `sourceCriterion.requestHeaderName` + +Requests having the same value for the given header are grouped as coming from the same source. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requestheadername=username" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-ratelimit +spec: + rateLimit: + sourceCriterion: + requestHeaderName: username +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requestheadername=username" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requestheadername": "username" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-ratelimit.rateLimit] + [http.middlewares.test-ratelimit.rateLimit.sourceCriterion] + requestHeaderName = "username" +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-ratelimit: + rateLimit: + sourceCriterion: + requestHeaderName: username +``` + +#### `sourceCriterion.requestHost` + +Whether to consider the request host as the source. + +```yaml tab="Docker" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requesthost=true" +``` + +```yaml tab="Kubernetes" +apiVersion: traefik.containo.us/v1alpha1 +kind: Middleware +metadata: + name: test-ratelimit +spec: + rateLimit: + sourceCriterion: + requestHost: true +``` + +```yaml tab="Rancher" +labels: +- "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requesthost=true" +``` + +```json tab="Marathon" +"labels": { + "traefik.http.middlewares.test-ratelimit.ratelimit.sourcecriterion.requesthost": "true" +} +``` + +```toml tab="File (TOML)" +[http.middlewares] + [http.middlewares.test-ratelimit.rateLimit] + [http.middlewares.test-ratelimit.rateLimit.sourceCriterion] + requestHost = true +``` + +```yaml tab="File (YAML)" +http: + middlewares: + test-ratelimit: + rateLimit: + sourceCriterion: + requestHost: true +``` \ No newline at end of file diff --git a/docs/content/middlewares/redirectregex.md b/docs/content/middlewares/redirectregex.md index 68b9343db..2d1a19d76 100644 --- a/docs/content/middlewares/redirectregex.md +++ b/docs/content/middlewares/redirectregex.md @@ -13,7 +13,7 @@ RegexRedirect redirect a request from an url to another with regex matching and # Redirect with domain replacement labels: - "traefik.http.middlewares.test-redirectregex.redirectregex.regex=^http://localhost/(.*)" -- "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$1" +- "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$${1}" ``` ```yaml tab="Kubernetes" @@ -25,13 +25,13 @@ metadata: spec: redirectRegex: regex: ^http://localhost/(.*) - replacement: http://mydomain/$1 + replacement: http://mydomain/${1} ``` ```json tab="Marathon" "labels": { "traefik.http.middlewares.test-redirectregex.redirectregex.regex": "^http://localhost/(.*)", - "traefik.http.middlewares.test-redirectregex.redirectregex.replacement": "http://mydomain/$1" + "traefik.http.middlewares.test-redirectregex.redirectregex.replacement": "http://mydomain/${1}" } ``` @@ -39,7 +39,7 @@ spec: # Redirect with domain replacement labels: - "traefik.http.middlewares.test-redirectregex.redirectregex.regex=^http://localhost/(.*)" -- "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/$1" +- "traefik.http.middlewares.test-redirectregex.redirectregex.replacement=http://mydomain/${1}" ``` ```toml tab="File (TOML)" @@ -47,7 +47,7 @@ labels: [http.middlewares] [http.middlewares.test-redirectregex.redirectRegex] regex = "^http://localhost/(.*)" - replacement = "http://mydomain/$1" + replacement = "http://mydomain/${1}" ``` ```yaml tab="File (YAML)" @@ -57,7 +57,7 @@ http: test-redirectregex: redirectRegex: regex: "^http://localhost/(.*)" - replacement: "http://mydomain/$1" + replacement: "http://mydomain/${1}" ``` ## Configuration Options @@ -80,5 +80,5 @@ The `regex` option is the regular expression to match and capture elements from ### `replacement` -The `replacement` option defines how to modify the URl to have the new target URL. +The `replacement` option defines how to modify the URL to have the new target URL. \ No newline at end of file diff --git a/docs/content/providers/kubernetes-crd.md b/docs/content/providers/kubernetes-crd.md index a2f396ef5..637024e8b 100644 --- a/docs/content/providers/kubernetes-crd.md +++ b/docs/content/providers/kubernetes-crd.md @@ -198,11 +198,13 @@ spec: # "Parameter", etc, to support simpler forms of rule matching, but for now we # only support "Rule". kind: Rule - # Priority disambiguates rules of the same length, for route matching. + # (optional) Priority disambiguates rules of the same length, for route matching. priority: 12 services: - name: whoami port: 80 + # (default 1) A weight used by the weighted round-robin strategy (WRR). + weight: 1 --- apiVersion: traefik.containo.us/v1alpha1 diff --git a/docs/content/reference/dynamic-configuration/docker-labels.yml b/docs/content/reference/dynamic-configuration/docker-labels.yml index bde9e1c2c..c01640149 100644 --- a/docs/content/reference/dynamic-configuration/docker-labels.yml +++ b/docs/content/reference/dynamic-configuration/docker-labels.yml @@ -64,8 +64,12 @@ - "traefik.http.middlewares.middleware10.ipwhitelist.ipstrategy.depth=42" - "traefik.http.middlewares.middleware10.ipwhitelist.ipstrategy.excludedips=foobar, foobar" - "traefik.http.middlewares.middleware10.ipwhitelist.sourcerange=foobar, foobar" -- "traefik.http.middlewares.middleware11.maxconn.amount=42" -- "traefik.http.middlewares.middleware11.maxconn.extractorfunc=foobar" +- "traefik.http.middlewares.middleware11.inflightreq.amount=42" +- "traefik.http.middlewares.middleware11.inflightreq.sourcecriterion.requestheadername=foobar" +- "traefik.http.middlewares.middleware11.inflightreq.sourcecriterion.requesthost=true" +- "traefik.http.middlewares.middleware11.inflightreq.sourcecriterion.ipstrategy.depth=42" +- "traefik.http.middlewares.middleware11.inflightreq.sourcecriterion.ipstrategy.excludedips=foobar, foobar" +- "traefik.http.middlewares.middleware11.inflightreq.sourcecriterion.requesthost=true" - "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.commonname=true" - "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.country=true" - "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.domaincomponent=true" @@ -130,10 +134,10 @@ - "traefik.http.services.service0.loadbalancer.healthcheck.timeout=foobar" - "traefik.http.services.service0.loadbalancer.passhostheader=true" - "traefik.http.services.service0.loadbalancer.responseforwarding.flushinterval=foobar" -- "traefik.http.services.service0.loadbalancer.stickiness=true" -- "traefik.http.services.service0.loadbalancer.stickiness.cookiename=foobar" -- "traefik.http.services.service0.loadbalancer.stickiness.httponlycookie=true" -- "traefik.http.services.service0.loadbalancer.stickiness.securecookie=true" +- "traefik.http.services.service0.loadbalancer.sticky=true" +- "traefik.http.services.service0.loadbalancer.sticky.cookie.name=foobar" +- "traefik.http.services.service0.loadbalancer.sticky.cookie.httponly=true" +- "traefik.http.services.service0.loadbalancer.sticky.cookie.secure=true" - "traefik.http.services.service0.loadbalancer.server.port=foobar" - "traefik.http.services.service0.loadbalancer.server.scheme=foobar" - "traefik.http.services.service1.loadbalancer.healthcheck.headers.name0=foobar" @@ -146,10 +150,10 @@ - "traefik.http.services.service1.loadbalancer.healthcheck.timeout=foobar" - "traefik.http.services.service1.loadbalancer.passhostheader=true" - "traefik.http.services.service1.loadbalancer.responseforwarding.flushinterval=foobar" -- "traefik.http.services.service1.loadbalancer.stickiness=true" -- "traefik.http.services.service1.loadbalancer.stickiness.cookiename=foobar" -- "traefik.http.services.service1.loadbalancer.stickiness.httponlycookie=true" -- "traefik.http.services.service1.loadbalancer.stickiness.securecookie=true" +- "traefik.http.services.service1.loadbalancer.sticky=true" +- "traefik.http.services.service1.loadbalancer.sticky.cookie.name=foobar" +- "traefik.http.services.service1.loadbalancer.sticky.cookie.httponly=true" +- "traefik.http.services.service1.loadbalancer.sticky.cookie.secure=true" - "traefik.http.services.service1.loadbalancer.server.port=foobar" - "traefik.http.services.service1.loadbalancer.server.scheme=foobar" - "traefik.tcp.routers.tcprouter0.entrypoints=foobar, foobar" diff --git a/docs/content/reference/dynamic-configuration/file.toml b/docs/content/reference/dynamic-configuration/file.toml index 1bc9c258c..71ad8d891 100644 --- a/docs/content/reference/dynamic-configuration/file.toml +++ b/docs/content/reference/dynamic-configuration/file.toml @@ -35,56 +35,47 @@ main = "foobar" sans = ["foobar", "foobar"] [http.services] - [http.services.Service0] - [http.services.Service0.loadBalancer] + [http.services.Service01] + [http.services.Service01.loadBalancer] passHostHeader = true - [http.services.Service0.loadBalancer.stickiness] - cookieName = "foobar" - secureCookie = true - httpOnlyCookie = true + [http.services.Service01.loadBalancer.sticky] + [http.services.Service01.loadBalancer.sticky.cookie] + name = "foobar" + secure = true + httpOnly = true - [[http.services.Service0.loadBalancer.servers]] + [[http.services.Service01.loadBalancer.servers]] url = "foobar" - [[http.services.Service0.loadBalancer.servers]] + [[http.services.Service01.loadBalancer.servers]] url = "foobar" - [http.services.Service0.loadBalancer.healthCheck] + [http.services.Service01.loadBalancer.healthCheck] scheme = "foobar" path = "foobar" port = 42 interval = "foobar" timeout = "foobar" hostname = "foobar" - [http.services.Service0.loadBalancer.healthCheck.headers] + [http.services.Service01.loadBalancer.healthCheck.headers] name0 = "foobar" name1 = "foobar" - [http.services.Service0.loadBalancer.responseForwarding] + [http.services.Service01.loadBalancer.responseForwarding] flushInterval = "foobar" - [http.services.Service1] - [http.services.Service1.loadBalancer] - passHostHeader = true - [http.services.Service1.loadBalancer.stickiness] - cookieName = "foobar" - secureCookie = true - httpOnlyCookie = true + [http.services.Service02] + [http.services.Service02.weighted] - [[http.services.Service1.loadBalancer.servers]] - url = "foobar" + [[http.services.Service02.weighted.services]] + name = "foobar" + weight = 42 - [[http.services.Service1.loadBalancer.servers]] - url = "foobar" - [http.services.Service1.loadBalancer.healthCheck] - scheme = "foobar" - path = "foobar" - port = 42 - interval = "foobar" - timeout = "foobar" - hostname = "foobar" - [http.services.Service1.loadBalancer.healthCheck.headers] - name0 = "foobar" - name1 = "foobar" - [http.services.Service1.loadBalancer.responseForwarding] - flushInterval = "foobar" + [[http.services.Service02.weighted.services]] + name = "foobar" + weight = 42 + [http.services.Service02.weighted.sticky] + [http.services.Service02.weighted.sticky.cookie] + name = "foobar" + secure = true + httpOnly = true [http.middlewares] [http.middlewares.Middleware00] [http.middlewares.Middleware00.addPrefix] @@ -179,9 +170,14 @@ depth = 42 excludedIPs = ["foobar", "foobar"] [http.middlewares.Middleware11] - [http.middlewares.Middleware11.maxConn] + [http.middlewares.Middleware11.inFlightReq] amount = 42 - extractorFunc = "foobar" + [http.middlewares.Middleware11.inFlightReq.sourceCriterion] + requestHeaderName = "foobar" + requestHost = true + [http.middlewares.Middleware11.inFlightReq.sourceCriterion.ipStrategy] + depth = 42 + excludedIPs = ["foobar", "foobar"] [http.middlewares.Middleware12] [http.middlewares.Middleware12.passTLSClientCert] pem = true diff --git a/docs/content/reference/dynamic-configuration/file.yaml b/docs/content/reference/dynamic-configuration/file.yaml index a789b6d0d..89753c2a5 100644 --- a/docs/content/reference/dynamic-configuration/file.yaml +++ b/docs/content/reference/dynamic-configuration/file.yaml @@ -45,34 +45,13 @@ http: - foobar - foobar services: - Service0: + Service01: loadBalancer: - stickiness: - cookieName: foobar - secureCookie: true - httpOnlyCookie: true - servers: - - url: foobar - - url: foobar - healthCheck: - scheme: foobar - path: foobar - port: 42 - interval: foobar - timeout: foobar - hostname: foobar - headers: - name0: foobar - name1: foobar - passHostHeader: true - responseForwarding: - flushInterval: foobar - Service1: - loadBalancer: - stickiness: - cookieName: foobar - secureCookie: true - httpOnlyCookie: true + sticky: + cookie: + name: foobar + secure: true + httpOnly: true servers: - url: foobar - url: foobar @@ -89,6 +68,18 @@ http: passHostHeader: true responseForwarding: flushInterval: foobar + Service02: + weighted: + services: + - name: foobar + weight: 42 + - name: foobar + weight: 42 + sticky: + cookie: + name: foobar + secure: true + httpOnly: true middlewares: Middleware00: addPrefix: @@ -207,9 +198,14 @@ http: - foobar - foobar Middleware11: - maxConn: + inFlightReq: amount: 42 - extractorFunc: foobar + sourceCriterion: + ipStrategy: + depth: 42 + excludedIPs: [ foobar, foobar ] + requestHeaderName: foobar + requestHost: true Middleware12: passTLSClientCert: pem: true @@ -263,6 +259,16 @@ http: regex: - foobar - foobar + Middleware20: + rateLimit: + average: 42 + burst: 42 + sourceCriterion: + ipStrategy: + depth: 42 + excludedIPs: [ foobar, foobar ] + requestHeaderName: foobar + requestHost: true tcp: routers: TCPRouter0: diff --git a/docs/content/reference/dynamic-configuration/marathon-labels.json b/docs/content/reference/dynamic-configuration/marathon-labels.json index a3419d75e..163924b4a 100644 --- a/docs/content/reference/dynamic-configuration/marathon-labels.json +++ b/docs/content/reference/dynamic-configuration/marathon-labels.json @@ -64,8 +64,11 @@ "traefik.http.middlewares.middleware10.ipwhitelist.ipstrategy.depth": "42", "traefik.http.middlewares.middleware10.ipwhitelist.ipstrategy.excludedips": "foobar, foobar", "traefik.http.middlewares.middleware10.ipwhitelist.sourcerange": "foobar, foobar", -"traefik.http.middlewares.middleware11.maxconn.amount": "42", -"traefik.http.middlewares.middleware11.maxconn.extractorfunc": "foobar", +"traefik.http.middlewares.Middleware11.inflightreq.amount": "42", +"traefik.http.middlewares.Middleware11.inflightreq.sourcecriterion.ipstrategy.depth": "42", +"traefik.http.middlewares.Middleware11.inflightreq.sourcecriterion.ipstrategy.excludedips": "foobar, fiibar", +"traefik.http.middlewares.Middleware11.inflightreq.sourcecriterion.requestheadername": "foobar", +"traefik.http.middlewares.Middleware11.inflightreq.sourcecriterion.requesthost": "true", "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.commonname": "true", "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.country": "true", "traefik.http.middlewares.middleware12.passtlsclientcert.info.issuer.domaincomponent": "true", @@ -96,6 +99,12 @@ "traefik.http.middlewares.middleware17.retry.attempts": "42", "traefik.http.middlewares.middleware18.stripprefix.prefixes": "foobar, foobar", "traefik.http.middlewares.middleware19.stripprefixregex.regex": "foobar, foobar", +"traefik.http.middlewares.Middleware20.ratelimit.average": "42", +"traefik.http.middlewares.Middleware20.ratelimit.burst": "42", +"traefik.http.middlewares.Middleware20.ratelimit.sourcecriterion.requestheadername": "foobar", +"traefik.http.middlewares.Middleware20.ratelimit.sourcecriterion.requesthost": "true", +"traefik.http.middlewares.Middleware20.ratelimit.sourcecriterion.ipstrategy.depth": "42", +"traefik.http.middlewares.Middleware20.ratelimit.sourcecriterion.ipstrategy.excludedips": "foobar, foobar", "traefik.http.routers.router0.entrypoints": "foobar, foobar", "traefik.http.routers.router0.middlewares": "foobar, foobar", "traefik.http.routers.router0.priority": "42", @@ -130,10 +139,10 @@ "traefik.http.services.service0.loadbalancer.healthcheck.timeout": "foobar", "traefik.http.services.service0.loadbalancer.passhostheader": "true", "traefik.http.services.service0.loadbalancer.responseforwarding.flushinterval": "foobar", -"traefik.http.services.service0.loadbalancer.stickiness": "true", -"traefik.http.services.service0.loadbalancer.stickiness.cookiename": "foobar", -"traefik.http.services.service0.loadbalancer.stickiness.httponlycookie": "true", -"traefik.http.services.service0.loadbalancer.stickiness.securecookie": "true", +"traefik.http.services.service0.loadbalancer.sticky": "true", +"traefik.http.services.service0.loadbalancer.sticky.cookie.name": "foobar", +"traefik.http.services.service0.loadbalancer.sticky.cookie.httponly": "true", +"traefik.http.services.service0.loadbalancer.sticky.cookie.secure": "true", "traefik.http.services.service0.loadbalancer.server.port": "foobar", "traefik.http.services.service0.loadbalancer.server.scheme": "foobar", "traefik.http.services.service1.loadbalancer.healthcheck.headers.name0": "foobar", @@ -146,10 +155,10 @@ "traefik.http.services.service1.loadbalancer.healthcheck.timeout": "foobar", "traefik.http.services.service1.loadbalancer.passhostheader": "true", "traefik.http.services.service1.loadbalancer.responseforwarding.flushinterval": "foobar", -"traefik.http.services.service1.loadbalancer.stickiness": "true", -"traefik.http.services.service1.loadbalancer.stickiness.cookiename": "foobar", -"traefik.http.services.service1.loadbalancer.stickiness.httponlycookie": "true", -"traefik.http.services.service1.loadbalancer.stickiness.securecookie": "true", +"traefik.http.services.service1.loadbalancer.sticky": "true", +"traefik.http.services.service1.loadbalancer.sticky.cookie.name": "foobar", +"traefik.http.services.service1.loadbalancer.sticky.cookie.secure": "true", +"traefik.http.services.service1.loadbalancer.sticky.cookie.httponly": "true", "traefik.http.services.service1.loadbalancer.server.port": "foobar", "traefik.http.services.service1.loadbalancer.server.scheme": "foobar", "traefik.tcp.routers.tcprouter0.entrypoints": "foobar, foobar", diff --git a/docs/content/routing/entrypoints.md b/docs/content/routing/entrypoints.md index d13a6d77e..df8d9e676 100644 --- a/docs/content/routing/entrypoints.md +++ b/docs/content/routing/entrypoints.md @@ -128,7 +128,11 @@ entryPoints: ## ProxyProtocol -Traefik supports [ProxyProtocol](https://www.haproxy.org/download/1.8/doc/proxy-protocol.txt). +Traefik supports [ProxyProtocol](https://www.haproxy.org/download/2.0/doc/proxy-protocol.txt) version 1 and 2. + +If proxyprotocol header parsing is enabled for the entry point, this entry point can accept connections with or without proxyprotocol headers. + +If the proxyprotocol header is passed, then the version is determined automatically. ??? example "Enabling Proxy Protocol with Trusted IPs" diff --git a/docs/content/routing/services/index.md b/docs/content/routing/services/index.md index cef456c93..7f0a8bf4a 100644 --- a/docs/content/routing/services/index.md +++ b/docs/content/routing/services/index.md @@ -54,13 +54,7 @@ The `Services` are responsible for configuring how to reach the actual services ## Configuring HTTP Services -### General - -Currently, `LoadBalancer` is the only supported kind of HTTP `Service` (see below). -However, since Traefik is an ever evolving project, other kind of HTTP Services will be available in the future, -reason why you have to specify it. - -### Load Balancer +### Servers Load Balancer The load balancers are able to load balance the requests between multiple instances of your programs. @@ -161,7 +155,7 @@ On subsequent requests, the client is forwarded to the same server. ```toml tab="TOML" [http.services] [http.services.my-service] - [http.services.my-service.loadBalancer.stickiness] + [http.services.my-service.loadBalancer.sticky.cookie] ``` ```yaml tab="YAML" @@ -169,18 +163,19 @@ On subsequent requests, the client is forwarded to the same server. services: my-service: loadBalancer: - stickiness: {} + sticky: + cookie: {} ``` -??? example "Adding Stickiness with a Custom Cookie Name" +??? example "Adding Stickiness with custom Options" ```toml tab="TOML" [http.services] [http.services.my-service] - [http.services.my-service.loadBalancer.stickiness] - cookieName = "my_stickiness_cookie_name" - secureCookie = true - httpOnlyCookie = true + [http.services.my-service.loadBalancer.sticky.cookie] + name = "my_sticky_cookie_name" + secure = true + httpOnly = true ``` ```yaml tab="YAML" @@ -188,10 +183,11 @@ On subsequent requests, the client is forwarded to the same server. services: my-service: loadBalancer: - stickiness: - cookieName: my_stickiness_cookie_name - secureCookie: true - httpOnlyCookie: true + sticky: + cookie: + name: my_sticky_cookie_name + secure: true + httpOnly: true ``` #### Health Check @@ -306,6 +302,104 @@ Below are the available options for the health check mechanism: My-Header: bar ``` +### Weighted Round Robin (service) + +The WRR is able to load balance the requests between multiple services based on weights. + +This strategy is only available to load balance between [services](./index.md) and not between [servers](./index.md#servers). + +This strategy can be defined only with [File](../../providers/file.md). + +```toml tab="TOML" +[http.services] + [http.services.canary] + [[http.services.canary.weighted.services]] + name = "appv1" + weight = 3 + [[http.services.canary.weighted.services]] + name = "appv2" + weight = 1 + + [http.services.appv1] + [http.services.appv1.loadBalancer] + [[http.services.appv1.loadBalancer.servers]] + url = "http://private-ip-server-1/" + + [http.services.appv2] + [http.services.appv2.loadBalancer] + [[http.services.appv2.loadBalancer.servers]] + url = "http://private-ip-server-2/" +``` + +```yaml tab="YAML" +http: + services: + canary: + weighted: + services: + - name: appv1 + weight: 3 + - name: appv2 + weight: 1 + + appv1: + loadBalancer: + servers: + - url: "http://private-ip-server-1/" + + appv2: + loadBalancer: + servers: + - url: "http://private-ip-server-2/" +``` + +### Mirroring (service) + +The mirroring is able to mirror requests sent to a service to other services. + +This strategy can be defined only with [File](../../providers/file.md). + +```toml tab="TOML" +[http.services] + [http.services.mirroring] + [http.services.mirroring.mirroring] + service = "app" + [[http.services.mirroring.mirroring.mirrors]] + name = "mirror" + percent = 10 + + [http.services.app] + [http.services.app.loadBalancer] + [[http.services.appv1.loadBalancer.servers]] + url = "http://private-ip-server-1/" + + [http.services.mirror] + [http.services.mirror.loadBalancer] + [[http.services.mirror.loadBalancer.servers]] + url = "http://private-ip-server-2/" +``` + +```yaml tab="YAML" +http: + services: + mirroring: + mirroring: + service: app + mirrors: + - name: mirror + percent: 10 + + app: + loadBalancer: + servers: + - url: "http://private-ip-server-1/" + + mirror: + loadBalancer: + servers: + - url: "http://private-ip-server-2/" +``` + ## Configuring TCP Services ### General diff --git a/docs/content/user-guides/crd-acme/03-deployments.yml b/docs/content/user-guides/crd-acme/03-deployments.yml index d3b436bcd..71780e9ce 100644 --- a/docs/content/user-guides/crd-acme/03-deployments.yml +++ b/docs/content/user-guides/crd-acme/03-deployments.yml @@ -35,7 +35,6 @@ spec: - --providers.kubernetescrd - --certificatesresolvers.default.acme.tlschallenge - --certificatesresolvers.default.acme.email=foo@you.com - - --certificatesresolvers.default.acme.entrypoint=websecure - --certificatesresolvers.default.acme.storage=acme.json # Please note that this is the staging Let's Encrypt server. # Once you get things working, you should remove that whole line altogether. diff --git a/docs/content/user-guides/crd-acme/index.md b/docs/content/user-guides/crd-acme/index.md index 5a02451dd..f6e4d9263 100644 --- a/docs/content/user-guides/crd-acme/index.md +++ b/docs/content/user-guides/crd-acme/index.md @@ -18,7 +18,7 @@ In the following, the Kubernetes resources defined in YAML configuration files c !!! important "Kubectl Version" - With the `rancher/k3s` version used in this guide (`0.5.0`), the kubectl version needs to be >= `0.11`. + With the `rancher/k3s` version used in this guide (`0.8.0`), the kubectl version needs to be >= `0.11`. ## k3s Docker-compose Configuration diff --git a/docs/content/user-guides/crd-acme/k3s.yml b/docs/content/user-guides/crd-acme/k3s.yml index 6e9042646..a424d9f56 100644 --- a/docs/content/user-guides/crd-acme/k3s.yml +++ b/docs/content/user-guides/crd-acme/k3s.yml @@ -1,5 +1,5 @@ server: - image: rancher/k3s:v0.5.0 + image: rancher/k3s:v0.8.0 command: server --disable-agent --no-deploy traefik environment: - K3S_CLUSTER_SECRET=somethingtotallyrandom @@ -17,7 +17,7 @@ server: - 6443:6443 node: - image: rancher/k3s:v0.5.0 + image: rancher/k3s:v0.8.0 privileged: true links: - server diff --git a/docs/content/user-guides/docker-compose/acme-http/docker-compose.yml b/docs/content/user-guides/docker-compose/acme-http/docker-compose.yml index bdacf474f..8f348a7a8 100644 --- a/docs/content/user-guides/docker-compose/acme-http/docker-compose.yml +++ b/docs/content/user-guides/docker-compose/acme-http/docker-compose.yml @@ -20,7 +20,7 @@ services: ports: - "80:80" - "443:443" - - ":8080:8080" + - "8080:8080" volumes: - "./letsencrypt:/letsencrypt" - "/var/run/docker.sock:/var/run/docker.sock:ro" diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 76f03293b..46cba835d 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -102,7 +102,7 @@ nav: - 'ForwardAuth': 'middlewares/forwardauth.md' - 'Headers': 'middlewares/headers.md' - 'IpWhitelist': 'middlewares/ipwhitelist.md' - - 'Maxconn': 'middlewares/maxconnection.md' + - 'InFlightReq': 'middlewares/inflightreq.md' - 'PassTLSClientCert': 'middlewares/passtlsclientcert.md' - 'RateLimit': 'middlewares/ratelimit.md' - 'RedirectRegex': 'middlewares/redirectregex.md' diff --git a/exp.Dockerfile b/exp.Dockerfile index 3b8801cf2..6f59b73e3 100644 --- a/exp.Dockerfile +++ b/exp.Dockerfile @@ -12,7 +12,7 @@ RUN yarn install RUN npm run build # BUILD -FROM golang:1.12-alpine as gobuild +FROM golang:1.13rc1-alpine as gobuild RUN apk --update upgrade \ && apk --no-cache --no-progress add git mercurial bash gcc musl-dev curl tar ca-certificates tzdata \ @@ -24,6 +24,12 @@ RUN mkdir -p /usr/local/bin \ && chmod +x /usr/local/bin/go-bindata WORKDIR /go/src/github.com/containous/traefik + +# Download go modules +COPY go.mod . +COPY go.sum . +RUN GO111MODULE=on GOPROXY=https://proxy.golang.org go mod download + COPY . /go/src/github.com/containous/traefik RUN rm -rf /go/src/github.com/containous/traefik/static/ diff --git a/go.mod b/go.mod new file mode 100644 index 000000000..d3304053d --- /dev/null +++ b/go.mod @@ -0,0 +1,122 @@ +module github.com/containous/traefik/v2 + +go 1.13 + +require ( + github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect + github.com/BurntSushi/toml v0.3.1 + github.com/ExpediaDotCom/haystack-client-go v0.0.0-20190315171017-e7edbdf53a61 + github.com/Masterminds/goutils v1.1.0 // indirect + github.com/Masterminds/semver v1.4.2 // indirect + github.com/Masterminds/sprig v2.20.0+incompatible + github.com/Microsoft/go-winio v0.4.14 // indirect + github.com/Microsoft/hcsshim v0.8.6 // indirect + github.com/NYTimes/gziphandler v1.1.1 + github.com/Shopify/sarama v1.23.1 // indirect + github.com/VividCortex/gohistogram v1.0.0 // indirect + github.com/abbot/go-http-auth v0.0.0-00010101000000-000000000000 + github.com/abronan/valkeyrie v0.0.0-20190802193736-ed4c4a229894 + github.com/c0va23/go-proxyprotocol v0.9.1 + github.com/cenkalti/backoff/v3 v3.0.0 + github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc // indirect + github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd + github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f + github.com/davecgh/go-spew v1.1.1 + github.com/docker/cli v0.0.0-20190711175710-5b38d82aa076 // indirect + github.com/docker/distribution v2.7.1+incompatible // indirect + github.com/docker/docker v0.0.0-00010101000000-000000000000 + github.com/docker/docker-credential-helpers v0.6.3 // indirect + github.com/docker/go-connections v0.4.0 + github.com/docker/go-metrics v0.0.0-20181218153428-b84716841b82 // indirect + github.com/docker/go-units v0.4.0 // indirect + github.com/docker/libcompose v0.0.0-20190805081528-eac9fe1b8b03 // indirect + github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 // indirect + github.com/donovanhide/eventsource v0.0.0-20170630084216-b8f31a59085e // indirect + github.com/eapache/channels v1.1.0 + github.com/elazarl/go-bindata-assetfs v1.0.0 + github.com/evanphx/json-patch v4.5.0+incompatible // indirect + github.com/fatih/structs v1.1.0 + github.com/felixge/httpsnoop v1.0.0 // indirect + github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect + github.com/gambol99/go-marathon v0.0.0-20180614232016-99a156b96fb2 + github.com/go-acme/lego/v3 v3.0.2 + github.com/go-check/check v0.0.0-00010101000000-000000000000 + github.com/go-kit/kit v0.9.0 + github.com/golang/protobuf v1.3.2 + github.com/google/go-github/v27 v27.0.4 + github.com/googleapis/gnostic v0.1.0 // indirect + github.com/gorilla/mux v1.6.2 + github.com/gorilla/websocket v1.4.0 + github.com/hashicorp/go-version v1.2.0 + github.com/huandu/xstrings v1.2.0 // indirect + github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc + github.com/instana/go-sensor v1.4.17-0.20190515112224-78c14625025a + github.com/labbsr0x/goh v0.0.0-20190610190554-60aa50bcbca7 // indirect + github.com/libkermit/compose v0.0.0-20171122111507-c04e39c026ad + github.com/libkermit/docker v0.0.0-20171122101128-e6674d32b807 + github.com/libkermit/docker-check v0.0.0-20171122104347-1113af38e591 + github.com/looplab/fsm v0.1.0 // indirect + github.com/magiconair/properties v1.8.1 // indirect + github.com/mailgun/ttlmap v0.0.0-20170619185759-c1c17f74874f + github.com/miekg/dns v1.1.15 + github.com/mitchellh/copystructure v1.0.0 + github.com/mitchellh/hashstructure v1.0.0 + github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c // indirect + github.com/opencontainers/go-digest v1.0.0-rc1 // indirect + github.com/opencontainers/image-spec v1.0.1 // indirect + github.com/opencontainers/runc v1.0.0-rc8 // indirect + github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492 // indirect + github.com/opentracing/basictracer-go v1.0.0 // indirect + github.com/opentracing/opentracing-go v1.1.0 + github.com/openzipkin-contrib/zipkin-go-opentracing v0.3.5 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/philhofer/fwd v1.0.0 // indirect + github.com/pmezard/go-difflib v1.0.0 + github.com/prometheus/client_golang v1.0.0 + github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 + github.com/prometheus/common v0.6.0 // indirect + github.com/prometheus/procfs v0.0.3 // indirect + github.com/rancher/go-rancher-metadata v0.0.0-00010101000000-000000000000 + github.com/sirupsen/logrus v1.4.2 + github.com/stretchr/testify v1.3.0 + github.com/stvp/go-udp-testing v0.0.0-20171104055251-c4434f09ec13 + github.com/tinylib/msgp v1.0.2 // indirect + github.com/transip/gotransip v5.8.2+incompatible // indirect + github.com/uber/jaeger-client-go v2.16.0+incompatible + github.com/uber/jaeger-lib v2.0.0+incompatible + github.com/unrolled/render v1.0.1 + github.com/unrolled/secure v1.0.1 + github.com/vdemeester/shakers v0.1.0 + github.com/vulcand/oxy v1.0.0 + github.com/vulcand/predicate v1.1.0 + golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 + golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a // indirect + golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 + golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 // indirect + google.golang.org/grpc v1.22.1 + gopkg.in/DataDog/dd-trace-go.v1 v1.16.1 + gopkg.in/fsnotify.v1 v1.4.7 + gopkg.in/jcmturner/goidentity.v3 v3.0.0 // indirect + gopkg.in/yaml.v2 v2.2.2 + gotest.tools v2.2.0+incompatible // indirect + k8s.io/api v0.0.0-20190718183219-b59d8169aab5 + k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719 + k8s.io/client-go v0.0.0-20190718183610-8e956561bbf5 + k8s.io/code-generator v0.0.0-20190612205613-18da4a14b22b + mvdan.cc/xurls/v2 v2.0.0 +) + +replace ( + github.com/Azure/go-autorest => github.com/Azure/go-autorest v12.4.1+incompatible + github.com/docker/docker => github.com/docker/engine v0.0.0-20190725163905-fa8dd90ceb7b +) + +// Containous forks +replace ( + github.com/abbot/go-http-auth => github.com/containous/go-http-auth v0.4.1-0.20180112153951-65b0cdae8d7f + github.com/go-check/check => github.com/containous/check v0.0.0-20170915194414-ca0bf163426a + github.com/gorilla/mux => github.com/containous/mux v0.0.0-20181024131434-c33f32e26898 + github.com/mailgun/minheap => github.com/containous/minheap v0.0.0-20190809180810-6e71eb837595 + github.com/mailgun/multibuf => github.com/containous/multibuf v0.0.0-20190809014333-8b6c9a7e6bba + github.com/rancher/go-rancher-metadata => github.com/containous/go-rancher-metadata v0.0.0-20190402144056-c6a65f8b7a28 +) diff --git a/go.sum b/go.sum new file mode 100644 index 000000000..cbaba2ca0 --- /dev/null +++ b/go.sum @@ -0,0 +1,681 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0 h1:ROfEUZz+Gh5pa62DJWXSaonyu3StP6EA6lPEXPI6mCo= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +contrib.go.opencensus.io/exporter/ocagent v0.4.12 h1:jGFvw3l57ViIVEPKKEUXPcLYIXJmQxLUh6ey1eJhwyc= +contrib.go.opencensus.io/exporter/ocagent v0.4.12/go.mod h1:450APlNTSR6FrvC3CTRqYosuDstRB9un7SOx2k/9ckA= +github.com/Azure/azure-sdk-for-go v32.4.0+incompatible h1:1JP8SKfroEakYiQU2ZyPDosh8w2Tg9UopKt88VyQPt4= +github.com/Azure/azure-sdk-for-go v32.4.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 h1:w+iIsaOQNcT7OZ575w+acHgRric5iCyQh+xv+KJ4HB8= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= +github.com/Azure/go-autorest v12.4.1+incompatible h1:pst/kk4ljPhiBW1FDMi1BZBxJRPFrVBxHrJQVeXcv/E= +github.com/Azure/go-autorest v12.4.1+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest v0.1.0/go.mod h1:AKyIcETwSUFxIcs/Wnq/C+kwCtlEYGUVd7FPNb2slmg= +github.com/Azure/go-autorest/autorest v0.5.0 h1:Mlm9qy2fpQ9MvfyI41G2Zf5B4CsgjjNbLOWszfK6KrY= +github.com/Azure/go-autorest/autorest v0.5.0/go.mod h1:9HLKlQjVBH6U3oDfsXOeVc56THsLPw1L03yban4xThw= +github.com/Azure/go-autorest/autorest/adal v0.1.0/go.mod h1:MeS4XhScH55IST095THyTxElntu7WqB7pNbZo8Q5G3E= +github.com/Azure/go-autorest/autorest/adal v0.2.0 h1:7IBDu1jgh+ADHXnEYExkV9RE/ztOOlxdACkkPRthGKw= +github.com/Azure/go-autorest/autorest/adal v0.2.0/go.mod h1:MeS4XhScH55IST095THyTxElntu7WqB7pNbZo8Q5G3E= +github.com/Azure/go-autorest/autorest/azure/auth v0.1.0 h1:YgO/vSnJEc76NLw2ecIXvXa8bDWiqf1pOJzARAoZsYU= +github.com/Azure/go-autorest/autorest/azure/auth v0.1.0/go.mod h1:Gf7/i2FUpyb/sGBLIFxTBzrNzBo7aPXXE3ZVeDRwdpM= +github.com/Azure/go-autorest/autorest/azure/cli v0.1.0 h1:YTtBrcb6mhA+PoSW8WxFDoIIyjp13XqJeX80ssQtri4= +github.com/Azure/go-autorest/autorest/azure/cli v0.1.0/go.mod h1:Dk8CUAt/b/PzkfeRsWzVG9Yj3ps8mS8ECztu43rdU8U= +github.com/Azure/go-autorest/autorest/date v0.1.0 h1:YGrhWfrgtFs84+h0o46rJrlmsZtyZRg470CqAXTZaGM= +github.com/Azure/go-autorest/autorest/date v0.1.0/go.mod h1:plvfp3oPSKwf2DNjlBjWF/7vwR+cUD/ELuzDCXwHUVA= +github.com/Azure/go-autorest/autorest/mocks v0.1.0 h1:Kx+AUU2Te+A3JIyYn6Dfs+cFgx5XorQKuIXrZGoq/SI= +github.com/Azure/go-autorest/autorest/mocks v0.1.0/go.mod h1:OTyCOPRA2IgIlWxVYxBee2F5Gr4kF2zd2J5cFRaIDN0= +github.com/Azure/go-autorest/autorest/to v0.2.0 h1:nQOZzFCudTh+TvquAtCRjM01VEYx85e9qbwt5ncW4L8= +github.com/Azure/go-autorest/autorest/to v0.2.0/go.mod h1:GunWKJp1AEqgMaGLV+iocmRAJWqST1wQYhyyjXJ3SJc= +github.com/Azure/go-autorest/autorest/validation v0.1.0 h1:ISSNzGUh+ZSzizJWOWzs8bwpXIePbGLW4z/AmUFGH5A= +github.com/Azure/go-autorest/autorest/validation v0.1.0/go.mod h1:Ha3z/SqBeaalWQvokg3NZAlQTalVMtOIAs1aGK7G6u8= +github.com/Azure/go-autorest/logger v0.1.0 h1:ruG4BSDXONFRrZZJ2GUXDiUyVpayPmb1GnWeHDdaNKY= +github.com/Azure/go-autorest/logger v0.1.0/go.mod h1:oExouG+K6PryycPJfVSxi/koC6LSNgds39diKLz7Vrc= +github.com/Azure/go-autorest/tracing v0.1.0 h1:TRBxC5Pj/fIuh4Qob0ZpkggbfT8RC0SubHbpV3p4/Vc= +github.com/Azure/go-autorest/tracing v0.1.0/go.mod h1:ROEEAFwXycQw7Sn3DXNtEedEvdeRAgDr0izn4z5Ij88= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798 h1:2T/jmrHeTezcCM58lvEQXs0UpQJCo5SoGAcg+mbSTIg= +github.com/DataDog/zstd v1.3.6-0.20190409195224-796139022798/go.mod h1:1jcaCB/ufaK+sKp1NBhlGmpz41jOoPQ35bpF36t7BBo= +github.com/ExpediaDotCom/haystack-client-go v0.0.0-20190315171017-e7edbdf53a61 h1:1NIUJ+MAMpqDr4LWIfNsoJR+G7zg/8GZVwuRkmJxtTc= +github.com/ExpediaDotCom/haystack-client-go v0.0.0-20190315171017-e7edbdf53a61/go.mod h1:62qWSDaEI0BLykU+zQza5CAKgW0lOy9oBSz3/DvYz4w= +github.com/Masterminds/goutils v1.1.0 h1:zukEsf/1JZwCMgHiK3GZftabmxiCw4apj3a28RPBiVg= +github.com/Masterminds/goutils v1.1.0/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU= +github.com/Masterminds/semver v1.4.2 h1:WBLTQ37jOCzSLtXNdoo8bNM8876KhNqOKvrlGITgsTc= +github.com/Masterminds/semver v1.4.2/go.mod h1:MB6lktGJrhw8PrUyiEoblNEGEQ+RzHPF078ddwwvV3Y= +github.com/Masterminds/sprig v2.20.0+incompatible h1:dJTKKuUkYW3RMFdQFXPU/s6hg10RgctmTjRcbZ98Ap8= +github.com/Masterminds/sprig v2.20.0+incompatible/go.mod h1:y6hNFY5UBTIWBxnzTeuNhlNS5hqE0NB0E6fgfo2Br3o= +github.com/Microsoft/go-winio v0.4.14 h1:+hMXMk01us9KgxGb7ftKQt2Xpf5hH/yky+TDA+qxleU= +github.com/Microsoft/go-winio v0.4.14/go.mod h1:qXqCSQ3Xa7+6tgxaGTIe4Kpcdsi+P8jBhyzoq1bpyYA= +github.com/Microsoft/hcsshim v0.8.6 h1:ZfF0+zZeYdzMIVMZHKtDKJvLHj76XCuVae/jNkjj0IA= +github.com/Microsoft/hcsshim v0.8.6/go.mod h1:Op3hHsoHPAvb6lceZHDtd9OkTew38wNoXnJs8iY7rUg= +github.com/NYTimes/gziphandler v1.1.1 h1:ZUDjpQae29j0ryrS0u/B8HZfJBtBQHjqw2rQ2cqUQ3I= +github.com/NYTimes/gziphandler v1.1.1/go.mod h1:n/CVRwUEOgIxrgPvAQhUUr9oeUtvrhMomdKFjzJNB0c= +github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87 h1:xPMsUicZ3iosVPSIP7bW5EcGUzjiiMl1OYTe14y/R24= +github.com/OpenDNS/vegadns2client v0.0.0-20180418235048-a3fa4a771d87/go.mod h1:iGLljf5n9GjT6kc0HBvyI1nOKnGQbNB66VzSNbK5iks= +github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= +github.com/Shopify/sarama v1.23.1 h1:XxJBCZEoWJtoWjf/xRbmGUpAmTZGnuuF0ON0EvxxBrs= +github.com/Shopify/sarama v1.23.1/go.mod h1:XLH1GYJnLVE0XCr6KdJGVJRTwY30moWNJ4sERjXX6fs= +github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc= +github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= +github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= +github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= +github.com/abronan/valkeyrie v0.0.0-20190802193736-ed4c4a229894 h1:6oe+/ZnkM+gEJL+28sgHiCvO6qt15NE2lm52BuzBees= +github.com/abronan/valkeyrie v0.0.0-20190802193736-ed4c4a229894/go.mod h1:sQZ/48uDt1GRBDNsLboJGPD2w/HxEOhqf3JiikfHj1I= +github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.0 h1:rXPPPxDA4GCPN0YWwyVHMzcxVpVg8gai2uGhJ3VqOSs= +github.com/akamai/AkamaiOPEN-edgegrid-golang v0.9.0/go.mod h1:zpDJeKyp9ScW4NNrbdr+Eyxvry3ilGPewKoXw3XGN1k= +github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc= +github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0= +github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190808125512-07798873deee h1:NYqDBPkhVYt68W3yoGoRRi32i3MLx2ey7SFkJ1v/UI0= +github.com/aliyun/alibaba-cloud-sdk-go v0.0.0-20190808125512-07798873deee/go.mod h1:myCDvQSzCW+wB1WAlocEru4wMGJxy+vlxHdhegi1CDQ= +github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= +github.com/apache/thrift v0.12.0 h1:pODnxUFNcjP9UTLZGTdeh+j16A8lJbRvD3rOtrk/7bs= +github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/aws/aws-sdk-go v1.16.23/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.23.0 h1:ilfJN/vJtFo1XDFxB2YMBYGeOvGZl6Qow17oyD4+Z9A= +github.com/aws/aws-sdk-go v1.23.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f/go.mod h1:AuiFmCCPBSrqvVMvuqFuk0qogytodnVFVSN5CeJB8Gc= +github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= +github.com/beorn7/perks v1.0.0 h1:HWo1m869IqiPhD389kmkxeTalrjNbbJTC8LXupb+sl0= +github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= +github.com/c0va23/go-proxyprotocol v0.9.1 h1:5BCkp0fDJOhzzH1lhjUgHhmZz9VvRMMif1U2D31hb34= +github.com/c0va23/go-proxyprotocol v0.9.1/go.mod h1:TNjUV+llvk8TvWJxlPYAeAYZgSzT/iicNr3nWBWX320= +github.com/cenkalti/backoff/v3 v3.0.0 h1:ske+9nBpD9qZsTBoF41nW5L+AIuFBKMeze18XQ3eG1c= +github.com/cenkalti/backoff/v3 v3.0.0/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs= +github.com/census-instrumentation/opencensus-proto v0.2.0 h1:LzQXZOgg4CQfE6bFvXGM30YZL1WW/M337pXml+GrcZ4= +github.com/census-instrumentation/opencensus-proto v0.2.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudflare/cloudflare-go v0.10.0 h1:wJPNqfrQO0w3fCiQcf/2T4lR2y6Q2fAwRszllljgb8I= +github.com/cloudflare/cloudflare-go v0.10.0/go.mod h1:fOESqHl/jzAmCtEyjceLkw3v0rVjzl8V9iehxZPynXY= +github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd h1:qMd81Ts1T2OTKmB4acZcyKaMtRnY5Y44NuXGX2GFJ1w= +github.com/codahale/hdrhistogram v0.0.0-20161010025455-3a0bb77429bd/go.mod h1:sE/e/2PUdi/liOCUjSTXgM1o87ZssimdTWN964YiIeI= +github.com/codegangsta/negroni v1.0.0 h1:+aYywywx4bnKXWvoWtRfJ91vC59NbEhEY03sZjQhbVY= +github.com/codegangsta/negroni v1.0.0/go.mod h1:v0y3T5G7Y1UlFfyxFn/QLRU4a2EuNau2iZY63YTKWo0= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc h1:TP+534wVlf61smEIq1nwLLAjQVEK2EADoW3CX9AuT+8= +github.com/containerd/continuity v0.0.0-20190426062206-aaeac12a7ffc/go.mod h1:GL3xCUCBDV3CZiTSEKksMWbLE66hEyuu9qyDOOqM47Y= +github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd h1:0n+lFLh5zU0l6KSk3KpnDwfbPGAR44aRLgTbCnhRBHU= +github.com/containous/alice v0.0.0-20181107144136-d83ebdd94cbd/go.mod h1:BbQgeDS5i0tNvypwEoF1oNjOJw8knRAE1DnVvjDstcQ= +github.com/containous/check v0.0.0-20170915194414-ca0bf163426a h1:8esAQaPKjfntQR1bag/mAOvWJd5HqSX5nsa+0KT63zo= +github.com/containous/check v0.0.0-20170915194414-ca0bf163426a/go.mod h1:eQOqZ7GoFsLxI7jFKLs7+Nv2Rm1x4FyK8d2NV+yGjwQ= +github.com/containous/go-http-auth v0.4.1-0.20180112153951-65b0cdae8d7f h1:AgXgJSqQmsiNFW268OGe/y7Mn4jiCWaMUk05qser3Bo= +github.com/containous/go-http-auth v0.4.1-0.20180112153951-65b0cdae8d7f/go.mod h1:dCmRGidPSLagL8D/2u7yIO6Y/8D/yuYX9EdKrnrhpCA= +github.com/containous/go-rancher-metadata v0.0.0-20190402144056-c6a65f8b7a28 h1:YBo7nuGRif2QvUvqJuAEp8trX+5jnFj/8iAPJDe5U4k= +github.com/containous/go-rancher-metadata v0.0.0-20190402144056-c6a65f8b7a28/go.mod h1:YTAhdMF+tmHPGF7v0uZJ22+XNY/jz1ZYdBCeTZnsrYU= +github.com/containous/minheap v0.0.0-20190809180810-6e71eb837595 h1:aPspFRO6b94To3gl4yTDOEtpjFwXI7V2W+z0JcNljQ4= +github.com/containous/minheap v0.0.0-20190809180810-6e71eb837595/go.mod h1:+lHFbEasIiQVGzhVDVw/cn0ZaOzde2OwNncp1NhXV4c= +github.com/containous/multibuf v0.0.0-20190809014333-8b6c9a7e6bba h1:PhR03pep+5eO/9BSvCY9RyG8rjogB3uYS4X/WBYNTT8= +github.com/containous/multibuf v0.0.0-20190809014333-8b6c9a7e6bba/go.mod h1:zkWcASFUJEst6QwCrxLdkuw1gvaKqmflEipm+iecV5M= +github.com/containous/mux v0.0.0-20181024131434-c33f32e26898 h1:1srn9voikJGofblBhWy3WuZWqo14Ou7NaswNG/I2yWc= +github.com/containous/mux v0.0.0-20181024131434-c33f32e26898/go.mod h1:z8WW7n06n8/1xF9Jl9WmuDeZuHAhfL+bwarNjsciwwg= +github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE= +github.com/coreos/go-semver v0.2.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk= +github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f h1:JOrtw2xFKzlg+cbHpyrpLDmnN1HqhBfnX7WDiW7eG2c= +github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/cpu/goacmedns v0.0.1 h1:GeIU5chKys9zmHgOAgP+bstRaLqcGQ6HJh/hLw9hrus= +github.com/cpu/goacmedns v0.0.1/go.mod h1:sesf/pNnCYwUevQEQfEwY0Y3DydlQWSGZbaMElOWxok= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/decker502/dnspod-go v0.2.0 h1:6dwhUFCYbC5bgpebLKn7PrI43e/5mn9tpUL9YcYCdTU= +github.com/decker502/dnspod-go v0.2.0/go.mod h1:qsurYu1FgxcDwfSwXJdLt4kRsBLZeosEb9uq4Sy+08g= +github.com/dgrijalva/jwt-go v0.0.0-20160705203006-01aeca54ebda/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM= +github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ= +github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TRo4= +github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= +github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2 h1:G9/PqfhOrt8JXnw0DGTfVoOkKHDhOlEZqhE/cu+NvQM= +github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= +github.com/dnsimple/dnsimple-go v0.30.0 h1:IBIrn9jMKRMwporIRwdFyKdnHXVmwy6obnguB+ZMDIY= +github.com/dnsimple/dnsimple-go v0.30.0/go.mod h1:O5TJ0/U6r7AfT8niYNlmohpLbCSG+c71tQlGr9SeGrg= +github.com/docker/cli v0.0.0-20190711175710-5b38d82aa076 h1:bYvTMcZVIsw5l+uhPIPBI8VCVPKXgyQhP63+xXfM8bw= +github.com/docker/cli v0.0.0-20190711175710-5b38d82aa076/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug= +github.com/docker/distribution v2.7.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w= +github.com/docker/docker-credential-helpers v0.6.3 h1:zI2p9+1NQYdnG6sMU26EX4aVGlqbInSQxQXLvzJ4RPQ= +github.com/docker/docker-credential-helpers v0.6.3/go.mod h1:WRaJzqw3CTB9bk10avuGsjVBZsD05qeibJ1/TYlvc0Y= +github.com/docker/engine v0.0.0-20190725163905-fa8dd90ceb7b h1:rN+GLmgWe6Yb5E8yfvGmgKfksvla7QyvqFCUKWTD8Qo= +github.com/docker/engine v0.0.0-20190725163905-fa8dd90ceb7b/go.mod h1:3CPr2caMgTHxxIAZgEMd3uLYPDlRvPqCpyeRf6ncPcY= +github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-metrics v0.0.0-20181218153428-b84716841b82 h1:X0fj836zx99zFu83v/M79DuBn84IL/Syx1SY6Y5ZEMA= +github.com/docker/go-metrics v0.0.0-20181218153428-b84716841b82/go.mod h1:/u0gXw0Gay3ceNrsHubL3BtdOL2fHf93USgMTe0W5dI= +github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/docker/libcompose v0.0.0-20190805081528-eac9fe1b8b03 h1:kodxuqd2aTzaoldemGNQLrnYGpYLvm1kRdzngQa6hPc= +github.com/docker/libcompose v0.0.0-20190805081528-eac9fe1b8b03/go.mod h1:EyqDS+Iyca0hS44T7qIMTeO1EOYWWWNOGpufHu9R8cs= +github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7 h1:UhxFibDNY/bfvqU5CAUmr9zpesgbU6SWc8/B4mflAE4= +github.com/docker/libtrust v0.0.0-20160708172513-aabc10ec26b7/go.mod h1:cyGadeNEkKy96OOhEzfZl+yxihPEzKnqJwvfuSUqbZE= +github.com/docker/spdystream v0.0.0-20160310174837-449fdfce4d96/go.mod h1:Qh8CwZgvJUkLughtfhJv5dyTYa91l1fOUCrgjqmcifM= +github.com/donovanhide/eventsource v0.0.0-20170630084216-b8f31a59085e h1:rMOGp6HPeMHbdLrZkX2nD+94uqDunc27tXVuS+ey4mQ= +github.com/donovanhide/eventsource v0.0.0-20170630084216-b8f31a59085e/go.mod h1:56wL82FO0bfMU5RvfXoIwSOP2ggqqxT+tAfNEIyxuHw= +github.com/eapache/channels v1.1.0 h1:F1taHcn7/F0i8DYqKXJnyhJcVpp2kgFcNePxXtnyu4k= +github.com/eapache/channels v1.1.0/go.mod h1:jMm2qB5Ubtg9zLd+inMZd2/NUvXgzmWXsDaLyQIGfH0= +github.com/eapache/go-resiliency v1.1.0 h1:1NtRmCAqadE2FN4ZcN6g90TP3uk8cg9rn9eNK2197aU= +github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21 h1:YEetp8/yCZMuEPMUDHG0CW/brkkEp8mzqk2+ODEitlw= +github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU= +github.com/eapache/queue v1.1.0 h1:YOEu7KNc61ntiQlcEeUIoDTJ2o8mQznoNvUhiigpIqc= +github.com/eapache/queue v1.1.0/go.mod h1:6eCeP0CKFpHLu8blIFXhExK/dRa7WDZfr6jVFPTqq+I= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385 h1:clC1lXBpe2kTj2VHdaIu9ajZQe4kcEY9j0NsnDDBZ3o= +github.com/eknkc/amber v0.0.0-20171010120322-cdade1c07385/go.mod h1:0vRUJqYpeSZifjYj7uP3BG/gKcuzL9xWVV/Y+cK33KM= +github.com/elazarl/go-bindata-assetfs v1.0.0 h1:G/bYguwHIzWq9ZoyUQqrjTmJbbYn3j3CKKpKinvZLFk= +github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4= +github.com/elazarl/goproxy v0.0.0-20170405201442-c4fc26588b6e/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc= +github.com/evanphx/json-patch v0.0.0-20190203023257-5858425f7550/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/evanphx/json-patch v4.5.0+incompatible h1:ouOWdg56aJriqS0huScTkVXPC5IcNrDCXZ6OoTAWu7M= +github.com/evanphx/json-patch v4.5.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk= +github.com/exoscale/egoscale v0.18.1 h1:1FNZVk8jHUx0AvWhOZxLEDNlacTU0chMXUUNkm9EZaI= +github.com/exoscale/egoscale v0.18.1/go.mod h1:Z7OOdzzTOz1Q1PjQXumlz9Wn/CddH0zSYdCF3rnBKXE= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/felixge/httpsnoop v1.0.0 h1:gh8fMGz0rlOv/1WmRZm7OgncIOTsAj21iNJot48omJQ= +github.com/felixge/httpsnoop v1.0.0/go.mod h1:3+D9sFq0ahK/JeJPhCBUV1xlf4/eIYrUQaxulT0VzX8= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BHsljHzVlRcyQhjrss6TZTdY2VfCqZPbv5k3iBFa2ZQ= +github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:xEzjJPgXI435gkrCt3MPfRiAkVrwSbHsst4LCFVfpJc= +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/gambol99/go-marathon v0.0.0-20180614232016-99a156b96fb2 h1:df6OFl8WNXk82xxP3R9ZPZ5seOA8XZkwLdbEzZF1/xI= +github.com/gambol99/go-marathon v0.0.0-20180614232016-99a156b96fb2/go.mod h1:GLyXJD41gBO/NPKVPGQbhyyC06eugGy15QEZyUkE2/s= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-acme/lego/v3 v3.0.2 h1:cnS+URiPzkt2pd7I2WlZtFyt2ihQ762nouBybY4djjw= +github.com/go-acme/lego/v3 v3.0.2/go.mod h1:sMoLjf8BUo4Jexg+6Xw5KeFx98KVZ7Nfczh9tzLyhJU= +github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= +github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= +github.com/go-ini/ini v1.44.0 h1:8+SRbfpRFlIunpSum4BEf1ClTtVjOgKzgBv9pHFkI6w= +github.com/go-ini/ini v1.44.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-kit/kit v0.9.0 h1:wDJmvq38kDhkVxi50ni9ykkdUr1PKgqKOoi01fa0Mdk= +github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= +github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= +github.com/go-logfmt/logfmt v0.4.0 h1:MP4Eh7ZCb31lleYCFuwm0oe4/YGak+5l1vA2NOE80nA= +github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk= +github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gofrs/uuid v3.2.0+incompatible h1:y12jRkkFxsd7GpqdSZ+/KCs/fJbqpEXSGd4+jfEaewE= +github.com/gofrs/uuid v3.2.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/gogo/protobuf v0.0.0-20171007142547-342cbe0a0415/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/gogo/protobuf v1.2.0 h1:xU6/SpYbvkNYiptHJYEDRseDLvYE7wSqhYYNy0QSUzI= +github.com/gogo/protobuf v1.2.0/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ= +github.com/goji/httpauth v0.0.0-20160601135302-2da839ab0f4d/go.mod h1:nnjvkQ9ptGaCkuDUx6wNykzzlUixGxvkme+H/lnzb+A= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903 h1:LbsanbbD6LieFkXbj9YNNBupiGHJgFeLpO0j0Fza1h8= +github.com/golang/groupcache v0.0.0-20160516000752-02826c3e7903/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0 h1:28o5sBqPkBsMGnC6b4MvE2TzSr5/AT4c/1fLqVGIwlk= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20160524151835-7d79101e329e/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0 h1:crn/baboCvb5fXaQ0IJ1SGTsTVrWpDsCWC8EGETZijY= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-github/v27 v27.0.4 h1:N/EEqsvJLgqTbepTiMBz+12KhwLovv6YvwpRezd+4Fg= +github.com/google/go-github/v27 v27.0.4/go.mod h1:/0Gr8pJ55COkmv+S/yPKCczSkUPIM/LnFyubufRNIS0= +github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf h1:+RRA9JqSOZFfKrOeqr2z77+8R2RKyh8PG66dcu1V0ck= +github.com/google/gofuzz v0.0.0-20170612174753-24818f796faf/go.mod h1:HP5RmnzzSNb993RKQDq4+1A4ia9nllfqcQFTQJedwGI= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/uuid v1.0.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.1 h1:Gkbcsh/GbpXz7lPftLA3P6TYMwjCLYm83jiFQZF/3gY= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5 h1:sjZBwGj9Jlw33ImPtvFviGYvseOtDM7hkSKB7+Tv3SM= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gnostic v0.0.0-20170729233727-0c5108395e2d/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/googleapis/gnostic v0.1.0 h1:rVsPeBmXbYv4If/cumu1AzZPwV58q433hvONV1UEZoI= +github.com/googleapis/gnostic v0.1.0/go.mod h1:sJBsCZ4ayReDTBIg8b9dl28c5xFWyhBTVRp3pOg5EKY= +github.com/gophercloud/gophercloud v0.0.0-20190126172459-c818fa66e4c8/go.mod h1:3WdhXV3rUYy9p6AUW8d94kr+HS62Y4VL9mBnFxsD8q4= +github.com/gophercloud/gophercloud v0.3.0 h1:6sjpKIpVwRIIwmcEGp+WwNovNsem+c+2vm6oxshRpL8= +github.com/gophercloud/gophercloud v0.3.0/go.mod h1:vxM41WHh5uqHVBMZHzuwNOHh8XEoIEcSTewFxm1c5g8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q= +github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ= +github.com/gravitational/trace v0.0.0-20190726142706-a535a178675f h1:68WxnfBzJRYktZ30fmIjGQ74RsXYLoeH2/NITPktTMY= +github.com/gravitational/trace v0.0.0-20190726142706-a535a178675f/go.mod h1:RvdOUHE4SHqR3oXlFFKnGzms8a5dugHygGw1bqDstYI= +github.com/gregjones/httpcache v0.0.0-20170728041850-787624de3eb7/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA= +github.com/grpc-ecosystem/grpc-gateway v1.8.5 h1:2+KSC78XiO6Qy0hIjfc1OD9H+hsaJdJlb8Kqsd41CTE= +github.com/grpc-ecosystem/grpc-gateway v1.8.5/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542 h1:2VTzZjLZBgl62/EtslCrtky5vbi9dd7HrQPQIx6wqiw= +github.com/h2non/parth v0.0.0-20190131123155-b4df798d6542/go.mod h1:Ow0tF8D4Kplbc8s8sSb3V2oUCygFHVp8gC3Dn6U4MNI= +github.com/hashicorp/consul v1.4.0/go.mod h1:mFrjN1mfidgJfYP1xrJCF+AfRhr6Eaqhb2+sfyn/OOI= +github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= +github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= +github.com/hashicorp/go-uuid v1.0.1 h1:fv1ep09latC32wFoVwnqcnKJGnMSdBanPczbHAYm1BE= +github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E= +github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.3 h1:YPkqC67at8FYaadspW/6uE0COsBxS2656RLEr8Bppgk= +github.com/hashicorp/golang-lru v0.5.3/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/serf v0.8.1/go.mod h1:h/Ru6tmZazX7WO/GDmwdpS975F019L4t5ng5IgwbNrE= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/huandu/xstrings v1.2.0 h1:yPeWdRnmynF7p+lLYz0H2tthW9lqhMJrQV/U7yy4wX0= +github.com/huandu/xstrings v1.2.0/go.mod h1:DvyZB1rfVYsBIigL8HwpZgxHwXozlTgGqn63UyNX5k4= +github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df h1:MZf03xP9WdakyXhOWuAD5uPK3wHh96wCsqe3hCMKh8E= +github.com/iij/doapi v0.0.0-20190504054126-0bbf12d6d7df/go.mod h1:QMZY7/J/KSQEhKWFeDesPjMj+wCHReeknARU3wqlyN4= +github.com/imdario/mergo v0.3.5 h1:JboBksRwiiAJWvIYJVo46AfV+IAIKZpfrSzVKj42R4Q= +github.com/imdario/mergo v0.3.5/go.mod h1:2EnlNZ0deacrJVfApfmtdGgDfMuh/nq6Ok1EcJh5FfA= +github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc h1:KpMgaYJRieDkHZJWY3LMafvtqS/U8xX6+lUN+OKpl/Y= +github.com/influxdata/influxdb1-client v0.0.0-20190402204710-8ff2fc3824fc/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo= +github.com/instana/go-sensor v1.4.17-0.20190515112224-78c14625025a h1:S3CSPEIeIuXsxtwurn9dx41RoHIAvVjEeiQV6enM7WA= +github.com/instana/go-sensor v1.4.17-0.20190515112224-78c14625025a/go.mod h1:P1ynE0u78bUBZ2GkWewRpAO1/w1oW9CKDozeueH6QSg= +github.com/jcmturner/gofork v0.0.0-20190328161633-dc7c13fece03 h1:FUwcHNlEqkqLjLBdCp5PRlCFijNjvcYANOZXzCfXwCM= +github.com/jcmturner/gofork v0.0.0-20190328161633-dc7c13fece03/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= +github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= +github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= +github.com/json-iterator/go v0.0.0-20180701071628-ab8a2e0c74be/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.5/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/json-iterator/go v1.1.6 h1:MrUvLMLTMxbqFJ9kzlvat/rYZqZnW3u4wkLzWTaFwKs= +github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU= +github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/kolo/xmlrpc v0.0.0-20190717152603-07c4ee3fd181 h1:TrxPzApUukas24OMMVDUMlCs1XCExJtnGaDEiIAR4oQ= +github.com/kolo/xmlrpc v0.0.0-20190717152603-07c4ee3fd181/go.mod h1:o03bZfuBwAXHetKXuInt4S7omeXUu62/A845kiycsSQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2 h1:DB17ag19krx9CFsz4o3enTrPXyIXCl+2iCXH/aMAp9s= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY= +github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/labbsr0x/bindman-dns-webhook v1.0.0 h1:gooRvyQtVOCtV/l9ZCI4CManZeVN/kUWG/vugRqHqv4= +github.com/labbsr0x/bindman-dns-webhook v1.0.0/go.mod h1:pn4jcNjxSywRWDPDyGkFzgSnwty18OFdiUFc6S6fpgc= +github.com/labbsr0x/goh v0.0.0-20190417202808-8b16b4848295/go.mod h1:RBxeaayaaMmp7GxwHiKANjkg9e+rxjOm4mB5vD5rt/I= +github.com/labbsr0x/goh v0.0.0-20190610190554-60aa50bcbca7 h1:ocfbpesrzMqybD816LDEjourU4jiHj6gDGMieAcU8Io= +github.com/labbsr0x/goh v0.0.0-20190610190554-60aa50bcbca7/go.mod h1:RBxeaayaaMmp7GxwHiKANjkg9e+rxjOm4mB5vD5rt/I= +github.com/libkermit/compose v0.0.0-20171122111507-c04e39c026ad h1:nTyRWZ864mnHUnusBCVA628AZFgfGHwRUpbHqGhRQr8= +github.com/libkermit/compose v0.0.0-20171122111507-c04e39c026ad/go.mod h1:GyCk/ifDcqsU1tsRMMWqXANnTtxzcwEWscb7j5qmblM= +github.com/libkermit/docker v0.0.0-20171122101128-e6674d32b807 h1:/7J1WDQd6Xn1Pr8KtE2I/7/cKw66AV3hBUOyxqyXo84= +github.com/libkermit/docker v0.0.0-20171122101128-e6674d32b807/go.mod h1:std11u6pTaNwryy0Hy1dTQNdHKka1jNpflEieKtv5VE= +github.com/libkermit/docker-check v0.0.0-20171122104347-1113af38e591 h1:+zkZyvOyHZZUnITx0oJxAG/2+YLOjmy8YMMa1aWyrs4= +github.com/libkermit/docker-check v0.0.0-20171122104347-1113af38e591/go.mod h1:EBQ0jeOrBpOTkquwjmJl4W6z5xqlf5oA2LZfTqRNcO0= +github.com/linode/linodego v0.10.0 h1:AMdb82HVgY8o3mjBXJcUv9B+fnJjfDMn2rNRGbX+jvM= +github.com/linode/linodego v0.10.0/go.mod h1:cziNP7pbvE3mXIPneHj0oRY8L1WtGEIKlZ8LANE4eXA= +github.com/looplab/fsm v0.1.0 h1:Qte7Zdn/5hBNbXzP7yxVU4OIFHWXBovyTT2LaBTyC20= +github.com/looplab/fsm v0.1.0/go.mod h1:m2VaOfDHxqXBBMgc26m6yUOwkFn8H2AlJDE+jd/uafI= +github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4= +github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ= +github.com/mailgun/timetools v0.0.0-20141028012446-7e6055773c51 h1:Kg/NPZLLC3aAFr1YToMs98dbCdhootQ1hZIvZU28hAQ= +github.com/mailgun/timetools v0.0.0-20141028012446-7e6055773c51/go.mod h1:RYmqHbhWwIz3z9eVmQ2rx82rulEMG0t+Q1bzfc9DYN4= +github.com/mailgun/ttlmap v0.0.0-20170619185759-c1c17f74874f h1:ZZYhg16XocqSKPGNQAe0aeweNtFxuedbwwb4fSlg7h4= +github.com/mailgun/ttlmap v0.0.0-20170619185759-c1c17f74874f/go.mod h1:8heskWJ5c0v5J9WH89ADhyal1DOZcayll8fSbhB+/9A= +github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= +github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU= +github.com/mattn/go-tty v0.0.0-20180219170247-931426f7535a/go.mod h1:XPvLUNfbS4fJH25nqRHfWLMa1ONC8Amw+mIA639KxkE= +github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU= +github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0= +github.com/miekg/dns v1.1.15 h1:CSSIDtllwGLMoA6zjdKnaE6Tx6eVUxQ29LUgGetiDCI= +github.com/miekg/dns v1.1.15/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg= +github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ= +github.com/mitchellh/copystructure v1.0.0/go.mod h1:SNtv71yrdKgLRyLFxmLdkAbkKEFWgYaq1OVrnRcwhnw= +github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/go-vnc v0.0.0-20150629162542-723ed9867aed/go.mod h1:3rdaFaCv4AyBgu5ALFM0+tSuHrBh6v692nyQe3ikrq0= +github.com/mitchellh/hashstructure v1.0.0 h1:ZkRJX1CyOoTkar7p/mLS5TZU4nJ1Rn/F8u9dGS02Q3Y= +github.com/mitchellh/hashstructure v1.0.0/go.mod h1:QjSHrPWS+BGUVBYkbTZWEnOh3G1DutKwClXU/ABz6AQ= +github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= +github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= +github.com/mitchellh/reflectwalk v1.0.0 h1:9D+8oIskB4VJBN5SFlmc27fSlIBZaov1Wpk/IfikLNY= +github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.1 h1:9f412s+6RmYXLWZSEzVVgPGK7C2PphHj5RJrvfx9AWI= +github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c h1:nXxl5PrvVm2L/wCy8dQu6DMTwH4oIuGN8GJDAlqDdVE= +github.com/morikuni/aec v0.0.0-20170113033406-39771216ff4c/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc= +github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U= +github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f/go.mod h1:ZdcZmHo+o7JKHSa8/e818NopupXU1YMK5fe1lsApnBw= +github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04 h1:o6uBwrhM5C8Ll3MAAxrQxRHEu7FkapwTuI2WmL1rw4g= +github.com/namedotcom/go v0.0.0-20180403034216-08470befbe04/go.mod h1:5sN+Lt1CaY4wsPvgQH/jsuJi4XO2ssZbdsIizr4CVC8= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= +github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= +github.com/nrdcg/auroradns v1.0.0 h1:b+NpSqNG6HzMqX2ohGQe4Q/G0WQq8pduWCiZ19vdLY8= +github.com/nrdcg/auroradns v1.0.0/go.mod h1:6JPXKzIRzZzMqtTDgueIhTi6rFf1QvYE/HzqidhOhjw= +github.com/nrdcg/goinwx v0.6.1 h1:AJnjoWPELyCtofhGcmzzcEMFd9YdF2JB/LgutWsWt/s= +github.com/nrdcg/goinwx v0.6.1/go.mod h1:XPiut7enlbEdntAqalBIqcYcTEVhpv/dKWgDCX2SwKQ= +github.com/nrdcg/namesilo v0.2.1 h1:kLjCjsufdW/IlC+iSfAqj0iQGgKjlbUUeDJio5Y6eMg= +github.com/nrdcg/namesilo v0.2.1/go.mod h1:lwMvfQTyYq+BbjJd30ylEG4GPSS6PII0Tia4rRpRiyw= +github.com/olekukonko/tablewriter v0.0.1/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= +github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +github.com/onsi/gomega v0.0.0-20190113212917-5533ce8a0da3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.4.3/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= +github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= +github.com/opencontainers/go-digest v1.0.0-rc1 h1:WzifXhOVOEOuFYOJAW6aQqW0TooG2iki3E3Ii+WN7gQ= +github.com/opencontainers/go-digest v1.0.0-rc1/go.mod h1:cMLVZDEM3+U2I4VmLI6N8jQYUd2OVphdqWwCJHrFt2s= +github.com/opencontainers/image-spec v1.0.1 h1:JMemWkRwHx4Zj+fVxWoMCFm/8sYGGrUVojFA6h/TRcI= +github.com/opencontainers/image-spec v1.0.1/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/runc v1.0.0-rc8 h1:dDCFes8Hj1r/i5qnypONo5jdOme/8HWZC/aNDyhECt0= +github.com/opencontainers/runc v1.0.0-rc8/go.mod h1:qT5XzbpPznkRYVz/mWwUaVBUv2rmF59PVA73FjuZG0U= +github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492 h1:lM6RxxfUMrYL/f8bWEUqdXrANWtrL7Nndbm9iFN0DlU= +github.com/opentracing-contrib/go-observer v0.0.0-20170622124052-a52f23424492/go.mod h1:Ngi6UdF0k5OKD5t5wlmGhe/EDKPoUM3BXZSSfIuJbis= +github.com/opentracing/basictracer-go v1.0.0 h1:YyUAhaEfjoWXclZVJ9sGoNct7j4TVk7lZWlQw5UXuoo= +github.com/opentracing/basictracer-go v1.0.0/go.mod h1:QfBfYuafItcjQuMwinw9GhYKwFXS9KnPs5lxoYwgW74= +github.com/opentracing/opentracing-go v1.1.0 h1:pWlfV3Bxv7k65HYwkikxat0+s3pV4bsqf19k25Ur8rU= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/openzipkin-contrib/zipkin-go-opentracing v0.3.5 h1:82Tnq9OJpn+h5xgGpss5/mOv3KXdjtkdorFSOUusjM8= +github.com/openzipkin-contrib/zipkin-go-opentracing v0.3.5/go.mod h1:uVHyebswE1cCXr2A73cRM2frx5ld1RJUCJkFNZ90ZiI= +github.com/openzipkin/zipkin-go v0.1.6/go.mod h1:QgAqvLzwWbR/WpD4A3cGpPtJrZXNIiJc5AZX7/PBEpw= +github.com/oracle/oci-go-sdk v7.0.0+incompatible h1:oj5ESjXwwkFRdhZSnPlShvLWYdt/IZ65RQxveYM3maA= +github.com/oracle/oci-go-sdk v7.0.0+incompatible/go.mod h1:VQb79nF8Z2cwLkLS35ukwStZIg5F66tcBccjip/j888= +github.com/ovh/go-ovh v0.0.0-20181109152953-ba5adb4cf014 h1:37VE5TYj2m/FLA9SNr4z0+A0JefvTmR60Zwf8XSEV7c= +github.com/ovh/go-ovh v0.0.0-20181109152953-ba5adb4cf014/go.mod h1:joRatxRJaZBsY3JAOEMcoOp05CnZzsx4scTxi95DHyQ= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/philhofer/fwd v1.0.0 h1:UbZqGr5Y38ApvM/V/jEljVxwocdweyH+vmYvRPBnbqQ= +github.com/philhofer/fwd v1.0.0/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= +github.com/pierrec/lz4 v0.0.0-20190327172049-315a67e90e41/go.mod h1:3/3N9NVKO0jef7pBehbT1qWhCMrIgbYNnFAZCqQ5LRc= +github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= +github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= +github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw= +github.com/prometheus/client_golang v0.9.3-0.20190127221311-3c4408c8b829/go.mod h1:p2iRAGwDERtqlqzRXnrOVns+ignqQo//hLXqYxZYVNs= +github.com/prometheus/client_golang v1.0.0 h1:vrDKnkGzuGvhNAL56c7DBz29ZL+KxnoR0x7enabFceM= +github.com/prometheus/client_golang v1.0.0/go.mod h1:db9x61etRT2tGnBNRi70OPL5FsnadC4Ky3P0J6CfImo= +github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190115171406-56726106282f/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90 h1:S/YWwWx/RA8rT8tKFRuGUZhuA90OyIBpPCXkcbwU8DE= +github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/common v0.2.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.4.1/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4= +github.com/prometheus/common v0.6.0 h1:kRhiuYSXR3+uv2IbVbZhUxK5zVD/2pp3Gd2PpvPkpEo= +github.com/prometheus/common v0.6.0/go.mod h1:eBmuwkDJBwy6iBfxCBob6t6dR6ENT/y+J+Zk0j9GMYc= +github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.0-20190117184657-bf6a532e95b1/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk= +github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.0.3 h1:CTwfnzjQ+8dS6MhHHu4YswVAD99sL2wjPqP+VkURmKE= +github.com/prometheus/procfs v0.0.3/go.mod h1:4A/X28fw3Fc593LaREMrKMqOKvUAntwMDaekg4FpcdQ= +github.com/rainycape/memcache v0.0.0-20150622160815-1031fa0ce2f2/go.mod h1:7tZKcyumwBO6qip7RNQ5r77yrssm9bfCowcLEBcU5IA= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a h1:9ZKAASQSHhDYGoxY8uLVpewe1GDZ2vu2Tr/vTdVAkFQ= +github.com/rcrowley/go-metrics v0.0.0-20181016184325-3113b8401b8a/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4= +github.com/remyoudompheng/bigfft v0.0.0-20170806203942-52369c62f446/go.mod h1:uYEyJGbgTkfkS4+E/PavXkNJcbFIpEtjt2B0KDQ5+9M= +github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg= +github.com/sacloud/libsacloud v1.26.1 h1:td3Kd7lvpSAxxHEVpnaZ9goHmmhi0D/RfP0Rqqf/kek= +github.com/sacloud/libsacloud v1.26.1/go.mod h1:79ZwATmHLIFZIMd7sxA3LwzVy/B77uj3LDoToVTxDoQ= +github.com/samuel/go-zookeeper v0.0.0-20180130194729-c4fab1ac1bec/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2 h1:SPIRibHv4MatM3XXNO2BJeFLZwZ2LvZgfQ5+UNI2im4= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/skratchdot/open-golang v0.0.0-20160302144031-75fb7ed4208c/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM= +github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a h1:pa8hGb/2YqsZKovtsgrwcDH1RZhVbTKCjLp47XpqCDs= +github.com/smartystreets/goconvey v0.0.0-20190330032615-68dc04aab96a/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA= +github.com/spf13/pflag v1.0.1 h1:aCvUg6QPl3ibpQUxyLkrEkCHtPqYJL4x9AuhqVqFis4= +github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stvp/go-udp-testing v0.0.0-20171104055251-c4434f09ec13 h1:WYRIgR83bWdH2zjqXalfLuQYtgBG1KKxDRxinx2ygMI= +github.com/stvp/go-udp-testing v0.0.0-20171104055251-c4434f09ec13/go.mod h1:7jxmlfBCDBXRzr0eAQJ48XC1hBu1np4CS5+cHEYfwpc= +github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7 h1:CpHxIaZzVy26GqJn8ptRyto8fuoYOd1v0fXm9bG3wQ8= +github.com/timewasted/linode v0.0.0-20160829202747-37e84520dcf7/go.mod h1:imsgLplxEC/etjIhdr3dNzV3JeT27LbVu5pYWm0JCBY= +github.com/tinylib/msgp v1.0.2 h1:DfdQrzQa7Yh2es9SuLkixqxuXS2SxsdYn0KbdrOGWD8= +github.com/tinylib/msgp v1.0.2/go.mod h1:+d+yLhGm8mzTaHzB+wgMYrodPfmZrzkirds8fDWklFE= +github.com/transip/gotransip v0.0.0-20190812104329-6d8d9179b66f/go.mod h1:i0f4R4o2HM0m3DZYQWsj6/MEowD57VzoH0v3d7igeFY= +github.com/transip/gotransip v5.8.2+incompatible h1:aNJhw/w/3QBqFcHAIPz1ytoK5FexeMzbUCGrrhWr3H0= +github.com/transip/gotransip v5.8.2+incompatible/go.mod h1:uacMoJVmrfOcscM4Bi5NVg708b7c6rz2oDTWqa7i2Ic= +github.com/uber-go/atomic v1.3.2 h1:Azu9lPBWRNKzYXSIwRfgRuDuS0YKsK4NFhiQv98gkxo= +github.com/uber-go/atomic v1.3.2/go.mod h1:/Ct5t2lcmbJ4OSe/waGBoaVvVqtO0bmtfVNex1PFV8g= +github.com/uber/jaeger-client-go v2.16.0+incompatible h1:Q2Pp6v3QYiocMxomCaJuwQGFt7E53bPYqEgug/AoBtY= +github.com/uber/jaeger-client-go v2.16.0+incompatible/go.mod h1:WVhlPFC8FDjOFMMWRy2pZqQJSXxYSwNYOkTr/Z6d3Kk= +github.com/uber/jaeger-lib v2.0.0+incompatible h1:iMSCV0rmXEogjNWPh2D0xk9YVKvrtGoHJNe9ebLu/pw= +github.com/uber/jaeger-lib v2.0.0+incompatible/go.mod h1:ComeNDZlWwrWnDv8aPp0Ba6+uUTzImX/AauajbLI56U= +github.com/ugorji/go v0.0.0-20171019201919-bdcc60b419d1/go.mod h1:hnLbHMwcvSihnDhEfx2/BzKp2xb0Y+ErdfYcrs9tkJQ= +github.com/unrolled/render v1.0.1 h1:VDDnQQVfBMsOsp3VaCJszSO0nkBIVEYoPWeRThk9spY= +github.com/unrolled/render v1.0.1/go.mod h1:gN9T0NhL4Bfbwu8ann7Ry/TGHYfosul+J0obPf6NBdM= +github.com/unrolled/secure v1.0.1 h1:PZ79/VmnyIrDWRAUp9lWSwmckdf8H0v9djiqZxAb8Tc= +github.com/unrolled/secure v1.0.1/go.mod h1:R6rugAuzh4TQpbFAq69oqZggyBQxFRFQIewtz5z7Jsc= +github.com/urfave/cli v1.21.0/go.mod h1:lxDj6qX9Q6lWQxIrbrT0nwecwUtRnhVZAJjJZrVUZZQ= +github.com/vdemeester/shakers v0.1.0 h1:K+n9sSyUCg2ywmZkv+3c7vsYZfivcfKhMh8kRxCrONM= +github.com/vdemeester/shakers v0.1.0/go.mod h1:IZ1HHynUOQt32iQ3rvAeVddXLd19h/6LWiKsh9RZtAQ= +github.com/vulcand/oxy v1.0.0 h1:7vL5/pjDFzHGbtBEhmlHITUi6KLH4xXTDF33/wrdRKw= +github.com/vulcand/oxy v1.0.0/go.mod h1:6EXgOAl6CRa46/2ZGcDJKf3ywJUp5WtT7vSlGSkvecI= +github.com/vulcand/predicate v1.1.0 h1:Gq/uWopa4rx/tnZu2opOSBqHK63Yqlou/SzrbwdJiNg= +github.com/vulcand/predicate v1.1.0/go.mod h1:mlccC5IRBoc2cIFmCB8ZM62I3VDb6p2GXESMHa3CnZg= +github.com/vultr/govultr v0.1.4 h1:UnNMixYFVO0p80itc8PcweoVENyo1PasfvwKhoasR9U= +github.com/vultr/govultr v0.1.4/go.mod h1:9H008Uxr/C4vFNGLqKx232C206GL0PBHzOP0809bGNA= +github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I= +github.com/xdg/stringprep v1.0.0/go.mod h1:Jhud4/sHMO4oL310DaZAKk9ZaJ08SJfe+sJh0HrGL1Y= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.1.0 h1:ngVtJC9TY/lg0AA/1k48FYhBrhRoFlEmWzsehpNAaZg= +github.com/xeipuuv/gojsonschema v1.1.0/go.mod h1:5yf86TLmAcydyeJq5YvxkGPE2fm/u4myDekKRoLuqhs= +go.etcd.io/bbolt v1.3.1-etcd.8/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= +go.etcd.io/etcd v3.3.13+incompatible/go.mod h1:yaeTdrJi5lOmYerz05bd8+V7KubZs8YSFZfzsF9A6aI= +go.opencensus.io v0.20.1/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.20.2/go.mod h1:6WKK9ahsWS3RSO+PY9ZHZUfv2irvY6gN279GOPZjmmk= +go.opencensus.io v0.21.0 h1:mU6zScU4U1YAFPHEHYk+3JC4SY7JxgkqS10ZOSyksNg= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.uber.org/atomic v1.3.2 h1:2Oa65PReHzfn29GpvgsYwloV9AVFHPDk8tYxt2c2tr4= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277 h1:d9qaMM+ODpCq+9We41//fu/sHsTnXcrqd1en3x+GKy4= +go.uber.org/ratelimit v0.0.0-20180316092928-c15da0234277/go.mod h1:2X8KaoNd1J0lZV+PxJk/5+DGbO/tpwLR1m++a7FnB/Y= +golang.org/x/crypto v0.0.0-20180621125126-a49355c7e3f8/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20181025213731-e84da0312774/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190211182817-74369b46fc67/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190404164418-38d8ce5564a5/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190418165655-df01cb2cc480/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4 h1:HuIa8hRrWRSrqYzx1qI49NNxhdi2PrY7gxVSq1JjLDc= +golang.org/x/crypto v0.0.0-20190701094942-4def268fd1a4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495 h1:I6A9Ag9FpEKOjcKrRNjQkPHawoXIhKyTGfvvjFAiiAk= +golang.org/x/exp v0.0.0-20190312203227-4b39c73a6495/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/net v0.0.0-20180611182652-db08ff08e862/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190125091013-d26f9f9a57f3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190206173232-65e2d4e15006/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190613194153-d28f0bde5980/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80 h1:Ao/3l156eZf2AW5wK8a7/smtodRU+gha3+BeqJ69lRk= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190402181905-9f3314589c9a/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180622082034-63fc586f45fe/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20181122145206-62eef0e2fa9b/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190209173611-3b5209105503/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b h1:ag/x1USPSsqHud38I9BAC88qdNLDHHtQ4mlgQIZPPNA= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a h1:aYOabOQFp6Vj6W1F80affTUvO9UxmJRx8K0gsfABByQ= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20181227161524-e6919f6577db/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/time v0.0.0-20161028155119-f51c12702a4d/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c h1:97SnQk1GYRXJgvwZ8fadnxDOWfKvkNQHH3CtZntPSrM= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135 h1:5Beo0mZN8dRzgrMMkDp0jc8YXQKx9DiJ2k1dkvGsn5A= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485 h1:OB/uP/Puiu5vS5QMRPrXCDWUPb+kt8f1KW8oQzFejQw= +gonum.org/v1/gonum v0.0.0-20190331200053-3d26580ed485/go.mod h1:2ltnJ7xHfj0zHS40VVPYEAAMTa3ZGguvHGBSJeRWqE0= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e h1:jRyg0XfpwWlhEV8mDfdNGBeSJM2fuyh9Yjrnd8kF2Ts= +gonum.org/v1/netlib v0.0.0-20190331212654-76723241ea4e/go.mod h1:kS+toOQn6AQKjmKJ7gzohV1XkqsFehRA2FbsbkopSuQ= +google.golang.org/api v0.3.1/go.mod h1:6wY9I6uQWHQ8EM57III9mq/AjF+i8G65rmVagqKMtkk= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.8.0 h1:VGGbLNyPF7dvYHhcUGYBBGCRDDK0RRJAI6KCvo0CL+E= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0 h1:KxkO13IPW4Lslp2bz+KHP2E3gtFlrIGNThxkZQ3g+4c= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873 h1:nfPFGzJkUDX6uBmpN/pSw7MbOAWegH5QDQuoXFHedLg= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/grpc v1.17.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.18.0/go.mod h1:6QZJwpn2B+Zp71q/5VxRsJ6NXXVCE5NRUHRo+f3cWCs= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.19.1/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1 h1:Hz2g2wirWK7H0qIIhGIqRGTuMwTE8HEKFnDZZ7lm9NU= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.22.1 h1:/7cs52RnTJmD43s3uxzlq2U7nqVTd/37viQwMrMNlOM= +google.golang.org/grpc v1.22.1/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +gopkg.in/DataDog/dd-trace-go.v1 v1.16.1 h1:Dngw1zun6yTYFHNdzEWBlrJzFA2QJMjSA2sZ4nH2UWo= +gopkg.in/DataDog/dd-trace-go.v1 v1.16.1/go.mod h1:DVp8HmDh8PuTu2Z0fVVlBsyWaC++fzwVCaGWylTe3tg= +gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/h2non/gock.v1 v1.0.15 h1:SzLqcIlb/fDfg7UvukMpNcWsu7sI5tWwL+KCATZqks0= +gopkg.in/h2non/gock.v1 v1.0.15/go.mod h1:sX4zAkdYX1TRGJ2JY156cFspQn4yRWn6p9EMdODlynE= +gopkg.in/inf.v0 v0.9.0 h1:3zYtXIO92bvsdS3ggAdA8Gb4Azj0YU+TVY1uGYNFA8o= +gopkg.in/inf.v0 v0.9.0/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/ini.v1 v1.42.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/ini.v1 v1.44.0 h1:YRJzTUp0kSYWUVFF5XAbDFfyiqwsl0Vb9R8TVP5eRi0= +gopkg.in/ini.v1 v1.44.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/jcmturner/aescts.v1 v1.0.1 h1:cVVZBK2b1zY26haWB4vbBiZrfFQnfbTVrE3xZq6hrEw= +gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= +gopkg.in/jcmturner/dnsutils.v1 v1.0.1 h1:cIuC1OLRGZrld+16ZJvvZxVJeKPsvd5eUIvxfoN5hSM= +gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= +gopkg.in/jcmturner/goidentity.v3 v3.0.0 h1:1duIyWiTaYvVx3YX2CYtpJbUFd7/UuPYCfgXtQ3VTbI= +gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= +gopkg.in/jcmturner/gokrb5.v7 v7.2.3 h1:hHMV/yKPwMnJhPuPx7pH2Uw/3Qyf+thJYlisUc44010= +gopkg.in/jcmturner/gokrb5.v7 v7.2.3/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= +gopkg.in/jcmturner/rpc.v1 v1.1.0 h1:QHIUxTX1ISuAv9dD2wJ9HWQVuWDX/Zc0PfeC2tjc4rU= +gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8= +gopkg.in/ns1/ns1-go.v2 v2.0.0-20190730140822-b51389932cbc h1:GAcf+t0o8gdJAdSFYdE9wChu4bIyguMVqz0RHiFL5VY= +gopkg.in/ns1/ns1-go.v2 v2.0.0-20190730140822-b51389932cbc/go.mod h1:VV+3haRsgDiVLxyifmMBrBIuCWFBPYKbRssXB9z67Hw= +gopkg.in/redis.v5 v5.2.9/go.mod h1:6gtv0/+A4iM08kdRfocWYB3bLX2tebpNtfKlFT6H4mY= +gopkg.in/resty.v1 v1.9.1/go.mod h1:vo52Hzryw9PnPHcJfPsBiFW62XhNx5OczbV9y+IMpgc= +gopkg.in/resty.v1 v1.12.0 h1:CuXP0Pjfw9rOuY6EP+UvtNvt5DSqHpIxILZKT/quCZI= +gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo= +gopkg.in/square/go-jose.v2 v2.3.1 h1:SK5KegNXmKmqE342YYN2qPHEnUYeoMiXXl1poUlI+o4= +gopkg.in/square/go-jose.v2 v2.3.1/go.mod h1:M9dMgbHiYLoDGQrXy7OpJDJWiKiU//h+vD76mk0e1AI= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools v2.2.0+incompatible/go.mod h1:DsYFclhRJ6vuDpmuTbkuFWG+y2sxOXAzmJt81HFBacw= +honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +k8s.io/api v0.0.0-20190718183219-b59d8169aab5 h1:X3LHYU4fwu75lvvWypbppCKuhqg1KrvcZ1lLaAgmE/g= +k8s.io/api v0.0.0-20190718183219-b59d8169aab5/go.mod h1:TBhBqb1AWbBQbW3XRusr7n7E4v2+5ZY8r8sAMnyFC5A= +k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719 h1:uV4S5IB5g4Nvi+TBVNf3e9L4wrirlwYJ6w88jUQxTUw= +k8s.io/apimachinery v0.0.0-20190612205821-1799e75a0719/go.mod h1:I4A+glKBHiTgiEjQiCCQfCAIcIMFGt291SmsvcrFzJA= +k8s.io/client-go v0.0.0-20190718183610-8e956561bbf5 h1:ZIHnBytv9H1jiI7K/Szva829lP6zKsluhjVRdxf5kHA= +k8s.io/client-go v0.0.0-20190718183610-8e956561bbf5/go.mod h1:ozblAqkW495yoAX60QZyxQBq5W0YixE9Ffn4F91RO0g= +k8s.io/code-generator v0.0.0-20190612205613-18da4a14b22b h1:p+PRuwXWwk5e+UYvicGiavEupapqM5NOxUl3y1GkD6c= +k8s.io/code-generator v0.0.0-20190612205613-18da4a14b22b/go.mod h1:G8bQwmHm2eafm5bgtX67XDZQ8CWKSGu9DekI+yN4Y5I= +k8s.io/gengo v0.0.0-20190116091435-f8a0810f38af h1:SwjZbO0u5ZuaV6TRMWOGB40iaycX8sbdMQHtjNZ19dk= +k8s.io/gengo v0.0.0-20190116091435-f8a0810f38af/go.mod h1:ezvh/TsK7cY6rbqRK0oQQ8IAqLxYwwyPxAX1Pzy0ii0= +k8s.io/klog v0.3.1 h1:RVgyDHY/kFKtLqh67NvEWIgkMneNoIrdkN0CxDSQc68= +k8s.io/klog v0.3.1/go.mod h1:Gq+BEi5rUBO/HRz0bTSXDUcqjScdoY3a9IHpCEIOOfk= +k8s.io/kube-openapi v0.0.0-20190228160746-b3a7cee44a30 h1:TRb4wNWoBVrH9plmkp2q86FIDppkbrEXdXlxU3a3BMI= +k8s.io/kube-openapi v0.0.0-20190228160746-b3a7cee44a30/go.mod h1:BXM9ceUBTj2QnfH2MK1odQs778ajze1RxcmP6S8RVVc= +k8s.io/utils v0.0.0-20190221042446-c2654d5206da h1:ElyM7RPonbKnQqOcw7dG2IK5uvQQn3b/WPHqD5mBvP4= +k8s.io/utils v0.0.0-20190221042446-c2654d5206da/go.mod h1:8k8uAuAQ0rXslZKaEWd0c3oVhZz7sSzSiPnVZayjIX0= +modernc.org/cc v1.0.0/go.mod h1:1Sk4//wdnYJiUIxnW8ddKpaOJCF37yAdqYnkxUpaYxw= +modernc.org/golex v1.0.0/go.mod h1:b/QX9oBD/LhixY6NDh+IdGv17hgB+51fET1i2kPSmvk= +modernc.org/mathutil v1.0.0/go.mod h1:wU0vUrJsVWBZ4P6e7xtFJEhFSNsfRLJ8H458uRjg03k= +modernc.org/strutil v1.0.0/go.mod h1:lstksw84oURvj9y3tn8lGvRxyRC1S2+g5uuIzNfIOBs= +modernc.org/xc v1.0.0/go.mod h1:mRNCo0bvLjGhHO9WsyuKVU4q0ceiDDDoEeWDJHrNx8I= +mvdan.cc/xurls/v2 v2.0.0 h1:r1zSOSNS/kqtpmATyMMMvaZ4/djsesbYz5kr0+qMRWc= +mvdan.cc/xurls/v2 v2.0.0/go.mod h1:2/webFPYOXN9jp/lzuj0zuAVlF+9g4KPFJANH1oJhRU= +sigs.k8s.io/yaml v1.1.0 h1:4A07+ZFc2wgJwo8YNlQpr1rVlgUDlxXHhPJciaPY5gs= +sigs.k8s.io/yaml v1.1.0/go.mod h1:UJmg0vDUVViEyp3mgSv9WPwZCDxu4rQW1olrI1uml+o= diff --git a/integration/access_log_test.go b/integration/access_log_test.go index c87daaaf3..5017b2132 100644 --- a/integration/access_log_test.go +++ b/integration/access_log_test.go @@ -11,9 +11,9 @@ import ( "strings" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/acme_test.go b/integration/acme_test.go index 23c774b6b..d253b3ace 100644 --- a/integration/acme_test.go +++ b/integration/acme_test.go @@ -10,11 +10,11 @@ import ( "path/filepath" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/provider/acme" - "github.com/containous/traefik/pkg/testhelpers" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/provider/acme" + "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/types" "github.com/go-check/check" "github.com/miekg/dns" checker "github.com/vdemeester/shakers" diff --git a/integration/docker_compose_test.go b/integration/docker_compose_test.go index 5d81608ff..d499d2258 100644 --- a/integration/docker_compose_test.go +++ b/integration/docker_compose_test.go @@ -6,9 +6,9 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/api" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/api" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/docker_test.go b/integration/docker_test.go index b60a5d0c0..9e5db3972 100644 --- a/integration/docker_test.go +++ b/integration/docker_test.go @@ -9,7 +9,7 @@ import ( "strings" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/docker/docker/pkg/namesgenerator" "github.com/go-check/check" d "github.com/libkermit/docker" diff --git a/integration/error_pages_test.go b/integration/error_pages_test.go index b321b909f..5a4fd4afb 100644 --- a/integration/error_pages_test.go +++ b/integration/error_pages_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/fake_dns_server.go b/integration/fake_dns_server.go index 4c4fc1709..1c4c7a6cd 100644 --- a/integration/fake_dns_server.go +++ b/integration/fake_dns_server.go @@ -5,7 +5,7 @@ import ( "net" "os" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/miekg/dns" ) diff --git a/integration/file_test.go b/integration/file_test.go index 0a9db2266..85079b4e0 100644 --- a/integration/file_test.go +++ b/integration/file_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/fixtures/https/clientca/https_2ca1config.toml b/integration/fixtures/https/clientca/https_2ca1config.toml index 34ea565e9..948374c04 100644 --- a/integration/fixtures/https/clientca/https_2ca1config.toml +++ b/integration/fixtures/https/clientca/https_2ca1config.toml @@ -31,12 +31,12 @@ [http.services.service1] [http.services.service1.loadBalancer] [[http.services.service1.loadBalancer.servers]] - url = "http://127.0.0.1:9010" + url = "{{ .Server1 }}" [http.services.service2] [http.services.service2.loadBalancer] [[http.services.service2.loadBalancer.servers]] - url = "http://127.0.0.1:9020" + url = "{{ .Server2 }}" [[tls.certificates]] certFile = "fixtures/https/snitest.com.cert" diff --git a/integration/fixtures/https/clientca/https_2ca2config.toml b/integration/fixtures/https/clientca/https_2ca2config.toml index bec6abde7..5757ac602 100644 --- a/integration/fixtures/https/clientca/https_2ca2config.toml +++ b/integration/fixtures/https/clientca/https_2ca2config.toml @@ -30,12 +30,12 @@ [http.services.service1] [http.services.service1.loadBalancer] [[http.services.service1.loadBalancer.servers]] - url = "http://127.0.0.1:9010" + url = "{{ .Server1 }}" [http.services.service2] [http.services.service2.loadBalancer] [[http.services.service2.loadBalancer.servers]] - url = "http://127.0.0.1:9020" + url = "{{ .Server2 }}" [[tls.certificates]] certFile = "fixtures/https/snitest.com.cert" diff --git a/integration/fixtures/k8s/02-secrets.yml b/integration/fixtures/k8s/02-secrets.yml new file mode 100644 index 000000000..031c8a195 --- /dev/null +++ b/integration/fixtures/k8s/02-secrets.yml @@ -0,0 +1,9 @@ +apiVersion: v1 +kind: Secret +metadata: + name: tls-cert + namespace: default +type: kubernetes.io/tls +data: + tls.crt: LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUMvekNDQWVlZ0F3SUJBZ0lKQUw4NThwY2k1WHlqTUEwR0NTcUdTSWIzRFFFQkJRVUFNQll4RkRBU0JnTlYKQkFNTUMzTnVhWFJsYzNRdVkyOXRNQjRYRFRFMU1URXlNekl5TURVMU5sb1hEVEkxTVRFeU1ESXlNRFUxTmxvdwpGakVVTUJJR0ExVUVBd3dMYzI1cGRHVnpkQzVqYjIwd2dnRWlNQTBHQ1NxR1NJYjNEUUVCQVFVQUE0SUJEd0F3CmdnRUtBb0lCQVFEVkYyNXdFcm9TSVVPL2ROZ0h4bHl0OHBaRlZwSjhmTmFKdzdjbmxaMUpQMmhMdUVibWpBRlQKZEhxUzh3S0ROWUhrdHNCRU9VZk4vcWJrMEFpR2IrU3ZoUXc2a2ZNL1FTajlmWFZRN0toWVA5WFlPZWtUT0g3ZApNMFoyTDNSR2dxczh6KzgzZXhPT25BRlZ2SUpDTVpKWEVlaWpWNmlKbG1wQ2NKYTBLZy9KSGx4aG9XVEVlWnVVCkcraElUYWZrMXlXT0tvclRDUGxNaEIzMHd1UW9XZmJIUCszRzBic0VSTFhGaU1BTkU4RXRRdTgrWmhmc2VCVWgKNVR1NWdJQzRGbnJpYTdtUml4QVplRWlBYmxGUDloMHZyTlJjUDNubXVWejB0SFBJZVFzSlFpRWh4YVowOW9VVwpoOVdxVHNZQ1AxODIxK1NWYXpNOW9GUlRweTZjaFp5VEFnTUJBQUdqVURCT01CMEdBMVVkRGdRV0JCU3o5bWJYCmlhMVRNNUZHNFpnYWdhZXQyNFM4SERBZkJnTlZIU01FR0RBV2dCU3o5bWJYaWExVE01Rkc0WmdhZ2FldDI0UzgKSERBTUJnTlZIUk1FQlRBREFRSC9NQTBHQ1NxR1NJYjNEUUVCQlFVQUE0SUJBUUI3OVc4WFR4bG96aDl3L1c3VAo1dkRldjY3RzRUL3dldEFCU2I2OENScnFvanQ3OFBNSnVTODlKYXJBOEkzdHMwME8rMEpZbnNIeHArOXFDN3BmCmpXSGNEU2lMd1JVTXU3TVhXL0tJZW4xRUI4QlFOQTB4V2JBaVFhV1lQSHpzQmxYNDgrOXdCZTBIVER4N0xjeGIKT3NtblhIQkY1ZmQyRVkrUjhxSnUrUHlURERMMVdMSXRGSnB6SGlGaUdpWUY4VHlpYzNra1BqamU2ZUlPeFJtVApocStxYndBcHpieno2aC9WRDV4UjN6QkRGQm8yWHM1dGRQMjY0S0l3L1lYRHBhWFZCaUo1RERqUTNkdEp3MUc1Cnl6Z3JIUVpXSk44R3M4WlpnR2RnUmY3UEhveDh4RVp0cVBpTWtDaER6NlQ3SGEzVTB4WU42VFpHTlpPUjZESHMKSzkvOAotLS0tLUVORCBDRVJUSUZJQ0FURS0tLS0tCg== + tls.key: LS0tLS1CRUdJTiBSU0EgUFJJVkFURSBLRVktLS0tLQpNSUlFcFFJQkFBS0NBUUVBMVJkdWNCSzZFaUZEdjNUWUI4WmNyZktXUlZhU2ZIeldpY08zSjVXZFNUOW9TN2hHCjVvd0JVM1I2a3ZNQ2d6V0I1TGJBUkRsSHpmNm01TkFJaG0va3I0VU1PcEh6UDBFby9YMTFVT3lvV0QvVjJEbnAKRXpoKzNUTkdkaTkwUm9LclBNL3ZOM3NUanB3QlZieUNRakdTVnhIb28xZW9pWlpxUW5DV3RDb1B5UjVjWWFGawp4SG1ibEJ2b1NFMm41TmNsamlxSzB3ajVUSVFkOU1Ma0tGbjJ4ei90eHRHN0JFUzF4WWpBRFJQQkxVTHZQbVlYCjdIZ1ZJZVU3dVlDQXVCWjY0bXU1a1lzUUdYaElnRzVSVC9ZZEw2elVYRDk1NXJsYzlMUnp5SGtMQ1VJaEljV20KZFBhRkZvZlZxazdHQWo5Zk50ZmtsV3N6UGFCVVU2Y3VuSVdja3dJREFRQUJBb0lCQUJBZFFZREFLY29OTWU1YwppNm1xMm45ZEJQZ2hYOXFDSmtjc3djRUFrM0JpbHlTQ3Z2bllSSkZuRVkzalNxRlpmb1VwUE1qcisvNGI3OHNGCjRGOHFQd1QyN3NIUEg3SDgzM2lyOEI4NmhsQ0dJMG5DdDFsNHdEOUNEV1lLbUtSc1pUNm9DdE1MUDZOZE1NeW4KQU1LNHRQUllxbHNQMmZMdHFRTjFPREJQcmZucmFvTkh0T1ZFNzg0aUJDRDVkZXdJQ0E1UklRRzJpL2QyK0NHRgorYmFoRnFVWFZDcUhveEJ6NEFWdnJSRkw5OVZjUDdQMmlaeWs2aERRN2ZjaTdYYXk4V2IvSHV0Unh1cXZGMGFVCmJHNkVuazZDQ3ROWkhMd05QcDRIcWZ0MFVkdmcydEc4b2tZd2JFbW9FTzQwblFzQ1N6UkNwcTVVdnppK0xYMWsKTHlrUTYrRUNnWUVBN3g4dlFveU9LNjBRM0xQcEpGR0RlYzIrWEpQb2VzVGZKVFQ2aWRhUDd1a1VMOHAzRnNVbwo5dnR4UlJmaFNPZFBvQUlObXJMMFR5TWVrTzJCNnpYeDBwbVdWcE1yRndaVzZ6TXdaQW5McC93KzNVU3BiR0N5CksxMklJd3ZSWXpUekt3b01UVkFLVFhtMzZiNm9xcjJMYTRiVGRKUjdSRVk2RzM3NEZySmIvSDBDZ1lFQTVDSGsKWW0waDdjZjAwZnc5VUVIUmZ6VVp4bUNmUldZNks4SW5PdUhkTGkrdTRUaXlYenM4eDVzMGUvRE4vcmFObVRHeApRTzgxVXp1UzNuS3djNG41UXlYalZuaHpSNURiYlNBQ0R3SHRkbnhaQnlMMEQxS3ZQanRSRjhGK3JXWFZpWHYyClRNN1VpT21uNlIzNzVGUFNBUHhleU14OFdvbWMzRW5BQWZMV0drOENnWUVBdjhJMldCdjNkemNXcXFic2RGK2EKRy9mT2pOZGdPL1BkTHkxSkxYaVBmSHdWNEMxeFN5VlpNSmQ3d25qZ0JXTGFDK3NabGRHazhrR3JwWFdTRmxudwpUMzh6Zk1JUWNDcDVVYXgvUmZwRkE3WFpoQUFvRGUyTmRCRlJ0eWtuQlhQVS9kTFZBcnNKU0JBd1dKYTVGQk5rCjF4b01RUlZCdFFMTVhuaDM0MXV0UU5FQ2dZRUE0bzFSMi9rYTE2TmFXbXBQalhNL2xEOXNrRmdGODRwNHZGbjgKVVhwYUIzTHREZGNiTkgyRWQ0bUhUb291V0FSOGpDVVFMVGNnMHI1M3RSZGFhZk1jS2ZYblZVa2Eybmhkb0hwSAo4UlZ0OTl1M0llSXhVMEkrcStPR1BidzNqQVYwVVN0Y3hwd2o3cTl6dzRxMlN1Sit5K0hVVXo3WFE2WWpzNVE5CjdQRjJjL3NDZ1lFQWhkVm41Z1o1RnZZS3JCaTQ2dDNweFBzV0s0NzZIbVFFVkhWaTUrb2Q3d2crYXJhRGVsQWUKOFFFOGhjOHFkWkdiamRCL0FIU1BDZVV4Zk8ydm5wc0NvU1JzMjlvNnBEdlF1cXZIWXMrTTUzbDVMRVllT2pvZgp0NkovREs1UGltMkNBRmpZRmNaazgvR3lsNUhqVHczUHBkV3hvUEQ1djJYdzNiYlk1N0lJYm00PQotLS0tLUVORCBSU0EgUFJJVkFURSBLRVktLS0tLQo= diff --git a/integration/fixtures/k8s/03-ingress-https.yml b/integration/fixtures/k8s/03-ingress-https.yml new file mode 100644 index 000000000..e214be777 --- /dev/null +++ b/integration/fixtures/k8s/03-ingress-https.yml @@ -0,0 +1,17 @@ +apiVersion: extensions/v1beta1 +kind: Ingress +metadata: + name: test.ingress.https + namespace: default + +spec: + rules: + - host: whoami.test.https + http: + paths: + - path: /whoami + backend: + serviceName: whoami + servicePort: http + tls: + - secretName: tls-cert diff --git a/integration/fixtures/k8s/05-ingressroutetcp.yml b/integration/fixtures/k8s/05-ingressroutetcp.yml index f7b1896a8..8c9fbf7d1 100644 --- a/integration/fixtures/k8s/05-ingressroutetcp.yml +++ b/integration/fixtures/k8s/05-ingressroutetcp.yml @@ -1,7 +1,7 @@ apiVersion: traefik.containo.us/v1alpha1 kind: IngressRouteTCP metadata: - name: test3.crd + name: test3.route namespace: default spec: diff --git a/vendor/github.com/modern-go/reflect2/reflect2_amd64.s b/integration/fixtures/k8s/config.skip/.gitkeep similarity index 100% rename from vendor/github.com/modern-go/reflect2/reflect2_amd64.s rename to integration/fixtures/k8s/config.skip/.gitkeep diff --git a/integration/fixtures/mirror.toml b/integration/fixtures/mirror.toml new file mode 100644 index 000000000..a5a07cce8 --- /dev/null +++ b/integration/fixtures/mirror.toml @@ -0,0 +1,44 @@ +[global] + checkNewVersion = false + sendAnonymousUsage = false + +[api] + +[log] + level = "DEBUG" + +[entryPoints] + + [entryPoints.web] + address = ":8000" + +[providers.file] + filename = "{{ .SelfFilename }}" + +## dynamic configuration ## + +[http.routers] + [http.routers.router] + service = "mirror" + rule = "Path(`/whoami`)" + +[http.services] + [http.services.mirror.mirroring] + service = "service1" + [[http.services.mirror.mirroring.mirrors]] + name = "mirror1" + percent = 10 + [[http.services.mirror.mirroring.mirrors]] + name = "mirror2" + percent = 50 + + [http.services.service1.loadBalancer] + [[http.services.service1.loadBalancer.servers]] + url = "{{ .MainServer }}" + [http.services.mirror1.loadBalancer] + [[http.services.mirror1.loadBalancer.servers]] + url = "{{ .Mirror1Server }}" + [http.services.mirror2.loadBalancer] + [[http.services.mirror2.loadBalancer.servers]] + url = "{{ .Mirror2Server }}" + diff --git a/integration/fixtures/ratelimit/simple.toml b/integration/fixtures/ratelimit/simple.toml index 49373088a..7bdb5a367 100644 --- a/integration/fixtures/ratelimit/simple.toml +++ b/integration/fixtures/ratelimit/simple.toml @@ -24,15 +24,8 @@ [http.middlewares] [http.middlewares.ratelimit.rateLimit] - extractorfunc = "client.ip" - [http.middlewares.ratelimit.rateLimit.rateSet.rateset1] - period = "60s" - average = 4 - burst = 5 - [http.middlewares.ratelimit.rateLimit.rateSet.rateset2] - period = "3s" - average = 1 - burst = 2 + average = 100 + burst = 1 [http.services] [http.services.service1] diff --git a/integration/fixtures/tcp/multi-tls-options.toml b/integration/fixtures/tcp/multi-tls-options.toml index 9aca38006..b36dae76a 100644 --- a/integration/fixtures/tcp/multi-tls-options.toml +++ b/integration/fixtures/tcp/multi-tls-options.toml @@ -34,7 +34,6 @@ [tcp.services.whoami-no-cert] [tcp.services.whoami-no-cert.loadBalancer] - method = "wrr" [[tcp.services.whoami-no-cert.loadBalancer.servers]] address = "localhost:8083" diff --git a/integration/fixtures/wrr.toml b/integration/fixtures/wrr.toml new file mode 100644 index 000000000..ad63ceb0d --- /dev/null +++ b/integration/fixtures/wrr.toml @@ -0,0 +1,38 @@ +[global] + checkNewVersion = false + sendAnonymousUsage = false + +[api] + +[log] + level = "DEBUG" + +[entryPoints] + + [entryPoints.web] + address = ":8000" + +[providers.file] + filename = "{{ .SelfFilename }}" + +## dynamic configuration ## + +[http.routers] + [http.routers.router] + service = "wrr" + rule = "Path(`/whoami`)" + +[http.services] + [[http.services.wrr.weighted.services]] + name = "service1" + weight = 3 + [[http.services.wrr.weighted.services]] + name = "service2" + + [http.services.service1.loadBalancer] + [[http.services.service1.loadBalancer.servers]] + url = "{{ .Server1 }}" + [http.services.service2.loadBalancer] + [[http.services.service2.loadBalancer.servers]] + url = "{{ .Server2 }}" + diff --git a/integration/fixtures/wrr_sticky.toml b/integration/fixtures/wrr_sticky.toml new file mode 100644 index 000000000..4181dde54 --- /dev/null +++ b/integration/fixtures/wrr_sticky.toml @@ -0,0 +1,41 @@ +[global] + checkNewVersion = false + sendAnonymousUsage = false + +[api] + +[log] + level = "DEBUG" + +[entryPoints] + + [entryPoints.web] + address = ":8000" + +[providers.file] + filename = "{{ .SelfFilename }}" + +## dynamic configuration ## + +[http.routers] + [http.routers.router] + service = "wrr" + rule = "Path(`/whoami`)" + +[http.services] + [http.services.wrr.weighted.sticky.cookie] + name = "test" + + [[http.services.wrr.weighted.services]] + name = "service1" + weight = 3 + [[http.services.wrr.weighted.services]] + name = "service2" + weight = 1 + + [http.services.service1.loadBalancer] + [[http.services.service1.loadBalancer.servers]] + url = "{{ .Server1 }}" + [http.services.service2.loadBalancer] + [[http.services.service2.loadBalancer.servers]] + url = "{{ .Server2 }}" diff --git a/integration/grpc_test.go b/integration/grpc_test.go index e2d4c63e3..7664c4548 100644 --- a/integration/grpc_test.go +++ b/integration/grpc_test.go @@ -11,9 +11,9 @@ import ( "os" "time" - "github.com/containous/traefik/integration/helloworld" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/integration/helloworld" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/log" "github.com/go-check/check" "google.golang.org/grpc" "google.golang.org/grpc/credentials" diff --git a/integration/headers_test.go b/integration/headers_test.go index 7e0a1422e..8d5194abd 100644 --- a/integration/headers_test.go +++ b/integration/headers_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/healthcheck_test.go b/integration/healthcheck_test.go index 13fc47860..110ba08eb 100644 --- a/integration/healthcheck_test.go +++ b/integration/healthcheck_test.go @@ -6,7 +6,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/hostresolver_test.go b/integration/hostresolver_test.go index 9ff71ad99..c1e58b07d 100644 --- a/integration/hostresolver_test.go +++ b/integration/hostresolver_test.go @@ -4,7 +4,7 @@ import ( "net/http" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/https_test.go b/integration/https_test.go index 5da57cd61..0d35b9570 100644 --- a/integration/https_test.go +++ b/integration/https_test.go @@ -11,9 +11,9 @@ import ( "time" "github.com/BurntSushi/toml" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/config/dynamic" - traefiktls "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/config/dynamic" + traefiktls "github.com/containous/traefik/v2/pkg/tls" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -501,7 +501,21 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) { // TestWithClientCertificateAuthentication // Use two CA:s and test that clients with client signed by either of them can connect func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check.C) { - file := s.adaptFile(c, "fixtures/https/clientca/https_2ca1config.toml", struct{}{}) + server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Write([]byte("server1")) })) + server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Write([]byte("server2")) })) + defer func() { + server1.Close() + server2.Close() + }() + + file := s.adaptFile(c, "fixtures/https/clientca/https_2ca1config.toml", struct { + Server1 string + Server2 string + }{ + Server1: server1.URL, + Server2: server2.URL, + }) + defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) @@ -513,24 +527,32 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) c.Assert(err, checker.IsNil) + req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443", nil) + c.Assert(err, checker.IsNil) + req.Host = "snitest.com" + tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } - // Connection without client certificate should fail - _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server")) - // Connect with client signed by ca1 + client := http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } + + // Connection without client certificate should fail + _, err = client.Do(req) + c.Assert(err, checker.NotNil) + cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server")) - - conn.Close() + // Connect with client signed by ca1 + _, err = client.Do(req) + c.Assert(err, checker.IsNil) // Connect with client signed by ca2 tlsConfig = &tls.Config{ @@ -538,14 +560,19 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check ServerName: "snitest.com", Certificates: []tls.Certificate{}, } + cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server")) + client = http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } - conn.Close() + // Connect with client signed by ca1 + _, err = client.Do(req) + c.Assert(err, checker.IsNil) // Connect with client signed by ca3 should fail tlsConfig = &tls.Config{ @@ -553,18 +580,38 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check ServerName: "snitest.com", Certificates: []tls.Certificate{}, } + cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server")) + client = http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } + + // Connect with client signed by ca1 + _, err = client.Do(req) + c.Assert(err, checker.NotNil) } // TestWithClientCertificateAuthentication // Use two CA:s in two different files and test that clients with client signed by either of them can connect func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleFiles(c *check.C) { - file := s.adaptFile(c, "fixtures/https/clientca/https_2ca2config.toml", struct{}{}) + server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Write([]byte("server1")) })) + server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { rw.Write([]byte("server2")) })) + defer func() { + server1.Close() + server2.Close() + }() + + file := s.adaptFile(c, "fixtures/https/clientca/https_2ca2config.toml", struct { + Server1 string + Server2 string + }{ + Server1: server1.URL, + Server2: server2.URL, + }) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) defer display(c) @@ -576,24 +623,32 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleF err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("Host(`snitest.org`)")) c.Assert(err, checker.IsNil) + req, err := http.NewRequest(http.MethodGet, "https://127.0.0.1:4443", nil) + c.Assert(err, checker.IsNil) + req.Host = "snitest.com" + tlsConfig := &tls.Config{ InsecureSkipVerify: true, ServerName: "snitest.com", Certificates: []tls.Certificate{}, } + + client := http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } + // Connection without client certificate should fail - _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server")) + _, err = client.Do(req) + c.Assert(err, checker.NotNil) // Connect with client signed by ca1 cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server")) - - conn.Close() + _, err = client.Do(req) + c.Assert(err, checker.IsNil) // Connect with client signed by ca2 tlsConfig = &tls.Config{ @@ -601,13 +656,18 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleF ServerName: "snitest.com", Certificates: []tls.Certificate{}, } + cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server")) - conn.Close() + client = http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } + + _, err = client.Do(req) + c.Assert(err, checker.IsNil) // Connect with client signed by ca3 should fail tlsConfig = &tls.Config{ @@ -615,12 +675,18 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleF ServerName: "snitest.com", Certificates: []tls.Certificate{}, } + cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key") c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key")) tlsConfig.Certificates = append(tlsConfig.Certificates, cert) - _, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig) - c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server")) + client = http.Client{ + Transport: &http.Transport{TLSClientConfig: tlsConfig}, + Timeout: 1 * time.Second, + } + + _, err = client.Do(req) + c.Assert(err, checker.NotNil) } func (s *HTTPSSuite) TestWithRootCAsContentForHTTPSOnBackend(c *check.C) { diff --git a/integration/integration_test.go b/integration/integration_test.go index 1ab4da6a8..47f5f0b4f 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -14,7 +14,7 @@ import ( "testing" "text/template" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/fatih/structs" "github.com/go-check/check" compose "github.com/libkermit/compose/check" @@ -27,11 +27,6 @@ var host = flag.Bool("host", false, "run host integration tests") var showLog = flag.Bool("tlog", false, "always show Traefik logs") func Test(t *testing.T) { - check.TestingT(t) -} - -func init() { - flag.Parse() if !*integration { log.Info("Integration tests disabled.") return @@ -54,8 +49,7 @@ func init() { check.Suite(&LogRotationSuite{}) check.Suite(&MarathonSuite{}) check.Suite(&MarathonSuite15{}) - // TODO: disable temporarily - // check.Suite(&RateLimitSuite{}) + check.Suite(&RateLimitSuite{}) check.Suite(&RestSuite{}) check.Suite(&RetrySuite{}) check.Suite(&SimpleSuite{}) @@ -70,6 +64,8 @@ func init() { check.Suite(&ProxyProtocolSuite{}) check.Suite(&TCPSuite{}) } + + check.TestingT(t) } var traefikBinary = "../dist/traefik" @@ -119,17 +115,32 @@ func (s *BaseSuite) traefikCmd(args ...string) (*exec.Cmd, func(*check.C)) { cmd, out := s.cmdTraefik(args...) return cmd, func(c *check.C) { if c.Failed() || *showLog { + s.displayLogK3S(c) s.displayTraefikLog(c, out) } } } +func (s *BaseSuite) displayLogK3S(c *check.C) { + filePath := "./fixtures/k8s/config.skip/k3s.log" + if _, err := os.Stat(filePath); err == nil { + content, errR := ioutil.ReadFile(filePath) + if errR != nil { + log.WithoutContext().Error(errR) + } + log.WithoutContext().Println(string(content)) + } + log.WithoutContext().Println() + log.WithoutContext().Println("################################") + log.WithoutContext().Println() +} + func (s *BaseSuite) displayTraefikLog(c *check.C, output *bytes.Buffer) { if output == nil || output.Len() == 0 { - log.Infof("%s: No Traefik logs.", c.TestName()) + log.WithoutContext().Infof("%s: No Traefik logs.", c.TestName()) } else { - log.Infof("%s: Traefik logs: ", c.TestName()) - log.Infof(output.String()) + log.WithoutContext().Infof("%s: Traefik logs: ", c.TestName()) + log.WithoutContext().Infof(output.String()) } } diff --git a/integration/k8s_test.go b/integration/k8s_test.go index 4bb6cb02d..4a5deddeb 100644 --- a/integration/k8s_test.go +++ b/integration/k8s_test.go @@ -14,8 +14,9 @@ import ( "regexp" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/api" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/api" + "github.com/containous/traefik/v2/pkg/log" "github.com/go-check/check" "github.com/pmezard/go-difflib/difflib" checker "github.com/vdemeester/shakers" @@ -30,7 +31,7 @@ func (s *K8sSuite) SetUpSuite(c *check.C) { s.createComposeProject(c, "k8s") s.composeProject.Start(c) - abs, err := filepath.Abs("./fixtures/k8s/kubeconfig.yaml") + abs, err := filepath.Abs("./fixtures/k8s/config.skip/kubeconfig.yaml") c.Assert(err, checker.IsNil) err = try.Do(60*time.Second, try.DoCondition(func() error { @@ -46,17 +47,19 @@ func (s *K8sSuite) SetUpSuite(c *check.C) { func (s *K8sSuite) TearDownSuite(c *check.C) { s.composeProject.Stop(c) - err := os.Remove("./fixtures/k8s/kubeconfig.yaml") - if err != nil { - c.Log(err) + generatedFiles := []string{ + "./fixtures/k8s/config.skip/kubeconfig.yaml", + "./fixtures/k8s/config.skip/k3s.log", + "./fixtures/k8s/coredns.yaml", + "./fixtures/k8s/rolebindings.yaml", + "./fixtures/k8s/traefik.yaml", } - err = os.Remove("./fixtures/k8s/coredns.yaml") - if err != nil { - c.Log(err) - } - err = os.Remove("./fixtures/k8s/traefik.yaml") - if err != nil { - c.Log(err) + + for _, filename := range generatedFiles { + err := os.Remove(filename) + if err != nil { + log.WithoutContext().Warning(err) + } } } @@ -83,6 +86,9 @@ func (s *K8sSuite) TestCRDConfiguration(c *check.C) { } func testConfiguration(c *check.C, path string) { + err := try.GetRequest("http://127.0.0.1:8080/api/entrypoints", 20*time.Second, try.BodyContains(`"name":"web"`)) + c.Assert(err, checker.IsNil) + expectedJSON := filepath.FromSlash(path) if *updateExpected { @@ -93,7 +99,7 @@ func testConfiguration(c *check.C, path string) { } var buf bytes.Buffer - err := try.GetRequest("http://127.0.0.1:8080/api/rawdata", 20*time.Second, try.StatusCodeIs(http.StatusOK), matchesConfig(expectedJSON, &buf)) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 40*time.Second, try.StatusCodeIs(http.StatusOK), matchesConfig(expectedJSON, &buf)) if !*updateExpected { if err != nil { diff --git a/integration/keepalive_test.go b/integration/keepalive_test.go index 7dad0153b..8e1838974 100644 --- a/integration/keepalive_test.go +++ b/integration/keepalive_test.go @@ -8,7 +8,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/log_rotation_test.go b/integration/log_rotation_test.go index 60b04ad73..d1be2974d 100644 --- a/integration/log_rotation_test.go +++ b/integration/log_rotation_test.go @@ -10,7 +10,7 @@ import ( "syscall" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/marathon15_test.go b/integration/marathon15_test.go index 274170e1d..a15ce8e85 100644 --- a/integration/marathon15_test.go +++ b/integration/marathon15_test.go @@ -6,7 +6,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/gambol99/go-marathon" "github.com/go-check/check" checker "github.com/vdemeester/shakers" diff --git a/integration/marathon_test.go b/integration/marathon_test.go index 67d742993..b0406bf9c 100644 --- a/integration/marathon_test.go +++ b/integration/marathon_test.go @@ -6,7 +6,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/gambol99/go-marathon" "github.com/go-check/check" checker "github.com/vdemeester/shakers" diff --git a/integration/proxy_protocol_test.go b/integration/proxy_protocol_test.go index 66d5c93c5..8533d9719 100644 --- a/integration/proxy_protocol_test.go +++ b/integration/proxy_protocol_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -21,10 +21,11 @@ func (s *ProxyProtocolSuite) TestProxyProtocolTrusted(c *check.C) { gatewayIP := s.composeProject.Container(c, "haproxy").NetworkSettings.Gateway haproxyIP := s.composeProject.Container(c, "haproxy").NetworkSettings.IPAddress whoamiIP := s.composeProject.Container(c, "whoami").NetworkSettings.IPAddress + file := s.adaptFile(c, "fixtures/proxy-protocol/with.toml", struct { HaproxyIP string WhoamiIP string - }{haproxyIP, whoamiIP}) + }{HaproxyIP: haproxyIP, WhoamiIP: whoamiIP}) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) @@ -33,18 +34,43 @@ func (s *ProxyProtocolSuite) TestProxyProtocolTrusted(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://"+haproxyIP+"/whoami", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("X-Forwarded-For: "+gatewayIP)) - display(c) + err = try.GetRequest("http://"+haproxyIP+"/whoami", 500*time.Millisecond, + try.StatusCodeIs(http.StatusOK), + try.BodyContains("X-Forwarded-For: "+gatewayIP)) + c.Assert(err, checker.IsNil) +} + +func (s *ProxyProtocolSuite) TestProxyProtocolV2Trusted(c *check.C) { + gatewayIP := s.composeProject.Container(c, "haproxy").NetworkSettings.Gateway + haproxyIP := s.composeProject.Container(c, "haproxy").NetworkSettings.IPAddress + whoamiIP := s.composeProject.Container(c, "whoami").NetworkSettings.IPAddress + + file := s.adaptFile(c, "fixtures/proxy-protocol/with.toml", struct { + HaproxyIP string + WhoamiIP string + }{HaproxyIP: haproxyIP, WhoamiIP: whoamiIP}) + defer os.Remove(file) + + cmd, display := s.traefikCmd(withConfigFile(file)) + defer display(c) + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://"+haproxyIP+":81/whoami", 500*time.Millisecond, + try.StatusCodeIs(http.StatusOK), + try.BodyContains("X-Forwarded-For: "+gatewayIP)) c.Assert(err, checker.IsNil) } func (s *ProxyProtocolSuite) TestProxyProtocolNotTrusted(c *check.C) { haproxyIP := s.composeProject.Container(c, "haproxy").NetworkSettings.IPAddress whoamiIP := s.composeProject.Container(c, "whoami").NetworkSettings.IPAddress + file := s.adaptFile(c, "fixtures/proxy-protocol/without.toml", struct { HaproxyIP string WhoamiIP string - }{haproxyIP, whoamiIP}) + }{HaproxyIP: haproxyIP, WhoamiIP: whoamiIP}) defer os.Remove(file) cmd, display := s.traefikCmd(withConfigFile(file)) @@ -53,7 +79,30 @@ func (s *ProxyProtocolSuite) TestProxyProtocolNotTrusted(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://"+haproxyIP+"/whoami", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("X-Forwarded-For: "+haproxyIP)) - display(c) + err = try.GetRequest("http://"+haproxyIP+"/whoami", 500*time.Millisecond, + try.StatusCodeIs(http.StatusOK), + try.BodyContains("X-Forwarded-For: "+haproxyIP)) + c.Assert(err, checker.IsNil) +} + +func (s *ProxyProtocolSuite) TestProxyProtocolV2NotTrusted(c *check.C) { + haproxyIP := s.composeProject.Container(c, "haproxy").NetworkSettings.IPAddress + whoamiIP := s.composeProject.Container(c, "whoami").NetworkSettings.IPAddress + + file := s.adaptFile(c, "fixtures/proxy-protocol/without.toml", struct { + HaproxyIP string + WhoamiIP string + }{HaproxyIP: haproxyIP, WhoamiIP: whoamiIP}) + defer os.Remove(file) + + cmd, display := s.traefikCmd(withConfigFile(file)) + defer display(c) + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://"+haproxyIP+":81/whoami", 500*time.Millisecond, + try.StatusCodeIs(http.StatusOK), + try.BodyContains("X-Forwarded-For: "+haproxyIP)) c.Assert(err, checker.IsNil) } diff --git a/integration/ratelimit_test.go b/integration/ratelimit_test.go index 204221b80..32a9c12c3 100644 --- a/integration/ratelimit_test.go +++ b/integration/ratelimit_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -37,29 +37,19 @@ func (s *RateLimitSuite) TestSimpleConfiguration(c *check.C) { err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 1*time.Second, try.BodyContains("ratelimit")) c.Assert(err, checker.IsNil) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) - c.Assert(err, checker.IsNil) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) - c.Assert(err, checker.IsNil) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusTooManyRequests)) - c.Assert(err, checker.IsNil) - - // sleep for 4 seconds to be certain the configured time period has elapsed - // then test another request and verify a 200 status code - time.Sleep(4 * time.Second) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) - c.Assert(err, checker.IsNil) - - // continue requests at 3 second intervals to test the other rate limit time period - time.Sleep(3 * time.Second) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) - c.Assert(err, checker.IsNil) - - time.Sleep(3 * time.Second) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) - c.Assert(err, checker.IsNil) - - time.Sleep(3 * time.Second) - err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusTooManyRequests)) - c.Assert(err, checker.IsNil) + start := time.Now() + count := 0 + for { + err = try.GetRequest("http://127.0.0.1:8081/", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK)) + c.Assert(err, checker.IsNil) + count++ + if count > 100 { + break + } + } + stop := time.Now() + elapsed := stop.Sub(start) + if elapsed < time.Second*99/100 { + c.Fatalf("requests throughput was too fast wrt to rate limiting: 100 requests in %v", elapsed) + } } diff --git a/integration/resources/compose/k8s.yml b/integration/resources/compose/k8s.yml index d457fc333..29e14104b 100644 --- a/integration/resources/compose/k8s.yml +++ b/integration/resources/compose/k8s.yml @@ -1,18 +1,18 @@ server: - image: rancher/k3s:v0.5.0 - command: server --disable-agent --no-deploy traefik + image: rancher/k3s:v0.8.0 + command: server --disable-agent --no-deploy traefik --log /output/k3s.log environment: - K3S_CLUSTER_SECRET=somethingtotallyrandom - K3S_KUBECONFIG_OUTPUT=/output/kubeconfig.yaml - K3S_KUBECONFIG_MODE=666 volumes: - - ../../fixtures/k8s:/output + - ../../fixtures/k8s/config.skip:/output - ../../fixtures/k8s:/var/lib/rancher/k3s/server/manifests ports: - 6443:6443 node: - image: rancher/k3s:v0.5.0 + image: rancher/k3s:v0.8.0 privileged: true links: - server diff --git a/integration/resources/haproxy/haproxy.cfg b/integration/resources/haproxy/haproxy.cfg index de649591c..b7330d9ba 100644 --- a/integration/resources/haproxy/haproxy.cfg +++ b/integration/resources/haproxy/haproxy.cfg @@ -16,6 +16,15 @@ frontend TestServerTest mode tcp default_backend TestServerNodes +frontend TestServerTestV2 + bind 0.0.0.0:81 + mode tcp + default_backend TestServerNodesV2 + backend TestServerNodes mode tcp - server TestServer01 172.17.0.1:8000 send-proxy \ No newline at end of file + server TestServer01 172.17.0.1:8000 send-proxy + + backend TestServerNodesV2 + mode tcp + server TestServer01 172.17.0.1:8000 send-proxy-v2 \ No newline at end of file diff --git a/integration/rest_test.go b/integration/rest_test.go index a5da9df05..692542c9f 100644 --- a/integration/rest_test.go +++ b/integration/rest_test.go @@ -6,8 +6,8 @@ import ( "net/http" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -51,7 +51,7 @@ func (s *RestSuite) TestSimpleConfiguration(c *check.C) { }, Services: map[string]*dynamic.Service{ "service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://" + s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress + ":80", diff --git a/integration/retry_test.go b/integration/retry_test.go index a2d404d16..5b39e2d40 100644 --- a/integration/retry_test.go +++ b/integration/retry_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" "github.com/gorilla/websocket" checker "github.com/vdemeester/shakers" diff --git a/integration/simple_test.go b/integration/simple_test.go index 9ab260eb1..9b40b8b7c 100644 --- a/integration/simple_test.go +++ b/integration/simple_test.go @@ -2,17 +2,20 @@ package integration import ( "bytes" + "context" "encoding/json" "fmt" + "io/ioutil" "net/http" "net/http/httptest" "os" "strings" + "sync/atomic" "syscall" "time" - "github.com/containous/traefik/integration/try" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/integration/try" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -563,7 +566,7 @@ func (s *SimpleSuite) TestServiceConfigErrors(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains(`["the service \"service1@file\" doesn't have any load balancer"]`)) + err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains(`["the service \"service1@file\" does not have any type defined"]`)) c.Assert(err, checker.IsNil) err = try.GetRequest("http://127.0.0.1:8080/api/http/services/service1@file", 1000*time.Millisecond, try.BodyContains(`"status":"disabled"`)) @@ -572,3 +575,209 @@ func (s *SimpleSuite) TestServiceConfigErrors(c *check.C) { err = try.GetRequest("http://127.0.0.1:8080/api/http/services/service2@file", 1000*time.Millisecond, try.BodyContains(`"status":"enabled"`)) c.Assert(err, checker.IsNil) } + +func (s *SimpleSuite) TestWRR(c *check.C) { + s.createComposeProject(c, "base") + s.composeProject.Start(c) + + server1 := s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress + server2 := s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress + + file := s.adaptFile(c, "fixtures/wrr.toml", struct { + Server1 string + Server2 string + }{Server1: "http://" + server1, Server2: "http://" + server2}) + defer os.Remove(file) + + cmd, output := s.traefikCmd(withConfigFile(file)) + defer output(c) + + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains("service1", "service2")) + c.Assert(err, checker.IsNil) + + repartition := map[string]int{} + for i := 0; i < 4; i++ { + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) + c.Assert(err, checker.IsNil) + + response, err := http.DefaultClient.Do(req) + c.Assert(err, checker.IsNil) + c.Assert(response.StatusCode, checker.Equals, http.StatusOK) + + body, err := ioutil.ReadAll(response.Body) + c.Assert(err, checker.IsNil) + + if strings.Contains(string(body), server1) { + repartition[server1]++ + } + if strings.Contains(string(body), server2) { + repartition[server2]++ + } + } + + c.Assert(repartition[server1], checker.Equals, 3) + c.Assert(repartition[server2], checker.Equals, 1) +} + +func (s *SimpleSuite) TestWRRSticky(c *check.C) { + s.createComposeProject(c, "base") + s.composeProject.Start(c) + + server1 := s.composeProject.Container(c, "whoami1").NetworkSettings.IPAddress + server2 := s.composeProject.Container(c, "whoami2").NetworkSettings.IPAddress + + file := s.adaptFile(c, "fixtures/wrr_sticky.toml", struct { + Server1 string + Server2 string + }{Server1: "http://" + server1, Server2: "http://" + server2}) + defer os.Remove(file) + + cmd, output := s.traefikCmd(withConfigFile(file)) + defer output(c) + + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains("service1", "service2")) + c.Assert(err, checker.IsNil) + + repartition := map[string]int{} + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) + c.Assert(err, checker.IsNil) + for i := 0; i < 4; i++ { + + response, err := http.DefaultClient.Do(req) + c.Assert(err, checker.IsNil) + c.Assert(response.StatusCode, checker.Equals, http.StatusOK) + + for _, cookie := range response.Cookies() { + req.AddCookie(cookie) + } + + body, err := ioutil.ReadAll(response.Body) + c.Assert(err, checker.IsNil) + + if strings.Contains(string(body), server1) { + repartition[server1]++ + } + if strings.Contains(string(body), server2) { + repartition[server2]++ + } + } + + c.Assert(repartition[server1], checker.Equals, 4) + c.Assert(repartition[server2], checker.Equals, 0) +} + +func (s *SimpleSuite) TestMirror(c *check.C) { + var count, countMirror1, countMirror2 int32 + + main := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&count, 1) + })) + + mirror1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror1, 1) + })) + + mirror2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror2, 1) + })) + + mainServer := main.URL + mirror1Server := mirror1.URL + mirror2Server := mirror2.URL + + file := s.adaptFile(c, "fixtures/mirror.toml", struct { + MainServer string + Mirror1Server string + Mirror2Server string + }{MainServer: mainServer, Mirror1Server: mirror1Server, Mirror2Server: mirror2Server}) + defer os.Remove(file) + + cmd, output := s.traefikCmd(withConfigFile(file)) + defer output(c) + + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains("mirror1", "mirror2", "service1")) + c.Assert(err, checker.IsNil) + + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) + c.Assert(err, checker.IsNil) + for i := 0; i < 10; i++ { + response, err := http.DefaultClient.Do(req) + c.Assert(err, checker.IsNil) + c.Assert(response.StatusCode, checker.Equals, http.StatusOK) + } + + countTotal := atomic.LoadInt32(&count) + val1 := atomic.LoadInt32(&countMirror1) + val2 := atomic.LoadInt32(&countMirror2) + + c.Assert(countTotal, checker.Equals, int32(10)) + c.Assert(val1, checker.Equals, int32(1)) + c.Assert(val2, checker.Equals, int32(5)) +} + +func (s *SimpleSuite) TestMirrorCanceled(c *check.C) { + var count, countMirror1, countMirror2 int32 + + main := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&count, 1) + time.Sleep(time.Second * 2) + })) + + mirror1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror1, 1) + })) + + mirror2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror2, 1) + })) + + mainServer := main.URL + mirror1Server := mirror1.URL + mirror2Server := mirror2.URL + + file := s.adaptFile(c, "fixtures/mirror.toml", struct { + MainServer string + Mirror1Server string + Mirror2Server string + }{MainServer: mainServer, Mirror1Server: mirror1Server, Mirror2Server: mirror2Server}) + defer os.Remove(file) + + cmd, output := s.traefikCmd(withConfigFile(file)) + defer output(c) + + err := cmd.Start() + c.Assert(err, checker.IsNil) + defer cmd.Process.Kill() + + err = try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains("mirror1", "mirror2", "service1")) + c.Assert(err, checker.IsNil) + + for i := 0; i < 5; i++ { + req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) + c.Assert(err, checker.IsNil) + + newCtx, _ := context.WithTimeout(req.Context(), time.Second) + req = req.WithContext(newCtx) + http.DefaultClient.Do(req) + } + + countTotal := atomic.LoadInt32(&count) + val1 := atomic.LoadInt32(&countMirror1) + val2 := atomic.LoadInt32(&countMirror2) + + c.Assert(countTotal, checker.Equals, int32(5)) + c.Assert(val1, checker.Equals, int32(0)) + c.Assert(val2, checker.Equals, int32(0)) +} diff --git a/integration/tcp_test.go b/integration/tcp_test.go index 095993166..c1fc0d57c 100644 --- a/integration/tcp_test.go +++ b/integration/tcp_test.go @@ -8,7 +8,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) @@ -31,7 +31,7 @@ func (s *TCPSuite) TestMixed(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("Path(`/test`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("Path(`/test`)")) c.Assert(err, checker.IsNil) // Traefik passes through, termination handled by whoami-a @@ -81,7 +81,7 @@ func (s *TCPSuite) TestTLSOptions(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-c.test`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`whoami-c.test`)")) c.Assert(err, checker.IsNil) // Check that we can use a client tls version <= 1.1 with hostSNI 'whoami-c.test' @@ -111,7 +111,7 @@ func (s *TCPSuite) TestNonTLSFallback(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) c.Assert(err, checker.IsNil) // Traefik passes through, termination handled by whoami-a @@ -145,7 +145,7 @@ func (s *TCPSuite) TestNonTlsTcp(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) c.Assert(err, checker.IsNil) // Traefik will forward every requests on the given port to whoami-no-tls @@ -165,7 +165,7 @@ func (s *TCPSuite) TestCatchAllNoTLS(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) c.Assert(err, checker.IsNil) // Traefik will forward every requests on the given port to whoami-no-tls @@ -185,7 +185,7 @@ func (s *TCPSuite) TestCatchAllNoTLSWithHTTPS(c *check.C) { c.Assert(err, checker.IsNil) defer cmd.Process.Kill() - err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 500*time.Millisecond, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) + err = try.GetRequest("http://127.0.0.1:8080/api/rawdata", 5*time.Second, try.StatusCodeIs(http.StatusOK), try.BodyContains("HostSNI(`*`)")) c.Assert(err, checker.IsNil) req := httptest.NewRequest(http.MethodGet, "https://127.0.0.1:8093/test", nil) diff --git a/integration/testdata/rawdata-crd.json b/integration/testdata/rawdata-crd.json index 8600da5de..c26803e36 100644 --- a/integration/testdata/rawdata-crd.json +++ b/integration/testdata/rawdata-crd.json @@ -82,11 +82,11 @@ } }, "tcpRouters": { - "default/test3.crd-673acf455cb2dab0b43a@kubernetescrd": { + "default/test3.route-673acf455cb2dab0b43a@kubernetescrd": { "entryPoints": [ "footcp" ], - "service": "default/test3.crd-673acf455cb2dab0b43a", + "service": "default/test3.route-673acf455cb2dab0b43a", "rule": "HostSNI(`*`)", "tls": { "passthrough": false, @@ -96,7 +96,7 @@ } }, "tcpServices": { - "default/test3.crd-673acf455cb2dab0b43a@kubernetescrd": { + "default/test3.route-673acf455cb2dab0b43a@kubernetescrd": { "loadBalancer": { "servers": [ { @@ -109,7 +109,7 @@ }, "status": "enabled", "usedBy": [ - "default/test3.crd-673acf455cb2dab0b43a@kubernetescrd" + "default/test3.route-673acf455cb2dab0b43a@kubernetescrd" ] } } diff --git a/integration/testdata/rawdata-ingress.json b/integration/testdata/rawdata-ingress.json index 79692c664..9a9e1b9d7 100644 --- a/integration/testdata/rawdata-ingress.json +++ b/integration/testdata/rawdata-ingress.json @@ -1,5 +1,16 @@ { "routers": { + "whoami-test-https/whoami-tls@kubernetes": { + "service": "default/whoami/http", + "rule": "Host(`whoami.test.https`) \u0026\u0026 PathPrefix(`/whoami`)", + "tls": {}, + "status": "enabled" + }, + "whoami-test-https/whoami@kubernetes": { + "service": "default/whoami/http", + "rule": "Host(`whoami.test.https`) \u0026\u0026 PathPrefix(`/whoami`)", + "status": "enabled" + }, "whoami-test/whoami@kubernetes": { "service": "default/whoami/http", "rule": "Host(`whoami.test`) \u0026\u0026 PathPrefix(`/whoami`)", @@ -21,6 +32,8 @@ }, "status": "enabled", "usedBy": [ + "whoami-test-https/whoami-tls@kubernetes", + "whoami-test-https/whoami@kubernetes", "whoami-test/whoami@kubernetes" ], "serverStatus": { diff --git a/integration/timeout_test.go b/integration/timeout_test.go index 43db8761c..2a35ed04a 100644 --- a/integration/timeout_test.go +++ b/integration/timeout_test.go @@ -6,7 +6,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/tls_client_headers_test.go b/integration/tls_client_headers_test.go index f46ed660d..f730ec413 100644 --- a/integration/tls_client_headers_test.go +++ b/integration/tls_client_headers_test.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/tracing_test.go b/integration/tracing_test.go index 2d57b9e38..26cf987f9 100644 --- a/integration/tracing_test.go +++ b/integration/tracing_test.go @@ -5,7 +5,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" checker "github.com/vdemeester/shakers" ) diff --git a/integration/try/try.go b/integration/try/try.go index 60a2764bd..f9f982dbf 100644 --- a/integration/try/try.go +++ b/integration/try/try.go @@ -7,7 +7,7 @@ import ( "os" "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) const ( diff --git a/integration/websocket_test.go b/integration/websocket_test.go index ef83c88bf..e2c834cd4 100644 --- a/integration/websocket_test.go +++ b/integration/websocket_test.go @@ -11,7 +11,7 @@ import ( "os" "time" - "github.com/containous/traefik/integration/try" + "github.com/containous/traefik/v2/integration/try" "github.com/go-check/check" gorillawebsocket "github.com/gorilla/websocket" checker "github.com/vdemeester/shakers" diff --git a/internal/gendoc.go b/internal/gendoc.go index 92405a4d3..1f102082a 100644 --- a/internal/gendoc.go +++ b/internal/gendoc.go @@ -6,12 +6,12 @@ import ( "os" "strings" - "github.com/containous/traefik/pkg/config/env" - "github.com/containous/traefik/pkg/config/flag" - "github.com/containous/traefik/pkg/config/generator" - "github.com/containous/traefik/pkg/config/parser" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/env" + "github.com/containous/traefik/v2/pkg/config/flag" + "github.com/containous/traefik/v2/pkg/config/generator" + "github.com/containous/traefik/v2/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" ) func main() { diff --git a/pkg/anonymize/anonymize.go b/pkg/anonymize/anonymize.go index 7be585ee5..f955985aa 100644 --- a/pkg/anonymize/anonymize.go +++ b/pkg/anonymize/anonymize.go @@ -7,7 +7,7 @@ import ( "regexp" "github.com/mitchellh/copystructure" - "github.com/mvdan/xurls" + "mvdan.cc/xurls/v2" ) const ( @@ -39,7 +39,7 @@ func Do(baseConfig interface{}, indent bool) (string, error) { func doOnJSON(input string) string { mailExp := regexp.MustCompile(`\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3}"`) - return xurls.Relaxed.ReplaceAllString(mailExp.ReplaceAllString(input, maskLarge+"\""), maskLarge) + return xurls.Relaxed().ReplaceAllString(mailExp.ReplaceAllString(input, maskLarge+"\""), maskLarge) } func doOnStruct(field reflect.Value) error { diff --git a/pkg/anonymize/anonymize_config_test.go b/pkg/anonymize/anonymize_config_test.go index 2e0e3d338..6dfd372f7 100644 --- a/pkg/anonymize/anonymize_config_test.go +++ b/pkg/anonymize/anonymize_config_test.go @@ -5,21 +5,21 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/ping" - "github.com/containous/traefik/pkg/provider/acme" - acmeprovider "github.com/containous/traefik/pkg/provider/acme" - "github.com/containous/traefik/pkg/provider/docker" - "github.com/containous/traefik/pkg/provider/file" - "github.com/containous/traefik/pkg/provider/kubernetes/crd" - "github.com/containous/traefik/pkg/provider/kubernetes/ingress" - traefiktls "github.com/containous/traefik/pkg/tls" - "github.com/containous/traefik/pkg/tracing/datadog" - "github.com/containous/traefik/pkg/tracing/haystack" - "github.com/containous/traefik/pkg/tracing/instana" - "github.com/containous/traefik/pkg/tracing/jaeger" - "github.com/containous/traefik/pkg/tracing/zipkin" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/ping" + "github.com/containous/traefik/v2/pkg/provider/acme" + acmeprovider "github.com/containous/traefik/v2/pkg/provider/acme" + "github.com/containous/traefik/v2/pkg/provider/docker" + "github.com/containous/traefik/v2/pkg/provider/file" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/ingress" + traefiktls "github.com/containous/traefik/v2/pkg/tls" + "github.com/containous/traefik/v2/pkg/tracing/datadog" + "github.com/containous/traefik/v2/pkg/tracing/haystack" + "github.com/containous/traefik/v2/pkg/tracing/instana" + "github.com/containous/traefik/v2/pkg/tracing/jaeger" + "github.com/containous/traefik/v2/pkg/tracing/zipkin" + "github.com/containous/traefik/v2/pkg/types" assetfs "github.com/elazarl/go-bindata-assetfs" ) diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index f3c1bd758..001cc83d5 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -3,9 +3,9 @@ package api import ( "net/http" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" assetfs "github.com/elazarl/go-bindata-assetfs" + "github.com/gorilla/mux" ) // DashboardHandler expose dashboard routes diff --git a/pkg/api/debug.go b/pkg/api/debug.go index 35868f3c6..e9c7f8abc 100644 --- a/pkg/api/debug.go +++ b/pkg/api/debug.go @@ -7,7 +7,7 @@ import ( "net/http/pprof" "runtime" - "github.com/containous/mux" + "github.com/gorilla/mux" ) func init() { diff --git a/pkg/api/handler.go b/pkg/api/handler.go index 594e9b46c..7ee900c75 100644 --- a/pkg/api/handler.go +++ b/pkg/api/handler.go @@ -7,12 +7,12 @@ import ( "strconv" "strings" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/version" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/version" assetfs "github.com/elazarl/go-bindata-assetfs" + "github.com/gorilla/mux" ) const ( diff --git a/pkg/api/handler_entrypoint.go b/pkg/api/handler_entrypoint.go index b36dd619c..b4cc3f4e5 100644 --- a/pkg/api/handler_entrypoint.go +++ b/pkg/api/handler_entrypoint.go @@ -6,9 +6,9 @@ import ( "sort" "strconv" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/gorilla/mux" ) type entryPointRepresentation struct { diff --git a/pkg/api/handler_entrypoint_test.go b/pkg/api/handler_entrypoint_test.go index 333fd6c4c..9e796e59d 100644 --- a/pkg/api/handler_entrypoint_test.go +++ b/pkg/api/handler_entrypoint_test.go @@ -9,9 +9,9 @@ import ( "strconv" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/api/handler_http.go b/pkg/api/handler_http.go index d13d92f7a..39bc3fd3f 100644 --- a/pkg/api/handler_http.go +++ b/pkg/api/handler_http.go @@ -6,9 +6,9 @@ import ( "sort" "strconv" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/gorilla/mux" ) type routerRepresentation struct { diff --git a/pkg/api/handler_http_test.go b/pkg/api/handler_http_test.go index 2d04091c7..57524e675 100644 --- a/pkg/api/handler_http_test.go +++ b/pkg/api/handler_http_test.go @@ -9,10 +9,10 @@ import ( "strconv" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -203,7 +203,7 @@ func TestHandler_HTTP(t *testing.T) { "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -219,7 +219,7 @@ func TestHandler_HTTP(t *testing.T) { "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.2", @@ -248,7 +248,7 @@ func TestHandler_HTTP(t *testing.T) { "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -264,7 +264,7 @@ func TestHandler_HTTP(t *testing.T) { "baz@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.2", @@ -280,7 +280,7 @@ func TestHandler_HTTP(t *testing.T) { "test@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.3", @@ -309,7 +309,7 @@ func TestHandler_HTTP(t *testing.T) { "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -337,7 +337,7 @@ func TestHandler_HTTP(t *testing.T) { "bar@myprovider": func() *runtime.ServiceInfo { si := &runtime.ServiceInfo{ Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", diff --git a/pkg/api/handler_overview.go b/pkg/api/handler_overview.go index 9818de22f..f08d80351 100644 --- a/pkg/api/handler_overview.go +++ b/pkg/api/handler_overview.go @@ -5,9 +5,9 @@ import ( "net/http" "reflect" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" ) type schemeOverview struct { diff --git a/pkg/api/handler_overview_test.go b/pkg/api/handler_overview_test.go index 07c9fc05c..e8eaa7c92 100644 --- a/pkg/api/handler_overview_test.go +++ b/pkg/api/handler_overview_test.go @@ -7,19 +7,19 @@ import ( "net/http/httptest" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/provider/docker" - "github.com/containous/traefik/pkg/provider/file" - "github.com/containous/traefik/pkg/provider/kubernetes/crd" - "github.com/containous/traefik/pkg/provider/kubernetes/ingress" - "github.com/containous/traefik/pkg/provider/marathon" - "github.com/containous/traefik/pkg/provider/rancher" - "github.com/containous/traefik/pkg/provider/rest" - "github.com/containous/traefik/pkg/tracing/jaeger" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/provider/docker" + "github.com/containous/traefik/v2/pkg/provider/file" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/ingress" + "github.com/containous/traefik/v2/pkg/provider/marathon" + "github.com/containous/traefik/v2/pkg/provider/rancher" + "github.com/containous/traefik/v2/pkg/provider/rest" + "github.com/containous/traefik/v2/pkg/tracing/jaeger" + "github.com/containous/traefik/v2/pkg/types" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -55,7 +55,7 @@ func TestHandler_Overview(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, @@ -63,7 +63,7 @@ func TestHandler_Overview(t *testing.T) { }, "bar-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, @@ -71,7 +71,7 @@ func TestHandler_Overview(t *testing.T) { }, "fii-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{{URL: "http://127.0.0.1"}}, }, }, diff --git a/pkg/api/handler_tcp.go b/pkg/api/handler_tcp.go index 6dcb0915a..3f91f0386 100644 --- a/pkg/api/handler_tcp.go +++ b/pkg/api/handler_tcp.go @@ -6,9 +6,9 @@ import ( "sort" "strconv" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/gorilla/mux" ) type tcpRouterRepresentation struct { diff --git a/pkg/api/handler_tcp_test.go b/pkg/api/handler_tcp_test.go index 92009abc4..28c833f8b 100644 --- a/pkg/api/handler_tcp_test.go +++ b/pkg/api/handler_tcp_test.go @@ -7,10 +7,10 @@ import ( "net/http/httptest" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/api/handler_test.go b/pkg/api/handler_test.go index 1055eead0..7b506cd6c 100644 --- a/pkg/api/handler_test.go +++ b/pkg/api/handler_test.go @@ -8,10 +8,10 @@ import ( "net/http/httptest" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -37,7 +37,7 @@ func TestHandler_RawData(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", diff --git a/pkg/cli/help.go b/pkg/cli/help.go index 83f3a4935..7926ca7ec 100644 --- a/pkg/cli/help.go +++ b/pkg/cli/help.go @@ -7,9 +7,9 @@ import ( "text/template" "github.com/Masterminds/sprig" - "github.com/containous/traefik/pkg/config/flag" - "github.com/containous/traefik/pkg/config/generator" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/flag" + "github.com/containous/traefik/v2/pkg/config/generator" + "github.com/containous/traefik/v2/pkg/config/parser" ) const tmplHelp = `{{ .Cmd.Name }} {{ .Cmd.Description }} diff --git a/pkg/cli/loader_env.go b/pkg/cli/loader_env.go index 07e40faa4..c622a6821 100644 --- a/pkg/cli/loader_env.go +++ b/pkg/cli/loader_env.go @@ -5,8 +5,8 @@ import ( "os" "strings" - "github.com/containous/traefik/pkg/config/env" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/env" + "github.com/containous/traefik/v2/pkg/log" ) // EnvLoader loads a configuration from all the environment variables prefixed with "TRAEFIK_". diff --git a/pkg/cli/loader_file.go b/pkg/cli/loader_file.go index 2c0a04fe3..eb0b3f78e 100644 --- a/pkg/cli/loader_file.go +++ b/pkg/cli/loader_file.go @@ -5,9 +5,9 @@ import ( "os" "strings" - "github.com/containous/traefik/pkg/config/file" - "github.com/containous/traefik/pkg/config/flag" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/file" + "github.com/containous/traefik/v2/pkg/config/flag" + "github.com/containous/traefik/v2/pkg/log" ) // FileLoader loads a configuration from a file. diff --git a/pkg/cli/loader_flag.go b/pkg/cli/loader_flag.go index fcf2b3076..36ce0b521 100644 --- a/pkg/cli/loader_flag.go +++ b/pkg/cli/loader_flag.go @@ -3,8 +3,8 @@ package cli import ( "fmt" - "github.com/containous/traefik/pkg/config/flag" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/flag" + "github.com/containous/traefik/v2/pkg/log" ) // FlagLoader loads configuration from flags. diff --git a/pkg/collector/collector.go b/pkg/collector/collector.go index 0b41dd0ba..4a1a6f2a5 100644 --- a/pkg/collector/collector.go +++ b/pkg/collector/collector.go @@ -9,10 +9,10 @@ import ( "strconv" "time" - "github.com/containous/traefik/pkg/anonymize" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/version" + "github.com/containous/traefik/v2/pkg/anonymize" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/version" "github.com/mitchellh/hashstructure" ) diff --git a/pkg/config/dynamic/config.go b/pkg/config/dynamic/config.go index 225cd12f1..d41af3c46 100644 --- a/pkg/config/dynamic/config.go +++ b/pkg/config/dynamic/config.go @@ -1,7 +1,7 @@ package dynamic import ( - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/tls" ) // +k8s:deepcopy-gen=true diff --git a/pkg/config/dynamic/fixtures/sample.toml b/pkg/config/dynamic/fixtures/sample.toml index 017d1db0d..a90cee3f6 100644 --- a/pkg/config/dynamic/fixtures/sample.toml +++ b/pkg/config/dynamic/fixtures/sample.toml @@ -295,9 +295,14 @@ key = "foobar" insecureSkipVerify = true [http.middlewares.Middleware16] - [http.middlewares.Middleware16.maxConn] + [http.middlewares.Middleware16.inFlightReq] amount = 42 - extractorFunc = "foobar" + [http.middlewares.Middleware16.inFlightReq.sourceCriterion] + requestHeaderName = "foobar" + requestHost = true + [http.middlewares.Middleware16.inFlightReq.sourceCriterion.ipStrategy] + depth = 42 + excludedIPs = ["foobar", "foobar"] [http.middlewares.Middleware17] [http.middlewares.Middleware17.buffering] maxRequestBodyBytes = 42 @@ -404,8 +409,8 @@ [http.services.Service0] [http.services.Service0.loadBalancer] passHostHeader = true - [http.services.Service0.loadBalancer.stickiness] - cookieName = "foobar" + [http.services.Service0.loadBalancer.sticky.cookie] + name = "foobar" [[http.services.Service0.loadBalancer.servers]] url = "foobar" diff --git a/pkg/config/dynamic/http_config.go b/pkg/config/dynamic/http_config.go index 5356a5503..7fc264018 100644 --- a/pkg/config/dynamic/http_config.go +++ b/pkg/config/dynamic/http_config.go @@ -3,7 +3,7 @@ package dynamic import ( "reflect" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" ) // +k8s:deepcopy-gen=true @@ -19,7 +19,9 @@ type HTTPConfiguration struct { // Service holds a service configuration (can only be of one type at the same time). type Service struct { - LoadBalancer *LoadBalancerService `json:"loadBalancer,omitempty" toml:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty"` + LoadBalancer *ServersLoadBalancer `json:"loadBalancer,omitempty" toml:"loadBalancer,omitempty" yaml:"loadBalancer,omitempty"` + Weighted *WeightedRoundRobin `json:"weighted,omitempty" toml:"weighted,omitempty" yaml:"weighted,omitempty" label:"-"` + Mirroring *Mirroring `json:"mirroring,omitempty" toml:"mirroring,omitempty" yaml:"mirroring,omitempty" label:"-"` } // +k8s:deepcopy-gen=true @@ -45,9 +47,63 @@ type RouterTLSConfig struct { // +k8s:deepcopy-gen=true -// LoadBalancerService holds the LoadBalancerService configuration. -type LoadBalancerService struct { - Stickiness *Stickiness `json:"stickiness,omitempty" toml:"stickiness,omitempty" yaml:"stickiness,omitempty" label:"allowEmpty"` +// Mirroring holds the Mirroring configuration. +type Mirroring struct { + Service string `json:"service,omitempty" toml:"service,omitempty" yaml:"service,omitempty"` + Mirrors []MirrorService `json:"mirrors,omitempty" toml:"mirrors,omitempty" yaml:"mirrors,omitempty"` +} + +// +k8s:deepcopy-gen=true + +// MirrorService holds the MirrorService configuration. +type MirrorService struct { + Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty"` + Percent int `json:"percent,omitempty" toml:"percent,omitempty" yaml:"percent,omitempty"` +} + +// +k8s:deepcopy-gen=true + +// WeightedRoundRobin is a weighted round robin load-balancer of services. +type WeightedRoundRobin struct { + Services []WRRService `json:"services,omitempty" toml:"services,omitempty" yaml:"services,omitempty"` + Sticky *Sticky `json:"sticky,omitempty" toml:"sticky,omitempty" yaml:"sticky,omitempty"` +} + +// +k8s:deepcopy-gen=true + +// WRRService is a reference to a service load-balanced with weighted round robin. +type WRRService struct { + Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty"` + Weight *int `json:"weight,omitempty" toml:"weight,omitempty" yaml:"weight,omitempty"` +} + +// SetDefaults Default values for a ServersLoadBalancer. +func (w *WRRService) SetDefaults() { + defaultWeight := 1 + w.Weight = &defaultWeight +} + +// +k8s:deepcopy-gen=true + +// Sticky holds the sticky configuration. +type Sticky struct { + Cookie *Cookie `json:"cookie,omitempty" toml:"cookie,omitempty" yaml:"cookie,omitempty"` +} + +// +k8s:deepcopy-gen=true + +// Cookie holds the sticky configuration based on cookie. +type Cookie struct { + Name string `json:"name,omitempty" toml:"name,omitempty" yaml:"name,omitempty"` + Secure bool `json:"secure,omitempty" toml:"secure,omitempty" yaml:"secure,omitempty"` + HTTPOnly bool `json:"httpOnly,omitempty" toml:"httpOnly,omitempty" yaml:"httpOnly,omitempty"` +} + +// +k8s:deepcopy-gen=true + +// ServersLoadBalancer holds the ServersLoadBalancer configuration. +type ServersLoadBalancer struct { + Sticky *Sticky `json:"sticky,omitempty" toml:"sticky,omitempty" yaml:"sticky,omitempty" label:"allowEmpty"` Servers []Server `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server"` HealthCheck *HealthCheck `json:"healthCheck,omitempty" toml:"healthCheck,omitempty" yaml:"healthCheck,omitempty"` PassHostHeader bool `json:"passHostHeader" toml:"passHostHeader" yaml:"passHostHeader"` @@ -55,7 +111,7 @@ type LoadBalancerService struct { } // Mergeable tells if the given service is mergeable. -func (l *LoadBalancerService) Mergeable(loadBalancer *LoadBalancerService) bool { +func (l *ServersLoadBalancer) Mergeable(loadBalancer *ServersLoadBalancer) bool { savedServers := l.Servers defer func() { l.Servers = savedServers @@ -71,8 +127,8 @@ func (l *LoadBalancerService) Mergeable(loadBalancer *LoadBalancerService) bool return reflect.DeepEqual(l, loadBalancer) } -// SetDefaults Default values for a LoadBalancerService. -func (l *LoadBalancerService) SetDefaults() { +// SetDefaults Default values for a ServersLoadBalancer. +func (l *ServersLoadBalancer) SetDefaults() { l.PassHostHeader = true } @@ -85,15 +141,6 @@ type ResponseForwarding struct { // +k8s:deepcopy-gen=true -// Stickiness holds the stickiness configuration. -type Stickiness struct { - CookieName string `json:"cookieName,omitempty" toml:"cookieName,omitempty" yaml:"cookieName,omitempty"` - SecureCookie bool `json:"secureCookie,omitempty" toml:"secureCookie,omitempty" yaml:"secureCookie,omitempty"` - HTTPOnlyCookie bool `json:"httpOnlyCookie,omitempty" toml:"httpOnlyCookie,omitempty" yaml:"httpOnlyCookie,omitempty"` -} - -// +k8s:deepcopy-gen=true - // Server holds the server configuration. type Server struct { URL string `json:"url,omitempty" toml:"url,omitempty" yaml:"url,omitempty" label:"-"` diff --git a/pkg/config/dynamic/middlewares.go b/pkg/config/dynamic/middlewares.go index 9d8520e07..b8fb8df27 100644 --- a/pkg/config/dynamic/middlewares.go +++ b/pkg/config/dynamic/middlewares.go @@ -7,31 +7,29 @@ import ( "io/ioutil" "os" - "github.com/containous/traefik/pkg/ip" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/ip" ) // +k8s:deepcopy-gen=true // Middleware holds the Middleware configuration. type Middleware struct { - AddPrefix *AddPrefix `json:"addPrefix,omitempty" toml:"addPrefix,omitempty" yaml:"addPrefix,omitempty"` - StripPrefix *StripPrefix `json:"stripPrefix,omitempty" toml:"stripPrefix,omitempty" yaml:"stripPrefix,omitempty"` - StripPrefixRegex *StripPrefixRegex `json:"stripPrefixRegex,omitempty" toml:"stripPrefixRegex,omitempty" yaml:"stripPrefixRegex,omitempty"` - ReplacePath *ReplacePath `json:"replacePath,omitempty" toml:"replacePath,omitempty" yaml:"replacePath,omitempty"` - ReplacePathRegex *ReplacePathRegex `json:"replacePathRegex,omitempty" toml:"replacePathRegex,omitempty" yaml:"replacePathRegex,omitempty"` - Chain *Chain `json:"chain,omitempty" toml:"chain,omitempty" yaml:"chain,omitempty"` - IPWhiteList *IPWhiteList `json:"ipWhiteList,omitempty" toml:"ipWhiteList,omitempty" yaml:"ipWhiteList,omitempty"` - Headers *Headers `json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty"` - Errors *ErrorPage `json:"errors,omitempty" toml:"errors,omitempty" yaml:"errors,omitempty"` - // TODO: disable temporarily - // RateLimit *RateLimit `json:"rateLimit,omitempty" toml:"rateLimit,omitempty" yaml:"rateLimit,omitempty"` + AddPrefix *AddPrefix `json:"addPrefix,omitempty" toml:"addPrefix,omitempty" yaml:"addPrefix,omitempty"` + StripPrefix *StripPrefix `json:"stripPrefix,omitempty" toml:"stripPrefix,omitempty" yaml:"stripPrefix,omitempty"` + StripPrefixRegex *StripPrefixRegex `json:"stripPrefixRegex,omitempty" toml:"stripPrefixRegex,omitempty" yaml:"stripPrefixRegex,omitempty"` + ReplacePath *ReplacePath `json:"replacePath,omitempty" toml:"replacePath,omitempty" yaml:"replacePath,omitempty"` + ReplacePathRegex *ReplacePathRegex `json:"replacePathRegex,omitempty" toml:"replacePathRegex,omitempty" yaml:"replacePathRegex,omitempty"` + Chain *Chain `json:"chain,omitempty" toml:"chain,omitempty" yaml:"chain,omitempty"` + IPWhiteList *IPWhiteList `json:"ipWhiteList,omitempty" toml:"ipWhiteList,omitempty" yaml:"ipWhiteList,omitempty"` + Headers *Headers `json:"headers,omitempty" toml:"headers,omitempty" yaml:"headers,omitempty"` + Errors *ErrorPage `json:"errors,omitempty" toml:"errors,omitempty" yaml:"errors,omitempty"` + RateLimit *RateLimit `json:"rateLimit,omitempty" toml:"rateLimit,omitempty" yaml:"rateLimit,omitempty"` RedirectRegex *RedirectRegex `json:"redirectRegex,omitempty" toml:"redirectRegex,omitempty" yaml:"redirectRegex,omitempty"` RedirectScheme *RedirectScheme `json:"redirectScheme,omitempty" toml:"redirectScheme,omitempty" yaml:"redirectScheme,omitempty"` BasicAuth *BasicAuth `json:"basicAuth,omitempty" toml:"basicAuth,omitempty" yaml:"basicAuth,omitempty"` DigestAuth *DigestAuth `json:"digestAuth,omitempty" toml:"digestAuth,omitempty" yaml:"digestAuth,omitempty"` ForwardAuth *ForwardAuth `json:"forwardAuth,omitempty" toml:"forwardAuth,omitempty" yaml:"forwardAuth,omitempty"` - MaxConn *MaxConn `json:"maxConn,omitempty" toml:"maxConn,omitempty" yaml:"maxConn,omitempty"` + InFlightReq *InFlightReq `json:"inFlightReq,omitempty" toml:"inFlightReq,omitempty" yaml:"inFlightReq,omitempty"` Buffering *Buffering `json:"buffering,omitempty" toml:"buffering,omitempty" yaml:"buffering,omitempty"` CircuitBreaker *CircuitBreaker `json:"circuitBreaker,omitempty" toml:"circuitBreaker,omitempty" yaml:"circuitBreaker,omitempty"` Compress *Compress `json:"compress,omitempty" toml:"compress,omitempty" yaml:"compress,omitempty" label:"allowEmpty"` @@ -219,10 +217,11 @@ func (h *Headers) HasSecureHeadersDefined() bool { type IPStrategy struct { Depth int `json:"depth,omitempty" toml:"depth,omitempty" yaml:"depth,omitempty" export:"true"` ExcludedIPs []string `json:"excludedIPs,omitempty" toml:"excludedIPs,omitempty" yaml:"excludedIPs,omitempty"` + // TODO(mpl): I think we should make RemoteAddr an explicit field. For one thing, it would yield better documentation. } -// Get an IP selection strategy -// if nil return the RemoteAddr strategy +// Get an IP selection strategy. +// If nil return the RemoteAddr strategy // else return a strategy base on the configuration using the X-Forwarded-For Header. // Depth override the ExcludedIPs func (s *IPStrategy) Get() (ip.Strategy, error) { @@ -259,15 +258,17 @@ type IPWhiteList struct { // +k8s:deepcopy-gen=true -// MaxConn holds maximum connection configuration. -type MaxConn struct { - Amount int64 `json:"amount,omitempty" toml:"amount,omitempty" yaml:"amount,omitempty"` - ExtractorFunc string `json:"extractorFunc,omitempty" toml:"extractorFunc,omitempty" yaml:"extractorFunc,omitempty"` +// InFlightReq limits the number of requests being processed and served concurrently. +type InFlightReq struct { + Amount int64 `json:"amount,omitempty" toml:"amount,omitempty" yaml:"amount,omitempty"` + SourceCriterion *SourceCriterion `json:"sourceCriterion,omitempty" toml:"sourceCriterion,omitempty" yaml:"sourceCriterion,omitempty"` } -// SetDefaults Default values for a MaxConn. -func (m *MaxConn) SetDefaults() { - m.ExtractorFunc = "request.host" +// SetDefaults Default values for a InFlightReq. +func (i *InFlightReq) SetDefaults() { + i.SourceCriterion = &SourceCriterion{ + RequestHost: true, + } } // +k8s:deepcopy-gen=true @@ -280,25 +281,34 @@ type PassTLSClientCert struct { // +k8s:deepcopy-gen=true -// Rate holds the rate limiting configuration for a specific time period. -type Rate struct { - Period types.Duration `json:"period,omitempty" toml:"period,omitempty" yaml:"period,omitempty"` - Average int64 `json:"average,omitempty" toml:"average,omitempty" yaml:"average,omitempty"` - Burst int64 `json:"burst,omitempty" toml:"burst,omitempty" yaml:"burst,omitempty"` +// SourceCriterion defines what criterion is used to group requests as originating from a common source. +// The precedence order is IPStrategy, then RequestHeaderName. +// If none are set, the default is to use the request's remote address field. +type SourceCriterion struct { + IPStrategy *IPStrategy `json:"ipStrategy" toml:"ipStrategy, omitempty"` + RequestHeaderName string `json:"requestHeaderName,omitempty" toml:"requestHeaderName,omitempty" yaml:"requestHeaderName,omitempty"` + RequestHost bool `json:"requestHost,omitempty" toml:"requestHost,omitempty" yaml:"requestHost,omitempty"` } // +k8s:deepcopy-gen=true -// RateLimit holds the rate limiting configuration for a given frontend. +// RateLimit holds the rate limiting configuration for a given router. type RateLimit struct { - RateSet map[string]*Rate `json:"rateSet,omitempty" toml:"rateSet,omitempty" yaml:"rateSet,omitempty"` - // FIXME replace by ipStrategy see oxy and replace - ExtractorFunc string `json:"extractorFunc,omitempty" toml:"extractorFunc,omitempty" yaml:"extractorFunc,omitempty"` + // Average is the maximum rate, in requests/s, allowed for the given source. + // It defaults to 0, which means no rate limiting. + Average int64 `json:"average,omitempty" toml:"average,omitempty" yaml:"average,omitempty"` + // Burst is the maximum number of requests allowed to arrive in the same arbitrarily small period of time. + // It defaults to 1. + Burst int64 `json:"burst,omitempty" toml:"burst,omitempty" yaml:"burst,omitempty"` + SourceCriterion *SourceCriterion `json:"sourceCriterion,omitempty" toml:"sourceCriterion,omitempty" yaml:"sourceCriterion,omitempty"` } -// SetDefaults Default values for a MaxConn. +// SetDefaults sets the default values on a RateLimit. func (r *RateLimit) SetDefaults() { - r.ExtractorFunc = "request.host" + r.Burst = 1 + r.SourceCriterion = &SourceCriterion{ + IPStrategy: &IPStrategy{}, + } } // +k8s:deepcopy-gen=true @@ -398,30 +408,30 @@ type ClientTLS struct { } // CreateTLSConfig creates a TLS config from ClientTLS structures. -func (clientTLS *ClientTLS) CreateTLSConfig() (*tls.Config, error) { - if clientTLS == nil { +func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) { + if c == nil { return nil, nil } var err error caPool := x509.NewCertPool() clientAuth := tls.NoClientCert - if clientTLS.CA != "" { + if c.CA != "" { var ca []byte - if _, errCA := os.Stat(clientTLS.CA); errCA == nil { - ca, err = ioutil.ReadFile(clientTLS.CA) + if _, errCA := os.Stat(c.CA); errCA == nil { + ca, err = ioutil.ReadFile(c.CA) if err != nil { return nil, fmt.Errorf("failed to read CA. %s", err) } } else { - ca = []byte(clientTLS.CA) + ca = []byte(c.CA) } if !caPool.AppendCertsFromPEM(ca) { return nil, fmt.Errorf("failed to parse CA") } - if clientTLS.CAOptional { + if c.CAOptional { clientAuth = tls.VerifyClientCertIfGiven } else { clientAuth = tls.RequireAndVerifyClientCert @@ -429,16 +439,16 @@ func (clientTLS *ClientTLS) CreateTLSConfig() (*tls.Config, error) { } cert := tls.Certificate{} - _, errKeyIsFile := os.Stat(clientTLS.Key) + _, errKeyIsFile := os.Stat(c.Key) - if !clientTLS.InsecureSkipVerify && (len(clientTLS.Cert) == 0 || len(clientTLS.Key) == 0) { + if !c.InsecureSkipVerify && (len(c.Cert) == 0 || len(c.Key) == 0) { return nil, fmt.Errorf("TLS Certificate or Key file must be set when TLS configuration is created") } - if len(clientTLS.Cert) > 0 && len(clientTLS.Key) > 0 { - if _, errCertIsFile := os.Stat(clientTLS.Cert); errCertIsFile == nil { + if len(c.Cert) > 0 && len(c.Key) > 0 { + if _, errCertIsFile := os.Stat(c.Cert); errCertIsFile == nil { if errKeyIsFile == nil { - cert, err = tls.LoadX509KeyPair(clientTLS.Cert, clientTLS.Key) + cert, err = tls.LoadX509KeyPair(c.Cert, c.Key) if err != nil { return nil, fmt.Errorf("failed to load TLS keypair: %v", err) } @@ -447,7 +457,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig() (*tls.Config, error) { } } else { if errKeyIsFile != nil { - cert, err = tls.X509KeyPair([]byte(clientTLS.Cert), []byte(clientTLS.Key)) + cert, err = tls.X509KeyPair([]byte(c.Cert), []byte(c.Key)) if err != nil { return nil, fmt.Errorf("failed to load TLS keypair: %v", err) @@ -461,7 +471,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig() (*tls.Config, error) { return &tls.Config{ Certificates: []tls.Certificate{cert}, RootCAs: caPool, - InsecureSkipVerify: clientTLS.InsecureSkipVerify, + InsecureSkipVerify: c.InsecureSkipVerify, ClientAuth: clientAuth, }, nil } diff --git a/pkg/config/dynamic/tcp_config.go b/pkg/config/dynamic/tcp_config.go index e72c2fd76..e3e42ab68 100644 --- a/pkg/config/dynamic/tcp_config.go +++ b/pkg/config/dynamic/tcp_config.go @@ -3,7 +3,7 @@ package dynamic import ( "reflect" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" ) // +k8s:deepcopy-gen=true @@ -45,7 +45,7 @@ type RouterTCPTLSConfig struct { // TCPLoadBalancerService holds the LoadBalancerService configuration. type TCPLoadBalancerService struct { - Servers []TCPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server" label-slice-as-struct:"server"` + Servers []TCPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server"` } // Mergeable tells if the given service is mergeable. diff --git a/pkg/config/dynamic/zz_generated.deepcopy.go b/pkg/config/dynamic/zz_generated.deepcopy.go index 46b64d071..84aefd044 100644 --- a/pkg/config/dynamic/zz_generated.deepcopy.go +++ b/pkg/config/dynamic/zz_generated.deepcopy.go @@ -29,8 +29,8 @@ THE SOFTWARE. package dynamic import ( - tls "github.com/containous/traefik/pkg/tls" - types "github.com/containous/traefik/pkg/types" + tls "github.com/containous/traefik/v2/pkg/tls" + types "github.com/containous/traefik/v2/pkg/types" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. @@ -247,6 +247,22 @@ func (in Configurations) DeepCopy() Configurations { return *out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Cookie) DeepCopyInto(out *Cookie) { + *out = *in + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Cookie. +func (in *Cookie) DeepCopy() *Cookie { + if in == nil { + return nil + } + out := new(Cookie) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *DigestAuth) DeepCopyInto(out *DigestAuth) { *out = *in @@ -509,53 +525,22 @@ func (in *IPWhiteList) DeepCopy() *IPWhiteList { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *LoadBalancerService) DeepCopyInto(out *LoadBalancerService) { +func (in *InFlightReq) DeepCopyInto(out *InFlightReq) { *out = *in - if in.Stickiness != nil { - in, out := &in.Stickiness, &out.Stickiness - *out = new(Stickiness) - **out = **in - } - if in.Servers != nil { - in, out := &in.Servers, &out.Servers - *out = make([]Server, len(*in)) - copy(*out, *in) - } - if in.HealthCheck != nil { - in, out := &in.HealthCheck, &out.HealthCheck - *out = new(HealthCheck) + if in.SourceCriterion != nil { + in, out := &in.SourceCriterion, &out.SourceCriterion + *out = new(SourceCriterion) (*in).DeepCopyInto(*out) } - if in.ResponseForwarding != nil { - in, out := &in.ResponseForwarding, &out.ResponseForwarding - *out = new(ResponseForwarding) - **out = **in - } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new LoadBalancerService. -func (in *LoadBalancerService) DeepCopy() *LoadBalancerService { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new InFlightReq. +func (in *InFlightReq) DeepCopy() *InFlightReq { if in == nil { return nil } - out := new(LoadBalancerService) - in.DeepCopyInto(out) - return out -} - -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *MaxConn) DeepCopyInto(out *MaxConn) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new MaxConn. -func (in *MaxConn) DeepCopy() *MaxConn { - if in == nil { - return nil - } - out := new(MaxConn) + out := new(InFlightReq) in.DeepCopyInto(out) return out } @@ -629,6 +614,11 @@ func (in *Middleware) DeepCopyInto(out *Middleware) { *out = new(ErrorPage) (*in).DeepCopyInto(*out) } + if in.RateLimit != nil { + in, out := &in.RateLimit, &out.RateLimit + *out = new(RateLimit) + (*in).DeepCopyInto(*out) + } if in.RedirectRegex != nil { in, out := &in.RedirectRegex, &out.RedirectRegex *out = new(RedirectRegex) @@ -654,10 +644,10 @@ func (in *Middleware) DeepCopyInto(out *Middleware) { *out = new(ForwardAuth) (*in).DeepCopyInto(*out) } - if in.MaxConn != nil { - in, out := &in.MaxConn, &out.MaxConn - *out = new(MaxConn) - **out = **in + if in.InFlightReq != nil { + in, out := &in.InFlightReq, &out.InFlightReq + *out = new(InFlightReq) + (*in).DeepCopyInto(*out) } if in.Buffering != nil { in, out := &in.Buffering, &out.Buffering @@ -718,39 +708,13 @@ func (in *PassTLSClientCert) DeepCopy() *PassTLSClientCert { return out } -// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Rate) DeepCopyInto(out *Rate) { - *out = *in - return -} - -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Rate. -func (in *Rate) DeepCopy() *Rate { - if in == nil { - return nil - } - out := new(Rate) - in.DeepCopyInto(out) - return out -} - // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *RateLimit) DeepCopyInto(out *RateLimit) { *out = *in - if in.RateSet != nil { - in, out := &in.RateSet, &out.RateSet - *out = make(map[string]*Rate, len(*in)) - for key, val := range *in { - var outVal *Rate - if val == nil { - (*out)[key] = nil - } else { - in, out := &val, &outVal - *out = new(Rate) - **out = **in - } - (*out)[key] = outVal - } + if in.SourceCriterion != nil { + in, out := &in.SourceCriterion, &out.SourceCriterion + *out = new(SourceCriterion) + (*in).DeepCopyInto(*out) } return } @@ -954,12 +918,53 @@ func (in *Server) DeepCopy() *Server { return out } +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *ServersLoadBalancer) DeepCopyInto(out *ServersLoadBalancer) { + *out = *in + if in.Sticky != nil { + in, out := &in.Sticky, &out.Sticky + *out = new(Sticky) + (*in).DeepCopyInto(*out) + } + if in.Servers != nil { + in, out := &in.Servers, &out.Servers + *out = make([]Server, len(*in)) + copy(*out, *in) + } + if in.HealthCheck != nil { + in, out := &in.HealthCheck, &out.HealthCheck + *out = new(HealthCheck) + (*in).DeepCopyInto(*out) + } + if in.ResponseForwarding != nil { + in, out := &in.ResponseForwarding, &out.ResponseForwarding + *out = new(ResponseForwarding) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ServersLoadBalancer. +func (in *ServersLoadBalancer) DeepCopy() *ServersLoadBalancer { + if in == nil { + return nil + } + out := new(ServersLoadBalancer) + in.DeepCopyInto(out) + return out +} + // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Service) DeepCopyInto(out *Service) { *out = *in if in.LoadBalancer != nil { in, out := &in.LoadBalancer, &out.LoadBalancer - *out = new(LoadBalancerService) + *out = new(ServersLoadBalancer) + (*in).DeepCopyInto(*out) + } + if in.Weighted != nil { + in, out := &in.Weighted, &out.Weighted + *out = new(WeightedRoundRobin) (*in).DeepCopyInto(*out) } return @@ -976,17 +981,43 @@ func (in *Service) DeepCopy() *Service { } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. -func (in *Stickiness) DeepCopyInto(out *Stickiness) { +func (in *SourceCriterion) DeepCopyInto(out *SourceCriterion) { *out = *in + if in.IPStrategy != nil { + in, out := &in.IPStrategy, &out.IPStrategy + *out = new(IPStrategy) + (*in).DeepCopyInto(*out) + } return } -// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Stickiness. -func (in *Stickiness) DeepCopy() *Stickiness { +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new SourceCriterion. +func (in *SourceCriterion) DeepCopy() *SourceCriterion { if in == nil { return nil } - out := new(Stickiness) + out := new(SourceCriterion) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *Sticky) DeepCopyInto(out *Sticky) { + *out = *in + if in.Cookie != nil { + in, out := &in.Cookie, &out.Cookie + *out = new(Cookie) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Sticky. +func (in *Sticky) DeepCopy() *Sticky { + if in == nil { + return nil + } + out := new(Sticky) in.DeepCopyInto(out) return out } @@ -1265,3 +1296,52 @@ func (in Users) DeepCopy() Users { in.DeepCopyInto(out) return *out } + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WRRService) DeepCopyInto(out *WRRService) { + *out = *in + if in.Weight != nil { + in, out := &in.Weight, &out.Weight + *out = new(int) + **out = **in + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WRRService. +func (in *WRRService) DeepCopy() *WRRService { + if in == nil { + return nil + } + out := new(WRRService) + in.DeepCopyInto(out) + return out +} + +// DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. +func (in *WeightedRoundRobin) DeepCopyInto(out *WeightedRoundRobin) { + *out = *in + if in.Services != nil { + in, out := &in.Services, &out.Services + *out = make([]WRRService, len(*in)) + for i := range *in { + (*in)[i].DeepCopyInto(&(*out)[i]) + } + } + if in.Sticky != nil { + in, out := &in.Sticky, &out.Sticky + *out = new(Sticky) + (*in).DeepCopyInto(*out) + } + return +} + +// DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new WeightedRoundRobin. +func (in *WeightedRoundRobin) DeepCopy() *WeightedRoundRobin { + if in == nil { + return nil + } + out := new(WeightedRoundRobin) + in.DeepCopyInto(out) + return out +} diff --git a/pkg/config/env/env.go b/pkg/config/env/env.go index d915272af..5fbd2a877 100644 --- a/pkg/config/env/env.go +++ b/pkg/config/env/env.go @@ -6,7 +6,7 @@ import ( "regexp" "strings" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) // DefaultNamePrefix is the default prefix for environment variable names. diff --git a/pkg/config/env/env_test.go b/pkg/config/env/env_test.go index 9294f4da6..9e399d283 100644 --- a/pkg/config/env/env_test.go +++ b/pkg/config/env/env_test.go @@ -3,8 +3,8 @@ package env import ( "testing" - "github.com/containous/traefik/pkg/config/generator" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/generator" + "github.com/containous/traefik/v2/pkg/config/parser" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/config/env/filter.go b/pkg/config/env/filter.go index 78604bc38..56914d3b7 100644 --- a/pkg/config/env/filter.go +++ b/pkg/config/env/filter.go @@ -4,7 +4,7 @@ import ( "reflect" "strings" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) // FindPrefixedEnvVars finds prefixed environment variables. diff --git a/pkg/config/file/file.go b/pkg/config/file/file.go index 6601669ce..2c0ca10e0 100644 --- a/pkg/config/file/file.go +++ b/pkg/config/file/file.go @@ -2,7 +2,7 @@ package file import ( - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) // Decode decodes the given configuration file into the given element. diff --git a/pkg/config/file/file_node.go b/pkg/config/file/file_node.go index 0c64f6e35..a18a8e8c4 100644 --- a/pkg/config/file/file_node.go +++ b/pkg/config/file/file_node.go @@ -8,7 +8,7 @@ import ( "strings" "github.com/BurntSushi/toml" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" "gopkg.in/yaml.v2" ) diff --git a/pkg/config/file/file_node_test.go b/pkg/config/file/file_node_test.go index affb8513b..1d9db2cde 100644 --- a/pkg/config/file/file_node_test.go +++ b/pkg/config/file/file_node_test.go @@ -3,7 +3,7 @@ package file import ( "testing" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" "github.com/stretchr/testify/assert" ) diff --git a/pkg/config/file/fixtures/sample.toml b/pkg/config/file/fixtures/sample.toml index c0050f7db..920ee573b 100644 --- a/pkg/config/file/fixtures/sample.toml +++ b/pkg/config/file/fixtures/sample.toml @@ -287,9 +287,14 @@ key = "foobar" insecureSkipVerify = true [http.middlewares.Middleware16] - [http.middlewares.Middleware16.maxConn] + [http.middlewares.Middleware16.inFlightReq] amount = 42 - extractorFunc = "foobar" + [http.middlewares.Middleware16.inFlightReq.sourceCriterion] + requestHeaderName = "foobar" + requestHost = true + [http.middlewares.Middleware16.inFlightReq.sourceCriterion.ipStrategy] + depth = 42 + excludedIPs = ["foobar", "foobar"] [http.middlewares.Middleware17] [http.middlewares.Middleware17.buffering] maxRequestBodyBytes = 42 @@ -396,8 +401,8 @@ [http.services.Service0] [http.services.Service0.loadBalancer] passHostHeader = true - [http.services.Service0.loadBalancer.stickiness] - cookieName = "foobar" + [http.services.Service0.loadBalancer.sticky.cookie] + name = "foobar" [[http.services.Service0.loadBalancer.servers]] url = "foobar" diff --git a/pkg/config/file/raw_node.go b/pkg/config/file/raw_node.go index f39499898..135e9cd68 100644 --- a/pkg/config/file/raw_node.go +++ b/pkg/config/file/raw_node.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) func decodeRawToNode(data map[string]interface{}, rootName string, filters ...string) (*parser.Node, error) { diff --git a/pkg/config/file/raw_node_test.go b/pkg/config/file/raw_node_test.go index dd3fea861..cd57c74bd 100644 --- a/pkg/config/file/raw_node_test.go +++ b/pkg/config/file/raw_node_test.go @@ -3,7 +3,7 @@ package file import ( "testing" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/config/flag/flag.go b/pkg/config/flag/flag.go index 91a356f3b..354335647 100644 --- a/pkg/config/flag/flag.go +++ b/pkg/config/flag/flag.go @@ -2,7 +2,7 @@ package flag import ( - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) // Decode decodes the given flag arguments into the given element. diff --git a/pkg/config/flag/flag_test.go b/pkg/config/flag/flag_test.go index 171a3f714..27112020a 100644 --- a/pkg/config/flag/flag_test.go +++ b/pkg/config/flag/flag_test.go @@ -4,9 +4,9 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/generator" - "github.com/containous/traefik/pkg/config/parser" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/generator" + "github.com/containous/traefik/v2/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/config/flag/flagparser.go b/pkg/config/flag/flagparser.go index d28248315..5638e7649 100644 --- a/pkg/config/flag/flagparser.go +++ b/pkg/config/flag/flagparser.go @@ -5,7 +5,7 @@ import ( "reflect" "strings" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) // Parse parses the command-line flag arguments into a map, diff --git a/pkg/config/flag/flagtype.go b/pkg/config/flag/flagtype.go index 93b4fd58d..12abd152d 100644 --- a/pkg/config/flag/flagtype.go +++ b/pkg/config/flag/flagtype.go @@ -4,7 +4,7 @@ import ( "reflect" "strings" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) func getFlagTypes(element interface{}) map[string]reflect.Kind { diff --git a/pkg/config/flag/flagtype_test.go b/pkg/config/flag/flagtype_test.go index 046d25ea4..93dcb6fca 100644 --- a/pkg/config/flag/flagtype_test.go +++ b/pkg/config/flag/flagtype_test.go @@ -4,7 +4,7 @@ import ( "reflect" "testing" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" "github.com/stretchr/testify/assert" ) diff --git a/pkg/config/generator/generator.go b/pkg/config/generator/generator.go index b8956a565..3615169fd 100644 --- a/pkg/config/generator/generator.go +++ b/pkg/config/generator/generator.go @@ -4,7 +4,7 @@ package generator import ( "reflect" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" ) type initializer interface { diff --git a/pkg/config/generator/generator_test.go b/pkg/config/generator/generator_test.go index fbd64a94d..70551db79 100644 --- a/pkg/config/generator/generator_test.go +++ b/pkg/config/generator/generator_test.go @@ -3,7 +3,7 @@ package generator import ( "testing" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/parser" "github.com/stretchr/testify/assert" ) diff --git a/pkg/config/label/label.go b/pkg/config/label/label.go index 09fdfac4e..c3fcc94fd 100644 --- a/pkg/config/label/label.go +++ b/pkg/config/label/label.go @@ -2,8 +2,8 @@ package label import ( - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/parser" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/parser" ) // DecodeConfiguration converts the labels to a configuration. diff --git a/pkg/config/label/label_test.go b/pkg/config/label/label_test.go index f7a305afd..1fedf3046 100644 --- a/pkg/config/label/label_test.go +++ b/pkg/config/label/label_test.go @@ -4,119 +4,120 @@ import ( "fmt" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestDecodeConfiguration(t *testing.T) { labels := map[string]string{ - "traefik.http.middlewares.Middleware0.addprefix.prefix": "foobar", - "traefik.http.middlewares.Middleware1.basicauth.headerfield": "foobar", - "traefik.http.middlewares.Middleware1.basicauth.realm": "foobar", - "traefik.http.middlewares.Middleware1.basicauth.removeheader": "true", - "traefik.http.middlewares.Middleware1.basicauth.users": "foobar, fiibar", - "traefik.http.middlewares.Middleware1.basicauth.usersfile": "foobar", - "traefik.http.middlewares.Middleware2.buffering.maxrequestbodybytes": "42", - "traefik.http.middlewares.Middleware2.buffering.maxresponsebodybytes": "42", - "traefik.http.middlewares.Middleware2.buffering.memrequestbodybytes": "42", - "traefik.http.middlewares.Middleware2.buffering.memresponsebodybytes": "42", - "traefik.http.middlewares.Middleware2.buffering.retryexpression": "foobar", - "traefik.http.middlewares.Middleware3.chain.middlewares": "foobar, fiibar", - "traefik.http.middlewares.Middleware4.circuitbreaker.expression": "foobar", - "traefik.http.middlewares.Middleware5.digestauth.headerfield": "foobar", - "traefik.http.middlewares.Middleware5.digestauth.realm": "foobar", - "traefik.http.middlewares.Middleware5.digestauth.removeheader": "true", - "traefik.http.middlewares.Middleware5.digestauth.users": "foobar, fiibar", - "traefik.http.middlewares.Middleware5.digestauth.usersfile": "foobar", - "traefik.http.middlewares.Middleware6.errors.query": "foobar", - "traefik.http.middlewares.Middleware6.errors.service": "foobar", - "traefik.http.middlewares.Middleware6.errors.status": "foobar, fiibar", - "traefik.http.middlewares.Middleware7.forwardauth.address": "foobar", - "traefik.http.middlewares.Middleware7.forwardauth.authresponseheaders": "foobar, fiibar", - "traefik.http.middlewares.Middleware7.forwardauth.tls.ca": "foobar", - "traefik.http.middlewares.Middleware7.forwardauth.tls.caoptional": "true", - "traefik.http.middlewares.Middleware7.forwardauth.tls.cert": "foobar", - "traefik.http.middlewares.Middleware7.forwardauth.tls.insecureskipverify": "true", - "traefik.http.middlewares.Middleware7.forwardauth.tls.key": "foobar", - "traefik.http.middlewares.Middleware7.forwardauth.trustforwardheader": "true", - "traefik.http.middlewares.Middleware8.headers.accesscontrolallowcredentials": "true", - "traefik.http.middlewares.Middleware8.headers.allowedhosts": "foobar, fiibar", - "traefik.http.middlewares.Middleware8.headers.accesscontrolallowheaders": "X-foobar, X-fiibar", - "traefik.http.middlewares.Middleware8.headers.accesscontrolallowmethods": "GET, PUT", - "traefik.http.middlewares.Middleware8.headers.accesscontrolalloworigin": "foobar", - "traefik.http.middlewares.Middleware8.headers.accesscontrolexposeheaders": "X-foobar, X-fiibar", - "traefik.http.middlewares.Middleware8.headers.accesscontrolmaxage": "200", - "traefik.http.middlewares.Middleware8.headers.addvaryheader": "true", - "traefik.http.middlewares.Middleware8.headers.browserxssfilter": "true", - "traefik.http.middlewares.Middleware8.headers.contentsecuritypolicy": "foobar", - "traefik.http.middlewares.Middleware8.headers.contenttypenosniff": "true", - "traefik.http.middlewares.Middleware8.headers.custombrowserxssvalue": "foobar", - "traefik.http.middlewares.Middleware8.headers.customframeoptionsvalue": "foobar", - "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name0": "foobar", - "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name1": "foobar", - "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name0": "foobar", - "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name1": "foobar", - "traefik.http.middlewares.Middleware8.headers.forcestsheader": "true", - "traefik.http.middlewares.Middleware8.headers.framedeny": "true", - "traefik.http.middlewares.Middleware8.headers.hostsproxyheaders": "foobar, fiibar", - "traefik.http.middlewares.Middleware8.headers.isdevelopment": "true", - "traefik.http.middlewares.Middleware8.headers.publickey": "foobar", - "traefik.http.middlewares.Middleware8.headers.referrerpolicy": "foobar", - "traefik.http.middlewares.Middleware8.headers.featurepolicy": "foobar", - "traefik.http.middlewares.Middleware8.headers.sslforcehost": "true", - "traefik.http.middlewares.Middleware8.headers.sslhost": "foobar", - "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name0": "foobar", - "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name1": "foobar", - "traefik.http.middlewares.Middleware8.headers.sslredirect": "true", - "traefik.http.middlewares.Middleware8.headers.ssltemporaryredirect": "true", - "traefik.http.middlewares.Middleware8.headers.stsincludesubdomains": "true", - "traefik.http.middlewares.Middleware8.headers.stspreload": "true", - "traefik.http.middlewares.Middleware8.headers.stsseconds": "42", - "traefik.http.middlewares.Middleware9.ipwhitelist.ipstrategy.depth": "42", - "traefik.http.middlewares.Middleware9.ipwhitelist.ipstrategy.excludedips": "foobar, fiibar", - "traefik.http.middlewares.Middleware9.ipwhitelist.sourcerange": "foobar, fiibar", - "traefik.http.middlewares.Middleware10.maxconn.amount": "42", - "traefik.http.middlewares.Middleware10.maxconn.extractorfunc": "foobar", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notafter": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notbefore": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.sans": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.commonname": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.country": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.domaincomponent": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.locality": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.organization": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.province": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.serialnumber": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.commonname": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.country": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.domaincomponent": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.locality": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.organization": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.province": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.serialnumber": "true", - "traefik.http.middlewares.Middleware11.passtlsclientcert.pem": "true", - // TODO: disable temporarily (rateLimit) - // "traefik.http.middlewares.Middleware12.ratelimit.extractorfunc": "foobar", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate0.average": "42", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate0.burst": "42", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate0.period": "42", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate1.average": "42", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate1.burst": "42", - // "traefik.http.middlewares.Middleware12.ratelimit.rateset.Rate1.period": "42", - "traefik.http.middlewares.Middleware13.redirectregex.permanent": "true", - "traefik.http.middlewares.Middleware13.redirectregex.regex": "foobar", - "traefik.http.middlewares.Middleware13.redirectregex.replacement": "foobar", - "traefik.http.middlewares.Middleware13b.redirectscheme.scheme": "https", - "traefik.http.middlewares.Middleware13b.redirectscheme.port": "80", - "traefik.http.middlewares.Middleware13b.redirectscheme.permanent": "true", - "traefik.http.middlewares.Middleware14.replacepath.path": "foobar", - "traefik.http.middlewares.Middleware15.replacepathregex.regex": "foobar", - "traefik.http.middlewares.Middleware15.replacepathregex.replacement": "foobar", - "traefik.http.middlewares.Middleware16.retry.attempts": "42", - "traefik.http.middlewares.Middleware17.stripprefix.prefixes": "foobar, fiibar", - "traefik.http.middlewares.Middleware18.stripprefixregex.regex": "foobar, fiibar", - "traefik.http.middlewares.Middleware19.compress": "true", + "traefik.http.middlewares.Middleware0.addprefix.prefix": "foobar", + "traefik.http.middlewares.Middleware1.basicauth.headerfield": "foobar", + "traefik.http.middlewares.Middleware1.basicauth.realm": "foobar", + "traefik.http.middlewares.Middleware1.basicauth.removeheader": "true", + "traefik.http.middlewares.Middleware1.basicauth.users": "foobar, fiibar", + "traefik.http.middlewares.Middleware1.basicauth.usersfile": "foobar", + "traefik.http.middlewares.Middleware2.buffering.maxrequestbodybytes": "42", + "traefik.http.middlewares.Middleware2.buffering.maxresponsebodybytes": "42", + "traefik.http.middlewares.Middleware2.buffering.memrequestbodybytes": "42", + "traefik.http.middlewares.Middleware2.buffering.memresponsebodybytes": "42", + "traefik.http.middlewares.Middleware2.buffering.retryexpression": "foobar", + "traefik.http.middlewares.Middleware3.chain.middlewares": "foobar, fiibar", + "traefik.http.middlewares.Middleware4.circuitbreaker.expression": "foobar", + "traefik.http.middlewares.Middleware5.digestauth.headerfield": "foobar", + "traefik.http.middlewares.Middleware5.digestauth.realm": "foobar", + "traefik.http.middlewares.Middleware5.digestauth.removeheader": "true", + "traefik.http.middlewares.Middleware5.digestauth.users": "foobar, fiibar", + "traefik.http.middlewares.Middleware5.digestauth.usersfile": "foobar", + "traefik.http.middlewares.Middleware6.errors.query": "foobar", + "traefik.http.middlewares.Middleware6.errors.service": "foobar", + "traefik.http.middlewares.Middleware6.errors.status": "foobar, fiibar", + "traefik.http.middlewares.Middleware7.forwardauth.address": "foobar", + "traefik.http.middlewares.Middleware7.forwardauth.authresponseheaders": "foobar, fiibar", + "traefik.http.middlewares.Middleware7.forwardauth.tls.ca": "foobar", + "traefik.http.middlewares.Middleware7.forwardauth.tls.caoptional": "true", + "traefik.http.middlewares.Middleware7.forwardauth.tls.cert": "foobar", + "traefik.http.middlewares.Middleware7.forwardauth.tls.insecureskipverify": "true", + "traefik.http.middlewares.Middleware7.forwardauth.tls.key": "foobar", + "traefik.http.middlewares.Middleware7.forwardauth.trustforwardheader": "true", + "traefik.http.middlewares.Middleware8.headers.accesscontrolallowcredentials": "true", + "traefik.http.middlewares.Middleware8.headers.allowedhosts": "foobar, fiibar", + "traefik.http.middlewares.Middleware8.headers.accesscontrolallowheaders": "X-foobar, X-fiibar", + "traefik.http.middlewares.Middleware8.headers.accesscontrolallowmethods": "GET, PUT", + "traefik.http.middlewares.Middleware8.headers.accesscontrolalloworigin": "foobar", + "traefik.http.middlewares.Middleware8.headers.accesscontrolexposeheaders": "X-foobar, X-fiibar", + "traefik.http.middlewares.Middleware8.headers.accesscontrolmaxage": "200", + "traefik.http.middlewares.Middleware8.headers.addvaryheader": "true", + "traefik.http.middlewares.Middleware8.headers.browserxssfilter": "true", + "traefik.http.middlewares.Middleware8.headers.contentsecuritypolicy": "foobar", + "traefik.http.middlewares.Middleware8.headers.contenttypenosniff": "true", + "traefik.http.middlewares.Middleware8.headers.custombrowserxssvalue": "foobar", + "traefik.http.middlewares.Middleware8.headers.customframeoptionsvalue": "foobar", + "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name0": "foobar", + "traefik.http.middlewares.Middleware8.headers.customrequestheaders.name1": "foobar", + "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name0": "foobar", + "traefik.http.middlewares.Middleware8.headers.customresponseheaders.name1": "foobar", + "traefik.http.middlewares.Middleware8.headers.forcestsheader": "true", + "traefik.http.middlewares.Middleware8.headers.framedeny": "true", + "traefik.http.middlewares.Middleware8.headers.hostsproxyheaders": "foobar, fiibar", + "traefik.http.middlewares.Middleware8.headers.isdevelopment": "true", + "traefik.http.middlewares.Middleware8.headers.publickey": "foobar", + "traefik.http.middlewares.Middleware8.headers.referrerpolicy": "foobar", + "traefik.http.middlewares.Middleware8.headers.featurepolicy": "foobar", + "traefik.http.middlewares.Middleware8.headers.sslforcehost": "true", + "traefik.http.middlewares.Middleware8.headers.sslhost": "foobar", + "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name0": "foobar", + "traefik.http.middlewares.Middleware8.headers.sslproxyheaders.name1": "foobar", + "traefik.http.middlewares.Middleware8.headers.sslredirect": "true", + "traefik.http.middlewares.Middleware8.headers.ssltemporaryredirect": "true", + "traefik.http.middlewares.Middleware8.headers.stsincludesubdomains": "true", + "traefik.http.middlewares.Middleware8.headers.stspreload": "true", + "traefik.http.middlewares.Middleware8.headers.stsseconds": "42", + "traefik.http.middlewares.Middleware9.ipwhitelist.ipstrategy.depth": "42", + "traefik.http.middlewares.Middleware9.ipwhitelist.ipstrategy.excludedips": "foobar, fiibar", + "traefik.http.middlewares.Middleware9.ipwhitelist.sourcerange": "foobar, fiibar", + "traefik.http.middlewares.Middleware10.inflightreq.amount": "42", + "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.ipstrategy.depth": "42", + "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.ipstrategy.excludedips": "foobar, fiibar", + "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.requestheadername": "foobar", + "traefik.http.middlewares.Middleware10.inflightreq.sourcecriterion.requesthost": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notafter": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.notbefore": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.sans": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.commonname": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.country": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.domaincomponent": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.locality": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.organization": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.province": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.subject.serialnumber": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.commonname": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.country": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.domaincomponent": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.locality": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.organization": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.province": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.info.issuer.serialnumber": "true", + "traefik.http.middlewares.Middleware11.passtlsclientcert.pem": "true", + "traefik.http.middlewares.Middleware12.ratelimit.average": "42", + "traefik.http.middlewares.Middleware12.ratelimit.burst": "42", + "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.requestheadername": "foobar", + "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.requesthost": "true", + "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.ipstrategy.depth": "42", + "traefik.http.middlewares.Middleware12.ratelimit.sourcecriterion.ipstrategy.excludedips": "foobar, foobar", + "traefik.http.middlewares.Middleware13.redirectregex.permanent": "true", + "traefik.http.middlewares.Middleware13.redirectregex.regex": "foobar", + "traefik.http.middlewares.Middleware13.redirectregex.replacement": "foobar", + "traefik.http.middlewares.Middleware13b.redirectscheme.scheme": "https", + "traefik.http.middlewares.Middleware13b.redirectscheme.port": "80", + "traefik.http.middlewares.Middleware13b.redirectscheme.permanent": "true", + "traefik.http.middlewares.Middleware14.replacepath.path": "foobar", + "traefik.http.middlewares.Middleware15.replacepathregex.regex": "foobar", + "traefik.http.middlewares.Middleware15.replacepathregex.replacement": "foobar", + "traefik.http.middlewares.Middleware16.retry.attempts": "42", + "traefik.http.middlewares.Middleware17.stripprefix.prefixes": "foobar, fiibar", + "traefik.http.middlewares.Middleware18.stripprefixregex.regex": "foobar, fiibar", + "traefik.http.middlewares.Middleware19.compress": "true", "traefik.http.routers.Router0.entrypoints": "foobar, fiibar", "traefik.http.routers.Router0.middlewares": "foobar, fiibar", @@ -142,8 +143,8 @@ func TestDecodeConfiguration(t *testing.T) { "traefik.http.services.Service0.loadbalancer.responseforwarding.flushinterval": "foobar", "traefik.http.services.Service0.loadbalancer.server.scheme": "foobar", "traefik.http.services.Service0.loadbalancer.server.port": "8080", - "traefik.http.services.Service0.loadbalancer.stickiness.cookiename": "foobar", - "traefik.http.services.Service0.loadbalancer.stickiness.securecookie": "true", + "traefik.http.services.Service0.loadbalancer.sticky.cookie.name": "foobar", + "traefik.http.services.Service0.loadbalancer.sticky.cookie.secure": "true", "traefik.http.services.Service1.loadbalancer.healthcheck.headers.name0": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.headers.name1": "foobar", "traefik.http.services.Service1.loadbalancer.healthcheck.hostname": "foobar", @@ -156,8 +157,8 @@ func TestDecodeConfiguration(t *testing.T) { "traefik.http.services.Service1.loadbalancer.responseforwarding.flushinterval": "foobar", "traefik.http.services.Service1.loadbalancer.server.scheme": "foobar", "traefik.http.services.Service1.loadbalancer.server.port": "8080", - "traefik.http.services.Service1.loadbalancer.stickiness": "false", - "traefik.http.services.Service1.loadbalancer.stickiness.cookiename": "fui", + "traefik.http.services.Service1.loadbalancer.sticky": "false", + "traefik.http.services.Service1.loadbalancer.sticky.cookie.name": "fui", "traefik.tcp.routers.Router0.rule": "foobar", "traefik.tcp.routers.Router0.entrypoints": "foobar, fiibar", "traefik.tcp.routers.Router0.service": "foobar", @@ -273,9 +274,16 @@ func TestDecodeConfiguration(t *testing.T) { }, }, "Middleware10": { - MaxConn: &dynamic.MaxConn{ - Amount: 42, - ExtractorFunc: "foobar", + InFlightReq: &dynamic.InFlightReq{ + Amount: 42, + SourceCriterion: &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{ + Depth: 42, + ExcludedIPs: []string{"foobar", "fiibar"}, + }, + RequestHeaderName: "foobar", + RequestHost: true, + }, }, }, "Middleware11": { @@ -306,24 +314,20 @@ func TestDecodeConfiguration(t *testing.T) { }, }, }, - // TODO: disable temporarily (rateLimit) - // "Middleware12": { - // RateLimit: &dynamic.RateLimit{ - // RateSet: map[string]*dynamic.Rate{ - // "Rate0": { - // Period: types.Duration(42 * time.Second), - // Average: 42, - // Burst: 42, - // }, - // "Rate1": { - // Period: types.Duration(42 * time.Second), - // Average: 42, - // Burst: 42, - // }, - // }, - // ExtractorFunc: "foobar", - // }, - // }, + "Middleware12": { + RateLimit: &dynamic.RateLimit{ + Average: 42, + Burst: 42, + SourceCriterion: &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{ + Depth: 42, + ExcludedIPs: []string{"foobar", "foobar"}, + }, + RequestHeaderName: "foobar", + RequestHost: true, + }, + }, + }, "Middleware13": { RedirectRegex: &dynamic.RedirectRegex{ Regex: "foobar", @@ -510,11 +514,13 @@ func TestDecodeConfiguration(t *testing.T) { }, Services: map[string]*dynamic.Service{ "Service0": { - LoadBalancer: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{ - CookieName: "foobar", - SecureCookie: true, - HTTPOnlyCookie: false, + LoadBalancer: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{ + Cookie: &dynamic.Cookie{ + Name: "foobar", + Secure: true, + HTTPOnly: false, + }, }, Servers: []dynamic.Server{ { @@ -541,7 +547,7 @@ func TestDecodeConfiguration(t *testing.T) { }, }, "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { Scheme: "foobar", @@ -672,9 +678,16 @@ func TestEncodeConfiguration(t *testing.T) { }, }, "Middleware10": { - MaxConn: &dynamic.MaxConn{ - Amount: 42, - ExtractorFunc: "foobar", + InFlightReq: &dynamic.InFlightReq{ + Amount: 42, + SourceCriterion: &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{ + Depth: 42, + ExcludedIPs: []string{"foobar", "fiibar"}, + }, + RequestHeaderName: "foobar", + RequestHost: true, + }, }, }, "Middleware11": { @@ -704,24 +717,20 @@ func TestEncodeConfiguration(t *testing.T) { }, }, }, - // TODO: disable temporarily (rateLimit) - // "Middleware12": { - // RateLimit: &dynamic.RateLimit{ - // RateSet: map[string]*dynamic.Rate{ - // "Rate0": { - // Period: types.Duration(42 * time.Nanosecond), - // Average: 42, - // Burst: 42, - // }, - // "Rate1": { - // Period: types.Duration(42 * time.Nanosecond), - // Average: 42, - // Burst: 42, - // }, - // }, - // ExtractorFunc: "foobar", - // }, - // }, + "Middleware12": { + RateLimit: &dynamic.RateLimit{ + Average: 42, + Burst: 42, + SourceCriterion: &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{ + Depth: 42, + ExcludedIPs: []string{"foobar", "foobar"}, + }, + RequestHeaderName: "foobar", + RequestHost: true, + }, + }, + }, "Middleware13": { RedirectRegex: &dynamic.RedirectRegex{ Regex: "foobar", @@ -908,10 +917,12 @@ func TestEncodeConfiguration(t *testing.T) { }, Services: map[string]*dynamic.Service{ "Service0": { - LoadBalancer: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{ - CookieName: "foobar", - HTTPOnlyCookie: true, + LoadBalancer: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{ + Cookie: &dynamic.Cookie{ + Name: "foobar", + HTTPOnly: true, + }, }, Servers: []dynamic.Server{ { @@ -938,7 +949,7 @@ func TestEncodeConfiguration(t *testing.T) { }, }, "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { Scheme: "foobar", @@ -971,112 +982,113 @@ func TestEncodeConfiguration(t *testing.T) { require.NoError(t, err) expected := map[string]string{ - "traefik.HTTP.Middlewares.Middleware0.AddPrefix.Prefix": "foobar", - "traefik.HTTP.Middlewares.Middleware1.BasicAuth.HeaderField": "foobar", - "traefik.HTTP.Middlewares.Middleware1.BasicAuth.Realm": "foobar", - "traefik.HTTP.Middlewares.Middleware1.BasicAuth.RemoveHeader": "true", - "traefik.HTTP.Middlewares.Middleware1.BasicAuth.Users": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware1.BasicAuth.UsersFile": "foobar", - "traefik.HTTP.Middlewares.Middleware2.Buffering.MaxRequestBodyBytes": "42", - "traefik.HTTP.Middlewares.Middleware2.Buffering.MaxResponseBodyBytes": "42", - "traefik.HTTP.Middlewares.Middleware2.Buffering.MemRequestBodyBytes": "42", - "traefik.HTTP.Middlewares.Middleware2.Buffering.MemResponseBodyBytes": "42", - "traefik.HTTP.Middlewares.Middleware2.Buffering.RetryExpression": "foobar", - "traefik.HTTP.Middlewares.Middleware3.Chain.Middlewares": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware4.CircuitBreaker.Expression": "foobar", - "traefik.HTTP.Middlewares.Middleware5.DigestAuth.HeaderField": "foobar", - "traefik.HTTP.Middlewares.Middleware5.DigestAuth.Realm": "foobar", - "traefik.HTTP.Middlewares.Middleware5.DigestAuth.RemoveHeader": "true", - "traefik.HTTP.Middlewares.Middleware5.DigestAuth.Users": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware5.DigestAuth.UsersFile": "foobar", - "traefik.HTTP.Middlewares.Middleware6.Errors.Query": "foobar", - "traefik.HTTP.Middlewares.Middleware6.Errors.Service": "foobar", - "traefik.HTTP.Middlewares.Middleware6.Errors.Status": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.Address": "foobar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.AuthResponseHeaders": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.CA": "foobar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.CAOptional": "true", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.Cert": "foobar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.InsecureSkipVerify": "true", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.Key": "foobar", - "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TrustForwardHeader": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowCredentials": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowHeaders": "X-foobar, X-fiibar", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowMethods": "GET, PUT", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowOrigin": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlExposeHeaders": "X-foobar, X-fiibar", - "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlMaxAge": "200", - "traefik.HTTP.Middlewares.Middleware8.Headers.AddVaryHeader": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.AllowedHosts": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware8.Headers.BrowserXSSFilter": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.ContentSecurityPolicy": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.ContentTypeNosniff": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomBrowserXSSValue": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomFrameOptionsValue": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomRequestHeaders.name0": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomRequestHeaders.name1": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomResponseHeaders.name0": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.CustomResponseHeaders.name1": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.ForceSTSHeader": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.FrameDeny": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.HostsProxyHeaders": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware8.Headers.IsDevelopment": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.PublicKey": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.ReferrerPolicy": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.FeaturePolicy": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLForceHost": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLHost": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLProxyHeaders.name0": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLProxyHeaders.name1": "foobar", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLRedirect": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.SSLTemporaryRedirect": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.STSIncludeSubdomains": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.STSPreload": "true", - "traefik.HTTP.Middlewares.Middleware8.Headers.STSSeconds": "42", - "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.IPStrategy.Depth": "42", - "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.IPStrategy.ExcludedIPs": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.SourceRange": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware10.MaxConn.Amount": "42", - "traefik.HTTP.Middlewares.Middleware10.MaxConn.ExtractorFunc": "foobar", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.NotAfter": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.NotBefore": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Sans": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Country": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Province": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Locality": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Organization": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.CommonName": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.SerialNumber": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.DomainComponent": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Country": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Province": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Locality": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Organization": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.CommonName": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.SerialNumber": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.DomainComponent": "true", - "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.PEM": "true", - // TODO: disable temporarily (rateLimit) - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.ExtractorFunc": "foobar", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate0.Average": "42", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate0.Burst": "42", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate0.Period": "42", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate1.Average": "42", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate1.Burst": "42", - // "traefik.HTTP.Middlewares.Middleware12.RateLimit.RateSet.Rate1.Period": "42", - "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Regex": "foobar", - "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Replacement": "foobar", - "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Permanent": "true", - "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Scheme": "https", - "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Port": "80", - "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Permanent": "true", - "traefik.HTTP.Middlewares.Middleware14.ReplacePath.Path": "foobar", - "traefik.HTTP.Middlewares.Middleware15.ReplacePathRegex.Regex": "foobar", - "traefik.HTTP.Middlewares.Middleware15.ReplacePathRegex.Replacement": "foobar", - "traefik.HTTP.Middlewares.Middleware16.Retry.Attempts": "42", - "traefik.HTTP.Middlewares.Middleware17.StripPrefix.Prefixes": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware18.StripPrefixRegex.Regex": "foobar, fiibar", - "traefik.HTTP.Middlewares.Middleware19.Compress": "true", + "traefik.HTTP.Middlewares.Middleware0.AddPrefix.Prefix": "foobar", + "traefik.HTTP.Middlewares.Middleware1.BasicAuth.HeaderField": "foobar", + "traefik.HTTP.Middlewares.Middleware1.BasicAuth.Realm": "foobar", + "traefik.HTTP.Middlewares.Middleware1.BasicAuth.RemoveHeader": "true", + "traefik.HTTP.Middlewares.Middleware1.BasicAuth.Users": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware1.BasicAuth.UsersFile": "foobar", + "traefik.HTTP.Middlewares.Middleware2.Buffering.MaxRequestBodyBytes": "42", + "traefik.HTTP.Middlewares.Middleware2.Buffering.MaxResponseBodyBytes": "42", + "traefik.HTTP.Middlewares.Middleware2.Buffering.MemRequestBodyBytes": "42", + "traefik.HTTP.Middlewares.Middleware2.Buffering.MemResponseBodyBytes": "42", + "traefik.HTTP.Middlewares.Middleware2.Buffering.RetryExpression": "foobar", + "traefik.HTTP.Middlewares.Middleware3.Chain.Middlewares": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware4.CircuitBreaker.Expression": "foobar", + "traefik.HTTP.Middlewares.Middleware5.DigestAuth.HeaderField": "foobar", + "traefik.HTTP.Middlewares.Middleware5.DigestAuth.Realm": "foobar", + "traefik.HTTP.Middlewares.Middleware5.DigestAuth.RemoveHeader": "true", + "traefik.HTTP.Middlewares.Middleware5.DigestAuth.Users": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware5.DigestAuth.UsersFile": "foobar", + "traefik.HTTP.Middlewares.Middleware6.Errors.Query": "foobar", + "traefik.HTTP.Middlewares.Middleware6.Errors.Service": "foobar", + "traefik.HTTP.Middlewares.Middleware6.Errors.Status": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.Address": "foobar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.AuthResponseHeaders": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.CA": "foobar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.CAOptional": "true", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.Cert": "foobar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.InsecureSkipVerify": "true", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TLS.Key": "foobar", + "traefik.HTTP.Middlewares.Middleware7.ForwardAuth.TrustForwardHeader": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowCredentials": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowHeaders": "X-foobar, X-fiibar", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowMethods": "GET, PUT", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlAllowOrigin": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlExposeHeaders": "X-foobar, X-fiibar", + "traefik.HTTP.Middlewares.Middleware8.Headers.AccessControlMaxAge": "200", + "traefik.HTTP.Middlewares.Middleware8.Headers.AddVaryHeader": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.AllowedHosts": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware8.Headers.BrowserXSSFilter": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.ContentSecurityPolicy": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.ContentTypeNosniff": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomBrowserXSSValue": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomFrameOptionsValue": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomRequestHeaders.name0": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomRequestHeaders.name1": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomResponseHeaders.name0": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.CustomResponseHeaders.name1": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.ForceSTSHeader": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.FrameDeny": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.HostsProxyHeaders": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware8.Headers.IsDevelopment": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.PublicKey": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.ReferrerPolicy": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.FeaturePolicy": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLForceHost": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLHost": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLProxyHeaders.name0": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLProxyHeaders.name1": "foobar", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLRedirect": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.SSLTemporaryRedirect": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.STSIncludeSubdomains": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.STSPreload": "true", + "traefik.HTTP.Middlewares.Middleware8.Headers.STSSeconds": "42", + "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.IPStrategy.Depth": "42", + "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.IPStrategy.ExcludedIPs": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware9.IPWhiteList.SourceRange": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware10.InFlightReq.Amount": "42", + "traefik.HTTP.Middlewares.Middleware10.InFlightReq.SourceCriterion.IPStrategy.Depth": "42", + "traefik.HTTP.Middlewares.Middleware10.InFlightReq.SourceCriterion.IPStrategy.ExcludedIPs": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware10.InFlightReq.SourceCriterion.RequestHeaderName": "foobar", + "traefik.HTTP.Middlewares.Middleware10.InFlightReq.SourceCriterion.RequestHost": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.NotAfter": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.NotBefore": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Sans": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Country": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Province": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Locality": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.Organization": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.CommonName": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.SerialNumber": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Subject.DomainComponent": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Country": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Province": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Locality": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.Organization": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.CommonName": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.SerialNumber": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.Info.Issuer.DomainComponent": "true", + "traefik.HTTP.Middlewares.Middleware11.PassTLSClientCert.PEM": "true", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.Average": "42", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.Burst": "42", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.SourceCriterion.RequestHeaderName": "foobar", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.SourceCriterion.RequestHost": "true", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.SourceCriterion.IPStrategy.Depth": "42", + "traefik.HTTP.Middlewares.Middleware12.RateLimit.SourceCriterion.IPStrategy.ExcludedIPs": "foobar, foobar", + "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Regex": "foobar", + "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Replacement": "foobar", + "traefik.HTTP.Middlewares.Middleware13.RedirectRegex.Permanent": "true", + "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Scheme": "https", + "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Port": "80", + "traefik.HTTP.Middlewares.Middleware13b.RedirectScheme.Permanent": "true", + "traefik.HTTP.Middlewares.Middleware14.ReplacePath.Path": "foobar", + "traefik.HTTP.Middlewares.Middleware15.ReplacePathRegex.Regex": "foobar", + "traefik.HTTP.Middlewares.Middleware15.ReplacePathRegex.Replacement": "foobar", + "traefik.HTTP.Middlewares.Middleware16.Retry.Attempts": "42", + "traefik.HTTP.Middlewares.Middleware17.StripPrefix.Prefixes": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware18.StripPrefixRegex.Regex": "foobar, fiibar", + "traefik.HTTP.Middlewares.Middleware19.Compress": "true", "traefik.HTTP.Routers.Router0.EntryPoints": "foobar, fiibar", "traefik.HTTP.Routers.Router0.Middlewares": "foobar, fiibar", @@ -1101,9 +1113,9 @@ func TestEncodeConfiguration(t *testing.T) { "traefik.HTTP.Services.Service0.LoadBalancer.ResponseForwarding.FlushInterval": "foobar", "traefik.HTTP.Services.Service0.LoadBalancer.server.Port": "8080", "traefik.HTTP.Services.Service0.LoadBalancer.server.Scheme": "foobar", - "traefik.HTTP.Services.Service0.LoadBalancer.Stickiness.CookieName": "foobar", - "traefik.HTTP.Services.Service0.LoadBalancer.Stickiness.HTTPOnlyCookie": "true", - "traefik.HTTP.Services.Service0.LoadBalancer.Stickiness.SecureCookie": "false", + "traefik.HTTP.Services.Service0.LoadBalancer.Sticky.Cookie.Name": "foobar", + "traefik.HTTP.Services.Service0.LoadBalancer.Sticky.Cookie.HTTPOnly": "true", + "traefik.HTTP.Services.Service0.LoadBalancer.Sticky.Cookie.Secure": "false", "traefik.HTTP.Services.Service1.LoadBalancer.HealthCheck.Headers.name0": "foobar", "traefik.HTTP.Services.Service1.LoadBalancer.HealthCheck.Headers.name1": "foobar", "traefik.HTTP.Services.Service1.LoadBalancer.HealthCheck.Hostname": "foobar", diff --git a/pkg/config/parser/element_fill.go b/pkg/config/parser/element_fill.go index 8b6119b73..0aa0a8bdb 100644 --- a/pkg/config/parser/element_fill.go +++ b/pkg/config/parser/element_fill.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" ) type initializer interface { diff --git a/pkg/config/parser/element_fill_test.go b/pkg/config/parser/element_fill_test.go index db0726c45..664b81bd7 100644 --- a/pkg/config/parser/element_fill_test.go +++ b/pkg/config/parser/element_fill_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/config/parser/flat_encode.go b/pkg/config/parser/flat_encode.go index a18e6daf7..443e7dad1 100644 --- a/pkg/config/parser/flat_encode.go +++ b/pkg/config/parser/flat_encode.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" ) const defaultPtrValue = "false" diff --git a/pkg/config/parser/flat_encode_test.go b/pkg/config/parser/flat_encode_test.go index 665bd894b..69f94f42c 100644 --- a/pkg/config/parser/flat_encode_test.go +++ b/pkg/config/parser/flat_encode_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/config/runtime/runtime.go b/pkg/config/runtime/runtime.go index aac70cc56..b59e768b8 100644 --- a/pkg/config/runtime/runtime.go +++ b/pkg/config/runtime/runtime.go @@ -1,13 +1,11 @@ package runtime import ( - "context" "sort" "strings" - "sync" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" ) // Status of the router/service @@ -171,255 +169,6 @@ func contains(entryPoints []string, entryPointName string) bool { return false } -// GetRoutersByEntryPoints returns all the http routers by entry points name and routers name -func (c *Configuration) GetRoutersByEntryPoints(ctx context.Context, entryPoints []string, tls bool) map[string]map[string]*RouterInfo { - entryPointsRouters := make(map[string]map[string]*RouterInfo) - - for rtName, rt := range c.Routers { - if (tls && rt.TLS == nil) || (!tls && rt.TLS != nil) { - continue - } - - eps := rt.EntryPoints - if len(eps) == 0 { - eps = entryPoints - } - for _, entryPointName := range eps { - if !contains(entryPoints, entryPointName) { - log.FromContext(log.With(ctx, log.Str(log.EntryPointName, entryPointName))). - Errorf("entryPoint %q doesn't exist", entryPointName) - continue - } - - if _, ok := entryPointsRouters[entryPointName]; !ok { - entryPointsRouters[entryPointName] = make(map[string]*RouterInfo) - } - - entryPointsRouters[entryPointName][rtName] = rt - } - } - - return entryPointsRouters -} - -// GetTCPRoutersByEntryPoints returns all the tcp routers by entry points name and routers name -func (c *Configuration) GetTCPRoutersByEntryPoints(ctx context.Context, entryPoints []string) map[string]map[string]*TCPRouterInfo { - entryPointsRouters := make(map[string]map[string]*TCPRouterInfo) - - for rtName, rt := range c.TCPRouters { - eps := rt.EntryPoints - if len(eps) == 0 { - eps = entryPoints - } - - for _, entryPointName := range eps { - if !contains(entryPoints, entryPointName) { - log.FromContext(log.With(ctx, log.Str(log.EntryPointName, entryPointName))). - Errorf("entryPoint %q doesn't exist", entryPointName) - continue - } - - if _, ok := entryPointsRouters[entryPointName]; !ok { - entryPointsRouters[entryPointName] = make(map[string]*TCPRouterInfo) - } - - entryPointsRouters[entryPointName][rtName] = rt - } - } - - return entryPointsRouters -} - -// RouterInfo holds information about a currently running HTTP router -type RouterInfo struct { - *dynamic.Router // dynamic configuration - // Err contains all the errors that occurred during router's creation. - Err []string `json:"error,omitempty"` - // Status reports whether the router is disabled, in a warning state, or all good (enabled). - // If not in "enabled" state, the reason for it should be in the list of Err. - // It is the caller's responsibility to set the initial status. - Status string `json:"status,omitempty"` -} - -// AddError adds err to r.Err, if it does not already exist. -// If critical is set, r is marked as disabled. -func (r *RouterInfo) AddError(err error, critical bool) { - for _, value := range r.Err { - if value == err.Error() { - return - } - } - - r.Err = append(r.Err, err.Error()) - if critical { - r.Status = StatusDisabled - return - } - - // only set it to "warning" if not already in a worse state - if r.Status != StatusDisabled { - r.Status = StatusWarning - } -} - -// TCPRouterInfo holds information about a currently running TCP router -type TCPRouterInfo struct { - *dynamic.TCPRouter // dynamic configuration - Err []string `json:"error,omitempty"` // initialization error - // Status reports whether the router is disabled, in a warning state, or all good (enabled). - // If not in "enabled" state, the reason for it should be in the list of Err. - // It is the caller's responsibility to set the initial status. - Status string `json:"status,omitempty"` -} - -// AddError adds err to r.Err, if it does not already exist. -// If critical is set, r is marked as disabled. -func (r *TCPRouterInfo) AddError(err error, critical bool) { - for _, value := range r.Err { - if value == err.Error() { - return - } - } - - r.Err = append(r.Err, err.Error()) - if critical { - r.Status = StatusDisabled - return - } - - // only set it to "warning" if not already in a worse state - if r.Status != StatusDisabled { - r.Status = StatusWarning - } -} - -// MiddlewareInfo holds information about a currently running middleware -type MiddlewareInfo struct { - *dynamic.Middleware // dynamic configuration - // Err contains all the errors that occurred during service creation. - Err []string `json:"error,omitempty"` - Status string `json:"status,omitempty"` - UsedBy []string `json:"usedBy,omitempty"` // list of routers and services using that middleware -} - -// AddError adds err to s.Err, if it does not already exist. -// If critical is set, m is marked as disabled. -func (m *MiddlewareInfo) AddError(err error, critical bool) { - for _, value := range m.Err { - if value == err.Error() { - return - } - } - - m.Err = append(m.Err, err.Error()) - if critical { - m.Status = StatusDisabled - return - } - - // only set it to "warning" if not already in a worse state - if m.Status != StatusDisabled { - m.Status = StatusWarning - } -} - -// ServiceInfo holds information about a currently running service -type ServiceInfo struct { - *dynamic.Service // dynamic configuration - // Err contains all the errors that occurred during service creation. - Err []string `json:"error,omitempty"` - // Status reports whether the service is disabled, in a warning state, or all good (enabled). - // If not in "enabled" state, the reason for it should be in the list of Err. - // It is the caller's responsibility to set the initial status. - Status string `json:"status,omitempty"` - UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service - - serverStatusMu sync.RWMutex - serverStatus map[string]string // keyed by server URL -} - -// AddError adds err to s.Err, if it does not already exist. -// If critical is set, s is marked as disabled. -func (s *ServiceInfo) AddError(err error, critical bool) { - for _, value := range s.Err { - if value == err.Error() { - return - } - } - - s.Err = append(s.Err, err.Error()) - if critical { - s.Status = StatusDisabled - return - } - - // only set it to "warning" if not already in a worse state - if s.Status != StatusDisabled { - s.Status = StatusWarning - } -} - -// UpdateServerStatus sets the status of the server in the ServiceInfo. -// It is the responsibility of the caller to check that s is not nil. -func (s *ServiceInfo) UpdateServerStatus(server string, status string) { - s.serverStatusMu.Lock() - defer s.serverStatusMu.Unlock() - - if s.serverStatus == nil { - s.serverStatus = make(map[string]string) - } - s.serverStatus[server] = status -} - -// GetAllStatus returns all the statuses of all the servers in ServiceInfo. -// It is the responsibility of the caller to check that s is not nil -func (s *ServiceInfo) GetAllStatus() map[string]string { - s.serverStatusMu.RLock() - defer s.serverStatusMu.RUnlock() - - if len(s.serverStatus) == 0 { - return nil - } - - allStatus := make(map[string]string, len(s.serverStatus)) - for k, v := range s.serverStatus { - allStatus[k] = v - } - return allStatus -} - -// TCPServiceInfo holds information about a currently running TCP service -type TCPServiceInfo struct { - *dynamic.TCPService // dynamic configuration - Err []string `json:"error,omitempty"` // initialization error - // Status reports whether the service is disabled, in a warning state, or all good (enabled). - // If not in "enabled" state, the reason for it should be in the list of Err. - // It is the caller's responsibility to set the initial status. - Status string `json:"status,omitempty"` - UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service -} - -// AddError adds err to s.Err, if it does not already exist. -// If critical is set, s is marked as disabled. -func (s *TCPServiceInfo) AddError(err error, critical bool) { - for _, value := range s.Err { - if value == err.Error() { - return - } - } - - s.Err = append(s.Err, err.Error()) - if critical { - s.Status = StatusDisabled - return - } - - // only set it to "warning" if not already in a worse state - if s.Status != StatusDisabled { - s.Status = StatusWarning - } -} - func getProviderName(elementName string) string { parts := strings.Split(elementName, "@") if len(parts) > 1 { diff --git a/pkg/config/runtime/runtime_http.go b/pkg/config/runtime/runtime_http.go new file mode 100644 index 000000000..1c6b9e4aa --- /dev/null +++ b/pkg/config/runtime/runtime_http.go @@ -0,0 +1,167 @@ +package runtime + +import ( + "context" + "sync" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" +) + +// GetRoutersByEntryPoints returns all the http routers by entry points name and routers name +func (c *Configuration) GetRoutersByEntryPoints(ctx context.Context, entryPoints []string, tls bool) map[string]map[string]*RouterInfo { + entryPointsRouters := make(map[string]map[string]*RouterInfo) + + for rtName, rt := range c.Routers { + if (tls && rt.TLS == nil) || (!tls && rt.TLS != nil) { + continue + } + + eps := rt.EntryPoints + if len(eps) == 0 { + eps = entryPoints + } + for _, entryPointName := range eps { + if !contains(entryPoints, entryPointName) { + log.FromContext(log.With(ctx, log.Str(log.EntryPointName, entryPointName))). + Errorf("entryPoint %q doesn't exist", entryPointName) + continue + } + + if _, ok := entryPointsRouters[entryPointName]; !ok { + entryPointsRouters[entryPointName] = make(map[string]*RouterInfo) + } + + entryPointsRouters[entryPointName][rtName] = rt + } + } + + return entryPointsRouters +} + +// RouterInfo holds information about a currently running HTTP router +type RouterInfo struct { + *dynamic.Router // dynamic configuration + // Err contains all the errors that occurred during router's creation. + Err []string `json:"error,omitempty"` + // Status reports whether the router is disabled, in a warning state, or all good (enabled). + // If not in "enabled" state, the reason for it should be in the list of Err. + // It is the caller's responsibility to set the initial status. + Status string `json:"status,omitempty"` +} + +// AddError adds err to r.Err, if it does not already exist. +// If critical is set, r is marked as disabled. +func (r *RouterInfo) AddError(err error, critical bool) { + for _, value := range r.Err { + if value == err.Error() { + return + } + } + + r.Err = append(r.Err, err.Error()) + if critical { + r.Status = StatusDisabled + return + } + + // only set it to "warning" if not already in a worse state + if r.Status != StatusDisabled { + r.Status = StatusWarning + } +} + +// MiddlewareInfo holds information about a currently running middleware +type MiddlewareInfo struct { + *dynamic.Middleware // dynamic configuration + // Err contains all the errors that occurred during service creation. + Err []string `json:"error,omitempty"` + Status string `json:"status,omitempty"` + UsedBy []string `json:"usedBy,omitempty"` // list of routers and services using that middleware +} + +// AddError adds err to s.Err, if it does not already exist. +// If critical is set, m is marked as disabled. +func (m *MiddlewareInfo) AddError(err error, critical bool) { + for _, value := range m.Err { + if value == err.Error() { + return + } + } + + m.Err = append(m.Err, err.Error()) + if critical { + m.Status = StatusDisabled + return + } + + // only set it to "warning" if not already in a worse state + if m.Status != StatusDisabled { + m.Status = StatusWarning + } +} + +// ServiceInfo holds information about a currently running service +type ServiceInfo struct { + *dynamic.Service // dynamic configuration + // Err contains all the errors that occurred during service creation. + Err []string `json:"error,omitempty"` + // Status reports whether the service is disabled, in a warning state, or all good (enabled). + // If not in "enabled" state, the reason for it should be in the list of Err. + // It is the caller's responsibility to set the initial status. + Status string `json:"status,omitempty"` + UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service + + serverStatusMu sync.RWMutex + serverStatus map[string]string // keyed by server URL +} + +// AddError adds err to s.Err, if it does not already exist. +// If critical is set, s is marked as disabled. +func (s *ServiceInfo) AddError(err error, critical bool) { + for _, value := range s.Err { + if value == err.Error() { + return + } + } + + s.Err = append(s.Err, err.Error()) + if critical { + s.Status = StatusDisabled + return + } + + // only set it to "warning" if not already in a worse state + if s.Status != StatusDisabled { + s.Status = StatusWarning + } +} + +// UpdateServerStatus sets the status of the server in the ServiceInfo. +// It is the responsibility of the caller to check that s is not nil. +func (s *ServiceInfo) UpdateServerStatus(server string, status string) { + s.serverStatusMu.Lock() + defer s.serverStatusMu.Unlock() + + if s.serverStatus == nil { + s.serverStatus = make(map[string]string) + } + s.serverStatus[server] = status +} + +// GetAllStatus returns all the statuses of all the servers in ServiceInfo. +// It is the responsibility of the caller to check that s is not nil +func (s *ServiceInfo) GetAllStatus() map[string]string { + s.serverStatusMu.RLock() + defer s.serverStatusMu.RUnlock() + + if len(s.serverStatus) == 0 { + return nil + } + + allStatus := make(map[string]string, len(s.serverStatus)) + for k, v := range s.serverStatus { + allStatus[k] = v + } + return allStatus +} diff --git a/pkg/config/runtime/runtime_http_test.go b/pkg/config/runtime/runtime_http_test.go new file mode 100644 index 000000000..38102c61d --- /dev/null +++ b/pkg/config/runtime/runtime_http_test.go @@ -0,0 +1,213 @@ +package runtime + +import ( + "context" + "testing" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/stretchr/testify/assert" +) + +func TestGetRoutersByEntryPoints(t *testing.T) { + testCases := []struct { + desc string + conf dynamic.Configuration + entryPoints []string + expected map[string]map[string]*RouterInfo + }{ + { + desc: "Empty Configuration without entrypoint", + conf: dynamic.Configuration{}, + entryPoints: []string{""}, + expected: map[string]map[string]*RouterInfo{}, + }, + { + desc: "Empty Configuration with unknown entrypoints", + conf: dynamic.Configuration{}, + entryPoints: []string{"foo"}, + expected: map[string]map[string]*RouterInfo{}, + }, + { + desc: "Valid configuration with an unknown entrypoint", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + }, + }, + }, + entryPoints: []string{"foo"}, + expected: map[string]map[string]*RouterInfo{}, + }, + { + desc: "Valid configuration with a known entrypoint", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "Host(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "HostSNI(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + }, + }, + }, + entryPoints: []string{"web"}, + expected: map[string]map[string]*RouterInfo{ + "web": { + "foo": { + Router: &dynamic.Router{ + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + Status: "enabled", + }, + "foobar": { + Router: &dynamic.Router{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + }, + }, + { + desc: "Valid configuration with multiple known entrypoints", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "Host(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "HostSNI(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + }, + }, + }, + entryPoints: []string{"web", "webs"}, + expected: map[string]map[string]*RouterInfo{ + "web": { + "foo": { + Router: &dynamic.Router{ + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + Status: "enabled", + }, + "foobar": { + Router: &dynamic.Router{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + "webs": { + "bar": { + Router: &dynamic.Router{ + + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "Host(`foo.bar`)", + }, + Status: "enabled", + }, + "foobar": { + Router: &dynamic.Router{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + }, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + runtimeConfig := NewConfig(test.conf) + actual := runtimeConfig.GetRoutersByEntryPoints(context.Background(), test.entryPoints, false) + assert.Equal(t, test.expected, actual) + }) + } +} diff --git a/pkg/config/runtime/runtime_tcp.go b/pkg/config/runtime/runtime_tcp.go new file mode 100644 index 000000000..a99d519f9 --- /dev/null +++ b/pkg/config/runtime/runtime_tcp.go @@ -0,0 +1,99 @@ +package runtime + +import ( + "context" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" +) + +// GetTCPRoutersByEntryPoints returns all the tcp routers by entry points name and routers name +func (c *Configuration) GetTCPRoutersByEntryPoints(ctx context.Context, entryPoints []string) map[string]map[string]*TCPRouterInfo { + entryPointsRouters := make(map[string]map[string]*TCPRouterInfo) + + for rtName, rt := range c.TCPRouters { + eps := rt.EntryPoints + if len(eps) == 0 { + eps = entryPoints + } + + for _, entryPointName := range eps { + if !contains(entryPoints, entryPointName) { + log.FromContext(log.With(ctx, log.Str(log.EntryPointName, entryPointName))). + Errorf("entryPoint %q doesn't exist", entryPointName) + continue + } + + if _, ok := entryPointsRouters[entryPointName]; !ok { + entryPointsRouters[entryPointName] = make(map[string]*TCPRouterInfo) + } + + entryPointsRouters[entryPointName][rtName] = rt + } + } + + return entryPointsRouters +} + +// TCPRouterInfo holds information about a currently running TCP router +type TCPRouterInfo struct { + *dynamic.TCPRouter // dynamic configuration + Err []string `json:"error,omitempty"` // initialization error + // Status reports whether the router is disabled, in a warning state, or all good (enabled). + // If not in "enabled" state, the reason for it should be in the list of Err. + // It is the caller's responsibility to set the initial status. + Status string `json:"status,omitempty"` +} + +// AddError adds err to r.Err, if it does not already exist. +// If critical is set, r is marked as disabled. +func (r *TCPRouterInfo) AddError(err error, critical bool) { + for _, value := range r.Err { + if value == err.Error() { + return + } + } + + r.Err = append(r.Err, err.Error()) + if critical { + r.Status = StatusDisabled + return + } + + // only set it to "warning" if not already in a worse state + if r.Status != StatusDisabled { + r.Status = StatusWarning + } +} + +// TCPServiceInfo holds information about a currently running TCP service +type TCPServiceInfo struct { + *dynamic.TCPService // dynamic configuration + Err []string `json:"error,omitempty"` // initialization error + // Status reports whether the service is disabled, in a warning state, or all good (enabled). + // If not in "enabled" state, the reason for it should be in the list of Err. + // It is the caller's responsibility to set the initial status. + Status string `json:"status,omitempty"` + UsedBy []string `json:"usedBy,omitempty"` // list of routers using that service +} + +// AddError adds err to s.Err, if it does not already exist. +// If critical is set, s is marked as disabled. +func (s *TCPServiceInfo) AddError(err error, critical bool) { + for _, value := range s.Err { + if value == err.Error() { + return + } + } + + s.Err = append(s.Err, err.Error()) + if critical { + s.Status = StatusDisabled + return + } + + // only set it to "warning" if not already in a worse state + if s.Status != StatusDisabled { + s.Status = StatusWarning + } +} diff --git a/pkg/config/runtime/runtime_tcp_test.go b/pkg/config/runtime/runtime_tcp_test.go new file mode 100644 index 000000000..9fb3f137e --- /dev/null +++ b/pkg/config/runtime/runtime_tcp_test.go @@ -0,0 +1,213 @@ +package runtime + +import ( + "context" + "testing" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/stretchr/testify/assert" +) + +func TestGetTCPRoutersByEntryPoints(t *testing.T) { + testCases := []struct { + desc string + conf dynamic.Configuration + entryPoints []string + expected map[string]map[string]*TCPRouterInfo + }{ + { + desc: "Empty Configuration without entrypoint", + conf: dynamic.Configuration{}, + entryPoints: []string{""}, + expected: map[string]map[string]*TCPRouterInfo{}, + }, + { + desc: "Empty Configuration with unknown entrypoints", + conf: dynamic.Configuration{}, + entryPoints: []string{"foo"}, + expected: map[string]map[string]*TCPRouterInfo{}, + }, + { + desc: "Valid configuration with an unknown entrypoint", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + }, + }, + }, + entryPoints: []string{"foo"}, + expected: map[string]map[string]*TCPRouterInfo{}, + }, + { + desc: "Valid configuration with a known entrypoint", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "Host(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "HostSNI(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + }, + }, + }, + entryPoints: []string{"web"}, + expected: map[string]map[string]*TCPRouterInfo{ + "web": { + "foo": { + TCPRouter: &dynamic.TCPRouter{ + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + Status: "enabled", + }, + "foobar": { + TCPRouter: &dynamic.TCPRouter{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + }, + }, + { + desc: "Valid configuration with multiple known entrypoints", + conf: dynamic.Configuration{ + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "Host(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "Host(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "Host(`bar.foobar`)", + }, + }, + }, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{ + "foo": { + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + "bar": { + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "HostSNI(`foo.bar`)", + }, + "foobar": { + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + }, + }, + }, + entryPoints: []string{"web", "webs"}, + expected: map[string]map[string]*TCPRouterInfo{ + "web": { + "foo": { + TCPRouter: &dynamic.TCPRouter{ + EntryPoints: []string{"web"}, + Service: "foo-service@myprovider", + Rule: "HostSNI(`bar.foo`)", + }, + Status: "enabled", + }, + "foobar": { + TCPRouter: &dynamic.TCPRouter{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + "webs": { + "bar": { + TCPRouter: &dynamic.TCPRouter{ + + EntryPoints: []string{"webs"}, + Service: "bar-service@myprovider", + Rule: "HostSNI(`foo.bar`)", + }, + Status: "enabled", + }, + "foobar": { + TCPRouter: &dynamic.TCPRouter{ + EntryPoints: []string{"web", "webs"}, + Service: "foobar-service@myprovider", + Rule: "HostSNI(`bar.foobar`)", + }, + Status: "enabled", + }, + }, + }, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + runtimeConfig := NewConfig(test.conf) + actual := runtimeConfig.GetTCPRoutersByEntryPoints(context.Background(), test.entryPoints) + assert.Equal(t, test.expected, actual) + }) + } +} diff --git a/pkg/config/runtime/runtime_test.go b/pkg/config/runtime/runtime_test.go index 0d5885f22..b2cbc6238 100644 --- a/pkg/config/runtime/runtime_test.go +++ b/pkg/config/runtime/runtime_test.go @@ -1,11 +1,10 @@ package runtime_test import ( - "context" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -44,7 +43,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ {URL: "http://127.0.0.1:8085"}, {URL: "http://127.0.0.1:8086"}, @@ -76,7 +75,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ {URL: "http://127.0.0.1"}, }, @@ -150,7 +149,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8085", @@ -168,7 +167,7 @@ func TestPopulateUsedBy(t *testing.T) { }, "bar-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8087", @@ -223,7 +222,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -294,7 +293,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -338,7 +337,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -390,7 +389,7 @@ func TestPopulateUsedBy(t *testing.T) { Services: map[string]*runtime.ServiceInfo{ "foo-service@myprovider": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -690,411 +689,3 @@ func TestPopulateUsedBy(t *testing.T) { } } - -func TestGetTCPRoutersByEntryPoints(t *testing.T) { - testCases := []struct { - desc string - conf dynamic.Configuration - entryPoints []string - expected map[string]map[string]*runtime.TCPRouterInfo - }{ - { - desc: "Empty Configuration without entrypoint", - conf: dynamic.Configuration{}, - entryPoints: []string{""}, - expected: map[string]map[string]*runtime.TCPRouterInfo{}, - }, - { - desc: "Empty Configuration with unknown entrypoints", - conf: dynamic.Configuration{}, - entryPoints: []string{"foo"}, - expected: map[string]map[string]*runtime.TCPRouterInfo{}, - }, - { - desc: "Valid configuration with an unknown entrypoint", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - }, - }, - }, - entryPoints: []string{"foo"}, - expected: map[string]map[string]*runtime.TCPRouterInfo{}, - }, - { - desc: "Valid configuration with a known entrypoint", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "Host(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "HostSNI(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - }, - }, - }, - entryPoints: []string{"web"}, - expected: map[string]map[string]*runtime.TCPRouterInfo{ - "web": { - "foo": { - TCPRouter: &dynamic.TCPRouter{ - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - Status: "enabled", - }, - "foobar": { - TCPRouter: &dynamic.TCPRouter{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - }, - }, - { - desc: "Valid configuration with multiple known entrypoints", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "Host(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "HostSNI(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - }, - }, - }, - entryPoints: []string{"web", "webs"}, - expected: map[string]map[string]*runtime.TCPRouterInfo{ - "web": { - "foo": { - TCPRouter: &dynamic.TCPRouter{ - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - Status: "enabled", - }, - "foobar": { - TCPRouter: &dynamic.TCPRouter{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - "webs": { - "bar": { - TCPRouter: &dynamic.TCPRouter{ - - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "HostSNI(`foo.bar`)", - }, - Status: "enabled", - }, - "foobar": { - TCPRouter: &dynamic.TCPRouter{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - runtimeConfig := runtime.NewConfig(test.conf) - actual := runtimeConfig.GetTCPRoutersByEntryPoints(context.Background(), test.entryPoints) - assert.Equal(t, test.expected, actual) - }) - } -} - -func TestGetRoutersByEntryPoints(t *testing.T) { - testCases := []struct { - desc string - conf dynamic.Configuration - entryPoints []string - expected map[string]map[string]*runtime.RouterInfo - }{ - { - desc: "Empty Configuration without entrypoint", - conf: dynamic.Configuration{}, - entryPoints: []string{""}, - expected: map[string]map[string]*runtime.RouterInfo{}, - }, - { - desc: "Empty Configuration with unknown entrypoints", - conf: dynamic.Configuration{}, - entryPoints: []string{"foo"}, - expected: map[string]map[string]*runtime.RouterInfo{}, - }, - { - desc: "Valid configuration with an unknown entrypoint", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - }, - }, - }, - entryPoints: []string{"foo"}, - expected: map[string]map[string]*runtime.RouterInfo{}, - }, - { - desc: "Valid configuration with a known entrypoint", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "Host(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "HostSNI(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - }, - }, - }, - entryPoints: []string{"web"}, - expected: map[string]map[string]*runtime.RouterInfo{ - "web": { - "foo": { - Router: &dynamic.Router{ - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - Status: "enabled", - }, - "foobar": { - Router: &dynamic.Router{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - }, - }, - { - desc: "Valid configuration with multiple known entrypoints", - conf: dynamic.Configuration{ - HTTP: &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "Host(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - }, - }, - TCP: &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{ - "foo": { - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "HostSNI(`bar.foo`)", - }, - "bar": { - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "HostSNI(`foo.bar`)", - }, - "foobar": { - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "HostSNI(`bar.foobar`)", - }, - }, - }, - }, - entryPoints: []string{"web", "webs"}, - expected: map[string]map[string]*runtime.RouterInfo{ - "web": { - "foo": { - Router: &dynamic.Router{ - EntryPoints: []string{"web"}, - Service: "foo-service@myprovider", - Rule: "Host(`bar.foo`)", - }, - Status: "enabled", - }, - "foobar": { - Router: &dynamic.Router{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - "webs": { - "bar": { - Router: &dynamic.Router{ - - EntryPoints: []string{"webs"}, - Service: "bar-service@myprovider", - Rule: "Host(`foo.bar`)", - }, - Status: "enabled", - }, - "foobar": { - Router: &dynamic.Router{ - EntryPoints: []string{"web", "webs"}, - Service: "foobar-service@myprovider", - Rule: "Host(`bar.foobar`)", - }, - Status: "enabled", - }, - }, - }, - }, - } - - for _, test := range testCases { - test := test - t.Run(test.desc, func(t *testing.T) { - t.Parallel() - runtimeConfig := runtime.NewConfig(test.conf) - actual := runtimeConfig.GetRoutersByEntryPoints(context.Background(), test.entryPoints, false) - assert.Equal(t, test.expected, actual) - }) - } -} diff --git a/pkg/config/static/static_config.go b/pkg/config/static/static_config.go index 3b568c458..a701b5e6c 100644 --- a/pkg/config/static/static_config.go +++ b/pkg/config/static/static_config.go @@ -6,25 +6,25 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/ping" - acmeprovider "github.com/containous/traefik/pkg/provider/acme" - "github.com/containous/traefik/pkg/provider/docker" - "github.com/containous/traefik/pkg/provider/file" - "github.com/containous/traefik/pkg/provider/kubernetes/crd" - "github.com/containous/traefik/pkg/provider/kubernetes/ingress" - "github.com/containous/traefik/pkg/provider/marathon" - "github.com/containous/traefik/pkg/provider/rancher" - "github.com/containous/traefik/pkg/provider/rest" - "github.com/containous/traefik/pkg/tls" - "github.com/containous/traefik/pkg/tracing/datadog" - "github.com/containous/traefik/pkg/tracing/haystack" - "github.com/containous/traefik/pkg/tracing/instana" - "github.com/containous/traefik/pkg/tracing/jaeger" - "github.com/containous/traefik/pkg/tracing/zipkin" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/ping" + acmeprovider "github.com/containous/traefik/v2/pkg/provider/acme" + "github.com/containous/traefik/v2/pkg/provider/docker" + "github.com/containous/traefik/v2/pkg/provider/file" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/ingress" + "github.com/containous/traefik/v2/pkg/provider/marathon" + "github.com/containous/traefik/v2/pkg/provider/rancher" + "github.com/containous/traefik/v2/pkg/provider/rest" + "github.com/containous/traefik/v2/pkg/tls" + "github.com/containous/traefik/v2/pkg/tracing/datadog" + "github.com/containous/traefik/v2/pkg/tracing/haystack" + "github.com/containous/traefik/v2/pkg/tracing/instana" + "github.com/containous/traefik/v2/pkg/tracing/jaeger" + "github.com/containous/traefik/v2/pkg/tracing/zipkin" + "github.com/containous/traefik/v2/pkg/types" assetfs "github.com/elazarl/go-bindata-assetfs" - legolog "github.com/go-acme/lego/log" + legolog "github.com/go-acme/lego/v3/log" "github.com/sirupsen/logrus" ) diff --git a/pkg/healthcheck/healthcheck.go b/pkg/healthcheck/healthcheck.go index 1da028d27..0e5ff0de7 100644 --- a/pkg/healthcheck/healthcheck.go +++ b/pkg/healthcheck/healthcheck.go @@ -10,9 +10,9 @@ import ( "sync" "time" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" "github.com/go-kit/kit/metrics" "github.com/vulcand/oxy/roundrobin" ) @@ -56,11 +56,16 @@ func (opt Options) String() string { return fmt.Sprintf("[Hostname: %s Headers: %v Path: %s Port: %d Interval: %s Timeout: %s]", opt.Hostname, opt.Headers, opt.Path, opt.Port, opt.Interval, opt.Timeout) } +type backendURL struct { + url *url.URL + weight int +} + // BackendConfig HealthCheck configuration for a backend type BackendConfig struct { Options name string - disabledURLs []*url.URL + disabledURLs []backendURL } func (b *BackendConfig) newRequest(serverURL *url.URL) (*http.Request, error) { @@ -135,21 +140,22 @@ func (hc *HealthCheck) execute(ctx context.Context, backend *BackendConfig) { func (hc *HealthCheck) checkBackend(backend *BackendConfig) { enabledURLs := backend.LB.Servers() - var newDisabledURLs []*url.URL + var newDisabledURLs []backendURL // FIXME re enable metrics for _, disableURL := range backend.disabledURLs { // FIXME serverUpMetricValue := float64(0) - if err := checkHealth(disableURL, backend); err == nil { - log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q", backend.name, disableURL.String()) - if err = backend.LB.UpsertServer(disableURL, roundrobin.Weight(1)); err != nil { + if err := checkHealth(disableURL.url, backend); err == nil { + log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d", + backend.name, disableURL.url.String(), disableURL.weight) + if err = backend.LB.UpsertServer(disableURL.url, roundrobin.Weight(disableURL.weight)); err != nil { log.Error(err) } // FIXME serverUpMetricValue = 1 } else { - log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.String(), err) + log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.url.String(), err) newDisabledURLs = append(newDisabledURLs, disableURL) } - // FIXME labelValues := []string{"backend", backend.name, "url", disableURL.String()} + // FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()} // FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) } backend.disabledURLs = newDisabledURLs @@ -158,11 +164,20 @@ func (hc *HealthCheck) checkBackend(backend *BackendConfig) { for _, enableURL := range enabledURLs { // FIXME serverUpMetricValue := float64(1) if err := checkHealth(enableURL, backend); err != nil { - log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Reason: %s", backend.name, enableURL.String(), err) + weight := 1 + rr, ok := backend.LB.(*roundrobin.RoundRobin) + if ok { + var gotWeight bool + weight, gotWeight = rr.ServerWeight(enableURL) + if !gotWeight { + weight = 1 + } + } + log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Weight: %d Reason: %s", backend.name, enableURL.String(), weight, err) if err := backend.LB.RemoveServer(enableURL); err != nil { log.Error(err) } - backend.disabledURLs = append(backend.disabledURLs, enableURL) + backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight}) // FIXME serverUpMetricValue = 0 } // FIXME labelValues := []string{"backend", backend.name, "url", enableURL.String()} diff --git a/pkg/healthcheck/healthcheck_test.go b/pkg/healthcheck/healthcheck_test.go index 59fbe8f43..fc9bbd9c1 100644 --- a/pkg/healthcheck/healthcheck_test.go +++ b/pkg/healthcheck/healthcheck_test.go @@ -9,8 +9,8 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vulcand/oxy/roundrobin" @@ -115,7 +115,7 @@ func TestSetBackendsConfiguration(t *testing.T) { if test.startHealthy { lb.servers = append(lb.servers, serverURL) } else { - backend.disabledURLs = append(backend.disabledURLs, serverURL) + backend.disabledURLs = append(backend.disabledURLs, backendURL{url: serverURL, weight: 1}) } collectingMetrics := testhelpers.NewCollectingHealthCheckMetrics() diff --git a/pkg/hostresolver/hostresolver.go b/pkg/hostresolver/hostresolver.go index cbf5f8164..2a7c7dcee 100644 --- a/pkg/hostresolver/hostresolver.go +++ b/pkg/hostresolver/hostresolver.go @@ -7,7 +7,7 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/miekg/dns" "github.com/patrickmn/go-cache" ) diff --git a/pkg/ip/strategy.go b/pkg/ip/strategy.go index dcb9f8b91..260c5021b 100644 --- a/pkg/ip/strategy.go +++ b/pkg/ip/strategy.go @@ -1,6 +1,7 @@ package ip import ( + "net" "net/http" "strings" ) @@ -17,9 +18,13 @@ type Strategy interface { // RemoteAddrStrategy a strategy that always return the remote address type RemoteAddrStrategy struct{} -// GetIP return the selected IP +// GetIP returns the selected IP func (s *RemoteAddrStrategy) GetIP(req *http.Request) string { - return req.RemoteAddr + ip, _, err := net.SplitHostPort(req.RemoteAddr) + if err != nil { + return req.RemoteAddr + } + return ip } // DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left diff --git a/pkg/ip/strategy_test.go b/pkg/ip/strategy_test.go index 54fe64837..8a05acd63 100644 --- a/pkg/ip/strategy_test.go +++ b/pkg/ip/strategy_test.go @@ -16,7 +16,7 @@ func TestRemoteAddrStrategy_GetIP(t *testing.T) { }{ { desc: "Use RemoteAddr", - expected: "192.0.2.1:1234", + expected: "192.0.2.1", }, } diff --git a/pkg/job/job.go b/pkg/job/job.go index 658ed86ae..244e449ed 100644 --- a/pkg/job/job.go +++ b/pkg/job/job.go @@ -3,7 +3,7 @@ package job import ( "time" - "github.com/cenkalti/backoff" + "github.com/cenkalti/backoff/v3" ) var ( diff --git a/pkg/job/job_test.go b/pkg/job/job_test.go index 0f85e45f0..5e3c488e6 100644 --- a/pkg/job/job_test.go +++ b/pkg/job/job_test.go @@ -4,7 +4,7 @@ import ( "testing" "time" - "github.com/cenkalti/backoff" + "github.com/cenkalti/backoff/v3" ) func TestJobBackOff(t *testing.T) { diff --git a/pkg/metrics/datadog.go b/pkg/metrics/datadog.go index f2f9b026d..fcd564461 100644 --- a/pkg/metrics/datadog.go +++ b/pkg/metrics/datadog.go @@ -4,9 +4,9 @@ import ( "context" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" kitlog "github.com/go-kit/kit/log" "github.com/go-kit/kit/metrics/dogstatsd" ) diff --git a/pkg/metrics/datadog_test.go b/pkg/metrics/datadog_test.go index a01252fe4..32e4fc1d7 100644 --- a/pkg/metrics/datadog_test.go +++ b/pkg/metrics/datadog_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stvp/go-udp-testing" ) diff --git a/pkg/metrics/influxdb.go b/pkg/metrics/influxdb.go index eae96d123..3bc859889 100644 --- a/pkg/metrics/influxdb.go +++ b/pkg/metrics/influxdb.go @@ -8,9 +8,9 @@ import ( "regexp" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" kitlog "github.com/go-kit/kit/log" "github.com/go-kit/kit/metrics/influx" influxdb "github.com/influxdata/influxdb1-client/v2" diff --git a/pkg/metrics/influxdb_test.go b/pkg/metrics/influxdb_test.go index 5b72fc632..10df13633 100644 --- a/pkg/metrics/influxdb_test.go +++ b/pkg/metrics/influxdb_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stvp/go-udp-testing" ) diff --git a/pkg/metrics/prometheus.go b/pkg/metrics/prometheus.go index bca770b3c..ffe236b94 100644 --- a/pkg/metrics/prometheus.go +++ b/pkg/metrics/prometheus.go @@ -8,12 +8,12 @@ import ( "strings" "sync" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" "github.com/go-kit/kit/metrics" + "github.com/gorilla/mux" stdprometheus "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" ) diff --git a/pkg/metrics/prometheus_test.go b/pkg/metrics/prometheus_test.go index 36a6fc970..7c0c5ed02 100644 --- a/pkg/metrics/prometheus_test.go +++ b/pkg/metrics/prometheus_test.go @@ -8,9 +8,9 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/dynamic" - th "github.com/containous/traefik/pkg/testhelpers" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + th "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/types" "github.com/prometheus/client_golang/prometheus" dto "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" diff --git a/pkg/metrics/statsd.go b/pkg/metrics/statsd.go index 38147ec2f..8ebf6986e 100644 --- a/pkg/metrics/statsd.go +++ b/pkg/metrics/statsd.go @@ -4,9 +4,9 @@ import ( "context" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" kitlog "github.com/go-kit/kit/log" "github.com/go-kit/kit/metrics/statsd" ) diff --git a/pkg/metrics/statsd_test.go b/pkg/metrics/statsd_test.go index c2c6f2f33..240685d67 100644 --- a/pkg/metrics/statsd_test.go +++ b/pkg/metrics/statsd_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stvp/go-udp-testing" ) diff --git a/pkg/middlewares/accesslog/capture_response_writer.go b/pkg/middlewares/accesslog/capture_response_writer.go index 200db3c12..094b5c922 100644 --- a/pkg/middlewares/accesslog/capture_response_writer.go +++ b/pkg/middlewares/accesslog/capture_response_writer.go @@ -6,7 +6,7 @@ import ( "net" "net/http" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares" ) var ( diff --git a/pkg/middlewares/accesslog/logger.go b/pkg/middlewares/accesslog/logger.go index a07945ed7..4cce7fe06 100644 --- a/pkg/middlewares/accesslog/logger.go +++ b/pkg/middlewares/accesslog/logger.go @@ -13,8 +13,8 @@ import ( "time" "github.com/containous/alice" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/types" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/accesslog/logger_test.go b/pkg/middlewares/accesslog/logger_test.go index db11adb2a..f133ae530 100644 --- a/pkg/middlewares/accesslog/logger_test.go +++ b/pkg/middlewares/accesslog/logger_test.go @@ -14,7 +14,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/addprefix/add_prefix.go b/pkg/middlewares/addprefix/add_prefix.go index c2d44c086..02374ea89 100644 --- a/pkg/middlewares/addprefix/add_prefix.go +++ b/pkg/middlewares/addprefix/add_prefix.go @@ -5,9 +5,9 @@ import ( "fmt" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/addprefix/add_prefix_test.go b/pkg/middlewares/addprefix/add_prefix_test.go index 01d1c16d1..1d130a083 100644 --- a/pkg/middlewares/addprefix/add_prefix_test.go +++ b/pkg/middlewares/addprefix/add_prefix_test.go @@ -5,8 +5,8 @@ import ( "net/http" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/sirupsen/logrus" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/middlewares/auth/basic_auth.go b/pkg/middlewares/auth/basic_auth.go index 62ec3773e..62eca1cb9 100644 --- a/pkg/middlewares/auth/basic_auth.go +++ b/pkg/middlewares/auth/basic_auth.go @@ -8,10 +8,10 @@ import ( "strings" goauth "github.com/abbot/go-http-auth" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/auth/basic_auth_test.go b/pkg/middlewares/auth/basic_auth_test.go index 103fd7771..19e176202 100644 --- a/pkg/middlewares/auth/basic_auth_test.go +++ b/pkg/middlewares/auth/basic_auth_test.go @@ -9,8 +9,8 @@ import ( "os" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/auth/digest_auth.go b/pkg/middlewares/auth/digest_auth.go index 3611b2cd5..25cb29cda 100644 --- a/pkg/middlewares/auth/digest_auth.go +++ b/pkg/middlewares/auth/digest_auth.go @@ -8,10 +8,10 @@ import ( "strings" goauth "github.com/abbot/go-http-auth" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/auth/digest_auth_test.go b/pkg/middlewares/auth/digest_auth_test.go index 7fc16e1f1..0993be036 100644 --- a/pkg/middlewares/auth/digest_auth_test.go +++ b/pkg/middlewares/auth/digest_auth_test.go @@ -9,8 +9,8 @@ import ( "os" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/auth/forward.go b/pkg/middlewares/auth/forward.go index 7e074b29f..85891f76e 100644 --- a/pkg/middlewares/auth/forward.go +++ b/pkg/middlewares/auth/forward.go @@ -9,9 +9,9 @@ import ( "net/http" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/vulcand/oxy/forward" "github.com/vulcand/oxy/utils" diff --git a/pkg/middlewares/auth/forward_test.go b/pkg/middlewares/auth/forward_test.go index 9b698186d..a816fb813 100644 --- a/pkg/middlewares/auth/forward_test.go +++ b/pkg/middlewares/auth/forward_test.go @@ -8,8 +8,8 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/vulcand/oxy/forward" diff --git a/pkg/middlewares/buffering/buffering.go b/pkg/middlewares/buffering/buffering.go index d247b2de2..97fdd1314 100644 --- a/pkg/middlewares/buffering/buffering.go +++ b/pkg/middlewares/buffering/buffering.go @@ -4,9 +4,9 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" oxybuffer "github.com/vulcand/oxy/buffer" ) diff --git a/pkg/middlewares/chain/chain.go b/pkg/middlewares/chain/chain.go index 914766a9d..ee3668bbd 100644 --- a/pkg/middlewares/chain/chain.go +++ b/pkg/middlewares/chain/chain.go @@ -5,8 +5,8 @@ import ( "net/http" "github.com/containous/alice" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" ) const ( diff --git a/pkg/middlewares/circuitbreaker/circuit_breaker.go b/pkg/middlewares/circuitbreaker/circuit_breaker.go index cb57b8894..dc561b465 100644 --- a/pkg/middlewares/circuitbreaker/circuit_breaker.go +++ b/pkg/middlewares/circuitbreaker/circuit_breaker.go @@ -4,10 +4,10 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/vulcand/oxy/cbreaker" ) diff --git a/pkg/middlewares/compress/compress.go b/pkg/middlewares/compress/compress.go index 8d3c3d933..2e9be3b81 100644 --- a/pkg/middlewares/compress/compress.go +++ b/pkg/middlewares/compress/compress.go @@ -7,8 +7,8 @@ import ( "strings" "github.com/NYTimes/gziphandler" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/compress/compress_test.go b/pkg/middlewares/compress/compress_test.go index 6f2c4e923..bca126916 100644 --- a/pkg/middlewares/compress/compress_test.go +++ b/pkg/middlewares/compress/compress_test.go @@ -7,7 +7,7 @@ import ( "testing" "github.com/NYTimes/gziphandler" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/customerrors/custom_errors.go b/pkg/middlewares/customerrors/custom_errors.go index 77a552c2f..c88c90c2f 100644 --- a/pkg/middlewares/customerrors/custom_errors.go +++ b/pkg/middlewares/customerrors/custom_errors.go @@ -11,10 +11,10 @@ import ( "strconv" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" + "github.com/containous/traefik/v2/pkg/types" "github.com/opentracing/opentracing-go/ext" "github.com/sirupsen/logrus" "github.com/vulcand/oxy/utils" diff --git a/pkg/middlewares/customerrors/custom_errors_test.go b/pkg/middlewares/customerrors/custom_errors_test.go index cf7d577b9..19aee2437 100644 --- a/pkg/middlewares/customerrors/custom_errors_test.go +++ b/pkg/middlewares/customerrors/custom_errors_test.go @@ -7,9 +7,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/emptybackendhandler/empty_backend_handler.go b/pkg/middlewares/emptybackendhandler/empty_backend_handler.go index 532e8cbd5..73743adfb 100644 --- a/pkg/middlewares/emptybackendhandler/empty_backend_handler.go +++ b/pkg/middlewares/emptybackendhandler/empty_backend_handler.go @@ -3,7 +3,7 @@ package emptybackendhandler import ( "net/http" - "github.com/containous/traefik/pkg/healthcheck" + "github.com/containous/traefik/v2/pkg/healthcheck" ) // EmptyBackend is a middleware that checks whether the current Backend diff --git a/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go b/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go index 514748698..dc4e89c94 100644 --- a/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go +++ b/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go @@ -7,7 +7,7 @@ import ( "net/url" "testing" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/vulcand/oxy/roundrobin" ) diff --git a/pkg/middlewares/extractor.go b/pkg/middlewares/extractor.go new file mode 100644 index 000000000..75b700523 --- /dev/null +++ b/pkg/middlewares/extractor.go @@ -0,0 +1,49 @@ +package middlewares + +import ( + "context" + "errors" + "fmt" + "net/http" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/vulcand/oxy/utils" +) + +// GetSourceExtractor returns the SourceExtractor function corresponding to the given sourceMatcher. +// It defaults to a RemoteAddrStrategy IPStrategy if need be. +func GetSourceExtractor(ctx context.Context, sourceMatcher *dynamic.SourceCriterion) (utils.SourceExtractor, error) { + if sourceMatcher == nil || + sourceMatcher.IPStrategy == nil && + sourceMatcher.RequestHeaderName == "" && !sourceMatcher.RequestHost { + sourceMatcher = &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{}, + } + } + + logger := log.FromContext(ctx) + if sourceMatcher.IPStrategy != nil { + strategy, err := sourceMatcher.IPStrategy.Get() + if err != nil { + return nil, err + } + + logger.Debug("Using IPStrategy") + return utils.ExtractorFunc(func(req *http.Request) (string, int64, error) { + return strategy.GetIP(req), 1, nil + }), nil + } + + if sourceMatcher.RequestHeaderName != "" { + logger.Debug("Using RequestHeaderName") + return utils.NewExtractor(fmt.Sprintf("request.header.%s", sourceMatcher.RequestHeaderName)) + } + + if sourceMatcher.RequestHost { + logger.Debug("Using RequestHost") + return utils.NewExtractor("request.host") + } + + return nil, errors.New("no SourceCriterion criterion defined") +} diff --git a/pkg/middlewares/forwardedheaders/forwarded_header.go b/pkg/middlewares/forwardedheaders/forwarded_header.go index 09f350353..455e756ec 100644 --- a/pkg/middlewares/forwardedheaders/forwarded_header.go +++ b/pkg/middlewares/forwardedheaders/forwarded_header.go @@ -6,7 +6,7 @@ import ( "os" "strings" - "github.com/containous/traefik/pkg/ip" + "github.com/containous/traefik/v2/pkg/ip" ) const ( diff --git a/pkg/middlewares/handler_switcher.go b/pkg/middlewares/handler_switcher.go index a52432aef..79be6d2e9 100644 --- a/pkg/middlewares/handler_switcher.go +++ b/pkg/middlewares/handler_switcher.go @@ -3,7 +3,7 @@ package middlewares import ( "net/http" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/safe" ) // HTTPHandlerSwitcher allows hot switching of http.ServeMux diff --git a/pkg/middlewares/headers/headers.go b/pkg/middlewares/headers/headers.go index d496ba5e5..63a623e13 100644 --- a/pkg/middlewares/headers/headers.go +++ b/pkg/middlewares/headers/headers.go @@ -8,9 +8,9 @@ import ( "strconv" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/unrolled/secure" ) diff --git a/pkg/middlewares/headers/headers_test.go b/pkg/middlewares/headers/headers_test.go index d4ec57e73..592be7a02 100644 --- a/pkg/middlewares/headers/headers_test.go +++ b/pkg/middlewares/headers/headers_test.go @@ -8,9 +8,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/inflightreq/inflight_req.go b/pkg/middlewares/inflightreq/inflight_req.go new file mode 100644 index 000000000..4be488bd8 --- /dev/null +++ b/pkg/middlewares/inflightreq/inflight_req.go @@ -0,0 +1,57 @@ +package inflightreq + +import ( + "context" + "fmt" + "net/http" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" + "github.com/opentracing/opentracing-go/ext" + "github.com/vulcand/oxy/connlimit" +) + +const ( + typeName = "InFlightReq" +) + +type inFlightReq struct { + handler http.Handler + name string +} + +// New creates a max request middleware. +func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, name string) (http.Handler, error) { + ctxLog := log.With(ctx, log.Str(log.MiddlewareName, name), log.Str(log.MiddlewareType, typeName)) + log.FromContext(ctxLog).Debug("Creating middleware") + + if config.SourceCriterion == nil || + config.SourceCriterion.IPStrategy == nil && + config.SourceCriterion.RequestHeaderName == "" && !config.SourceCriterion.RequestHost { + config.SourceCriterion = &dynamic.SourceCriterion{ + RequestHost: true, + } + } + + sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion) + if err != nil { + return nil, fmt.Errorf("error creating requests limiter: %v", err) + } + + handler, err := connlimit.New(next, sourceMatcher, config.Amount) + if err != nil { + return nil, fmt.Errorf("error creating connection limit: %v", err) + } + + return &inFlightReq{handler: handler, name: name}, nil +} + +func (i *inFlightReq) GetTracingInformation() (string, ext.SpanKindEnum) { + return i.name, tracing.SpanKindNoneEnum +} + +func (i *inFlightReq) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + i.handler.ServeHTTP(rw, req) +} diff --git a/pkg/middlewares/ipwhitelist/ip_whitelist.go b/pkg/middlewares/ipwhitelist/ip_whitelist.go index 659800c51..20c9bd7bc 100644 --- a/pkg/middlewares/ipwhitelist/ip_whitelist.go +++ b/pkg/middlewares/ipwhitelist/ip_whitelist.go @@ -6,10 +6,10 @@ import ( "fmt" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/ip" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/ip" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/ipwhitelist/ip_whitelist_test.go b/pkg/middlewares/ipwhitelist/ip_whitelist_test.go index 5200dea54..940716292 100644 --- a/pkg/middlewares/ipwhitelist/ip_whitelist_test.go +++ b/pkg/middlewares/ipwhitelist/ip_whitelist_test.go @@ -6,7 +6,7 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/maxconnection/max_connection.go b/pkg/middlewares/maxconnection/max_connection.go deleted file mode 100644 index e81c3089b..000000000 --- a/pkg/middlewares/maxconnection/max_connection.go +++ /dev/null @@ -1,48 +0,0 @@ -package maxconnection - -import ( - "context" - "fmt" - "net/http" - - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" - "github.com/opentracing/opentracing-go/ext" - "github.com/vulcand/oxy/connlimit" - "github.com/vulcand/oxy/utils" -) - -const ( - typeName = "MaxConnection" -) - -type maxConnection struct { - handler http.Handler - name string -} - -// New creates a max connection middleware. -func New(ctx context.Context, next http.Handler, maxConns dynamic.MaxConn, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") - - extractFunc, err := utils.NewExtractor(maxConns.ExtractorFunc) - if err != nil { - return nil, fmt.Errorf("error creating connection limit: %v", err) - } - - handler, err := connlimit.New(next, extractFunc, maxConns.Amount) - if err != nil { - return nil, fmt.Errorf("error creating connection limit: %v", err) - } - - return &maxConnection{handler: handler, name: name}, nil -} - -func (mc *maxConnection) GetTracingInformation() (string, ext.SpanKindEnum) { - return mc.name, tracing.SpanKindNoneEnum -} - -func (mc *maxConnection) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - mc.handler.ServeHTTP(rw, req) -} diff --git a/pkg/middlewares/metrics/metrics.go b/pkg/middlewares/metrics/metrics.go index d66d3b16f..6f86095e7 100644 --- a/pkg/middlewares/metrics/metrics.go +++ b/pkg/middlewares/metrics/metrics.go @@ -10,10 +10,10 @@ import ( "unicode/utf8" "github.com/containous/alice" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/metrics" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/retry" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/metrics" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/retry" gokitmetrics "github.com/go-kit/kit/metrics" ) diff --git a/pkg/middlewares/middleware.go b/pkg/middlewares/middleware.go index 0c65b9745..2b76b2bc8 100644 --- a/pkg/middlewares/middleware.go +++ b/pkg/middlewares/middleware.go @@ -3,7 +3,7 @@ package middlewares import ( "context" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go index 22002ef26..64d6f2fea 100644 --- a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go +++ b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go @@ -11,10 +11,10 @@ import ( "net/url" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go index a2c6cd967..5ba15c535 100644 --- a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go +++ b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert_test.go @@ -13,8 +13,8 @@ import ( "strings" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/pipelining/pipelining.go b/pkg/middlewares/pipelining/pipelining.go index cd0340f3f..e2cf2898a 100644 --- a/pkg/middlewares/pipelining/pipelining.go +++ b/pkg/middlewares/pipelining/pipelining.go @@ -6,7 +6,7 @@ import ( "net" "net/http" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares" ) const ( diff --git a/pkg/middlewares/ratelimiter/rate_limiter.go b/pkg/middlewares/ratelimiter/rate_limiter.go index 4f9e53865..73682c200 100644 --- a/pkg/middlewares/ratelimiter/rate_limiter.go +++ b/pkg/middlewares/ratelimiter/rate_limiter.go @@ -1,54 +1,146 @@ +// Package ratelimiter implements a rate limiting and traffic shaping middleware with a set of token buckets. package ratelimiter import ( "context" + "fmt" "net/http" + "sync" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" + "github.com/mailgun/ttlmap" "github.com/opentracing/opentracing-go/ext" - "github.com/vulcand/oxy/ratelimit" "github.com/vulcand/oxy/utils" + "golang.org/x/time/rate" ) const ( - typeName = "RateLimiterType" + typeName = "RateLimiterType" + maxSources = 65536 ) +// rateLimiter implements rate limiting and traffic shaping with a set of token buckets; +// one for each traffic source. The same parameters are applied to all the buckets. type rateLimiter struct { - handler http.Handler - name string + name string + rate rate.Limit // reqs/s + burst int64 + // maxDelay is the maximum duration we're willing to wait for a bucket reservation to become effective, in nanoseconds. + // For now it is somewhat arbitrarily set to 1/rate. + maxDelay time.Duration + sourceMatcher utils.SourceExtractor + next http.Handler + + bucketsMu sync.Mutex + buckets *ttlmap.TtlMap // actual buckets, keyed by source. } -// New creates rate limiter middleware. +// New returns a rate limiter middleware. func New(ctx context.Context, next http.Handler, config dynamic.RateLimit, name string) (http.Handler, error) { - middlewares.GetLogger(ctx, name, typeName).Debug("Creating middleware") + ctxLog := log.With(ctx, log.Str(log.MiddlewareName, name), log.Str(log.MiddlewareType, typeName)) + log.FromContext(ctxLog).Debug("Creating middleware") - extractFunc, err := utils.NewExtractor(config.ExtractorFunc) - if err != nil { - return nil, err - } - - rateSet := ratelimit.NewRateSet() - for _, rate := range config.RateSet { - if err = rateSet.Add(time.Duration(rate.Period), rate.Average, rate.Burst); err != nil { - return nil, err + if config.SourceCriterion == nil || + config.SourceCriterion.IPStrategy == nil && + config.SourceCriterion.RequestHeaderName == "" && !config.SourceCriterion.RequestHost { + config.SourceCriterion = &dynamic.SourceCriterion{ + IPStrategy: &dynamic.IPStrategy{}, } } - rl, err := ratelimit.New(next, extractFunc, rateSet) + sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion) if err != nil { return nil, err } - return &rateLimiter{handler: rl, name: name}, nil + + buckets, err := ttlmap.NewMap(maxSources) + if err != nil { + return nil, err + } + + burst := config.Burst + if burst <= 0 { + burst = 1 + } + + // Logically, we should set maxDelay to ~infinity when config.Average == 0 (because it means to rate limiting), + // but since the reservation will give us a delay = 0 anyway in this case, we're good even with any maxDelay >= 0. + var maxDelay time.Duration + if config.Average != 0 { + maxDelay = time.Second / time.Duration(config.Average*2) + } + + return &rateLimiter{ + name: name, + rate: rate.Limit(config.Average), + burst: burst, + maxDelay: maxDelay, + next: next, + sourceMatcher: sourceMatcher, + buckets: buckets, + }, nil } -func (r *rateLimiter) GetTracingInformation() (string, ext.SpanKindEnum) { - return r.name, tracing.SpanKindNoneEnum +func (rl *rateLimiter) GetTracingInformation() (string, ext.SpanKindEnum) { + return rl.name, tracing.SpanKindNoneEnum } -func (r *rateLimiter) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - r.handler.ServeHTTP(rw, req) +func (rl *rateLimiter) ServeHTTP(w http.ResponseWriter, r *http.Request) { + logger := middlewares.GetLogger(r.Context(), rl.name, typeName) + + source, amount, err := rl.sourceMatcher.Extract(r) + if err != nil { + logger.Errorf("could not extract source of request: %v", err) + http.Error(w, "could not extract source of request", http.StatusInternalServerError) + return + } + + if amount != 1 { + logger.Infof("ignoring token bucket amount > 1: %d", amount) + } + + rl.bucketsMu.Lock() + defer rl.bucketsMu.Unlock() + + var bucket *rate.Limiter + if rlSource, exists := rl.buckets.Get(source); exists { + bucket = rlSource.(*rate.Limiter) + } else { + bucket = rate.NewLimiter(rl.rate, int(rl.burst)) + if err := rl.buckets.Set(source, bucket, int(rl.maxDelay)*10+1); err != nil { + logger.Errorf("could not insert bucket: %v", err) + http.Error(w, "could not insert bucket", http.StatusInternalServerError) + return + } + } + + res := bucket.Reserve() + if !res.OK() { + http.Error(w, "No bursty traffic allowed", http.StatusTooManyRequests) + return + } + + delay := res.Delay() + if delay > rl.maxDelay { + res.Cancel() + rl.serveDelayError(w, r, delay) + return + } + + time.Sleep(delay) + rl.next.ServeHTTP(w, r) +} + +func (rl *rateLimiter) serveDelayError(w http.ResponseWriter, r *http.Request, delay time.Duration) { + w.Header().Set("Retry-After", fmt.Sprintf("%.0f", delay.Seconds())) + w.Header().Set("X-Retry-In", delay.String()) + w.WriteHeader(http.StatusTooManyRequests) + + if _, err := w.Write([]byte(http.StatusText(http.StatusTooManyRequests))); err != nil { + middlewares.GetLogger(r.Context(), rl.name, typeName).Errorf("could not serve 429: %v", err) + } } diff --git a/pkg/middlewares/ratelimiter/rate_limiter_test.go b/pkg/middlewares/ratelimiter/rate_limiter_test.go new file mode 100644 index 000000000..94fcedba8 --- /dev/null +++ b/pkg/middlewares/ratelimiter/rate_limiter_test.go @@ -0,0 +1,160 @@ +package ratelimiter + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "github.com/vulcand/oxy/utils" +) + +func TestNewRateLimiter(t *testing.T) { + testCases := []struct { + desc string + config dynamic.RateLimit + expectedMaxDelay time.Duration + expectedSourceIP string + }{ + { + desc: "maxDelay computation", + config: dynamic.RateLimit{ + Average: 200, + Burst: 10, + }, + expectedMaxDelay: 2500 * time.Microsecond, + }, + { + desc: "default SourceMatcher is remote address ip strategy", + config: dynamic.RateLimit{ + Average: 200, + Burst: 10, + }, + expectedSourceIP: "127.0.0.1", + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) + + h, err := New(context.Background(), next, test.config, "rate-limiter") + require.NoError(t, err) + + rtl, _ := h.(*rateLimiter) + if test.expectedMaxDelay != 0 { + assert.Equal(t, test.expectedMaxDelay, rtl.maxDelay) + } + + if test.expectedSourceIP != "" { + extractor, ok := rtl.sourceMatcher.(utils.ExtractorFunc) + require.True(t, ok, "Not an ExtractorFunc") + + req := http.Request{ + RemoteAddr: fmt.Sprintf("%s:1234", test.expectedSourceIP), + } + + ip, _, err := extractor(&req) + assert.NoError(t, err) + assert.Equal(t, test.expectedSourceIP, ip) + } + }) + } +} + +func TestRateLimit(t *testing.T) { + testCases := []struct { + desc string + config dynamic.RateLimit + reqCount int + }{ + { + desc: "Average is respected", + config: dynamic.RateLimit{ + Average: 100, + Burst: 1, + }, + reqCount: 200, + }, + { + desc: "Burst is taken into account", + config: dynamic.RateLimit{ + Average: 100, + Burst: 200, + }, + reqCount: 300, + }, + { + desc: "Zero average ==> no rate limiting", + config: dynamic.RateLimit{ + Average: 0, + Burst: 1, + }, + reqCount: 100, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + t.Parallel() + + reqCount := 0 + next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + reqCount++ + }) + + h, err := New(context.Background(), next, test.config, "rate-limiter") + require.NoError(t, err) + + start := time.Now() + for { + if reqCount >= test.reqCount { + break + } + + req := testhelpers.MustNewRequest(http.MethodGet, "http://localhost", nil) + req.RemoteAddr = "127.0.0.1:1234" + w := httptest.NewRecorder() + + h.ServeHTTP(w, req) + // TODO(mpl): predict and count the 200 VS the 429? + } + + stop := time.Now() + elapsed := stop.Sub(start) + if test.config.Average == 0 { + if elapsed > time.Millisecond { + t.Fatalf("rate should not have been limited, but: %d requests in %v", reqCount, elapsed) + } + return + } + + // Assume allowed burst is initially consumed in an infinitesimal period of time + var expectedDuration time.Duration + if test.config.Average != 0 { + expectedDuration = time.Duration((int64(test.reqCount)-test.config.Burst+1)/test.config.Average) * time.Second + } + + // Allow for a 2% leeway + minDuration := expectedDuration * 98 / 100 + maxDuration := expectedDuration * 102 / 100 + + if elapsed < minDuration { + t.Fatalf("rate was faster than expected: %d requests in %v", reqCount, elapsed) + } + if elapsed > maxDuration { + t.Fatalf("rate was slower than expected: %d requests in %v", reqCount, elapsed) + } + }) + } +} diff --git a/pkg/middlewares/recovery/recovery.go b/pkg/middlewares/recovery/recovery.go index 627478fdc..054b2d402 100644 --- a/pkg/middlewares/recovery/recovery.go +++ b/pkg/middlewares/recovery/recovery.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares" "github.com/sirupsen/logrus" ) diff --git a/pkg/middlewares/redirect/redirect.go b/pkg/middlewares/redirect/redirect.go index 44a7c0e4a..541c4ab7c 100644 --- a/pkg/middlewares/redirect/redirect.go +++ b/pkg/middlewares/redirect/redirect.go @@ -10,7 +10,7 @@ import ( "regexp" "strings" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/vulcand/oxy/utils" ) diff --git a/pkg/middlewares/redirect/redirect_regex.go b/pkg/middlewares/redirect/redirect_regex.go index 1028e2403..0c8f6406e 100644 --- a/pkg/middlewares/redirect/redirect_regex.go +++ b/pkg/middlewares/redirect/redirect_regex.go @@ -4,8 +4,8 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" ) const ( diff --git a/pkg/middlewares/redirect/redirect_regex_test.go b/pkg/middlewares/redirect/redirect_regex_test.go index 774f31b6d..9a3882003 100644 --- a/pkg/middlewares/redirect/redirect_regex_test.go +++ b/pkg/middlewares/redirect/redirect_regex_test.go @@ -7,8 +7,8 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/redirect/redirect_scheme.go b/pkg/middlewares/redirect/redirect_scheme.go index f95679eab..0ffd5d704 100644 --- a/pkg/middlewares/redirect/redirect_scheme.go +++ b/pkg/middlewares/redirect/redirect_scheme.go @@ -5,8 +5,8 @@ import ( "errors" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" ) const ( diff --git a/pkg/middlewares/redirect/redirect_scheme_test.go b/pkg/middlewares/redirect/redirect_scheme_test.go index 3e5072aa3..7000912db 100644 --- a/pkg/middlewares/redirect/redirect_scheme_test.go +++ b/pkg/middlewares/redirect/redirect_scheme_test.go @@ -8,7 +8,7 @@ import ( "regexp" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/replacepath/replace_path.go b/pkg/middlewares/replacepath/replace_path.go index 9706c425c..a53cc9a54 100644 --- a/pkg/middlewares/replacepath/replace_path.go +++ b/pkg/middlewares/replacepath/replace_path.go @@ -4,9 +4,9 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/replacepath/replace_path_test.go b/pkg/middlewares/replacepath/replace_path_test.go index 16d07442b..ca9e03e81 100644 --- a/pkg/middlewares/replacepath/replace_path_test.go +++ b/pkg/middlewares/replacepath/replace_path_test.go @@ -5,8 +5,8 @@ import ( "net/http" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/replacepathregex/replace_path_regex.go b/pkg/middlewares/replacepathregex/replace_path_regex.go index 0421cc06f..89d3b062a 100644 --- a/pkg/middlewares/replacepathregex/replace_path_regex.go +++ b/pkg/middlewares/replacepathregex/replace_path_regex.go @@ -7,10 +7,10 @@ import ( "regexp" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/replacepath" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/replacepath" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/replacepathregex/replace_path_regex_test.go b/pkg/middlewares/replacepathregex/replace_path_regex_test.go index fe73c6199..d865a5cc2 100644 --- a/pkg/middlewares/replacepathregex/replace_path_regex_test.go +++ b/pkg/middlewares/replacepathregex/replace_path_regex_test.go @@ -5,9 +5,9 @@ import ( "net/http" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares/replacepath" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares/replacepath" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/requestdecorator/hostresolver.go b/pkg/middlewares/requestdecorator/hostresolver.go index a5e7076d5..3c4652231 100644 --- a/pkg/middlewares/requestdecorator/hostresolver.go +++ b/pkg/middlewares/requestdecorator/hostresolver.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/miekg/dns" "github.com/patrickmn/go-cache" ) diff --git a/pkg/middlewares/requestdecorator/request_decorator.go b/pkg/middlewares/requestdecorator/request_decorator.go index a4c053cbe..eebf8a9e7 100644 --- a/pkg/middlewares/requestdecorator/request_decorator.go +++ b/pkg/middlewares/requestdecorator/request_decorator.go @@ -7,7 +7,7 @@ import ( "strings" "github.com/containous/alice" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" ) const ( diff --git a/pkg/middlewares/requestdecorator/request_decorator_test.go b/pkg/middlewares/requestdecorator/request_decorator_test.go index 4cce6bd1b..a757c1f60 100644 --- a/pkg/middlewares/requestdecorator/request_decorator_test.go +++ b/pkg/middlewares/requestdecorator/request_decorator_test.go @@ -4,9 +4,9 @@ import ( "net/http" "testing" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/types" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" ) diff --git a/pkg/middlewares/retry/retry.go b/pkg/middlewares/retry/retry.go index 3658e69f0..05fd158f1 100644 --- a/pkg/middlewares/retry/retry.go +++ b/pkg/middlewares/retry/retry.go @@ -9,9 +9,9 @@ import ( "net/http" "net/http/httptrace" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/retry/retry_test.go b/pkg/middlewares/retry/retry_test.go index 9df97011b..a9fbc6150 100644 --- a/pkg/middlewares/retry/retry_test.go +++ b/pkg/middlewares/retry/retry_test.go @@ -6,12 +6,13 @@ import ( "net/http" "net/http/httptest" "net/http/httptrace" + "strconv" "strings" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares/emptybackendhandler" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares/emptybackendhandler" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -38,7 +39,7 @@ func TestRetry(t *testing.T) { desc: "no retry when max request attempts is one", config: dynamic.Retry{Attempts: 1}, wantRetryAttempts: 0, - wantResponseStatus: http.StatusInternalServerError, + wantResponseStatus: http.StatusBadGateway, amountFaultyEndpoints: 1, }, { @@ -59,7 +60,7 @@ func TestRetry(t *testing.T) { desc: "max attempts exhausted delivers the 5xx response", config: dynamic.Retry{Attempts: 3}, wantRetryAttempts: 2, - wantResponseStatus: http.StatusInternalServerError, + wantResponseStatus: http.StatusBadGateway, amountFaultyEndpoints: 3, }, } @@ -83,13 +84,14 @@ func TestRetry(t *testing.T) { loadBalancer, err := roundrobin.New(forwarder) require.NoError(t, err) - basePort := 33444 + // out of range port + basePort := 1133444 for i := 0; i < test.amountFaultyEndpoints; i++ { // 192.0.2.0 is a non-routable IP for testing purposes. // See: https://stackoverflow.com/questions/528538/non-routable-ip-address/18436928#18436928 // We only use the port specification here because the URL is used as identifier // in the load balancer and using the exact same URL would not add a new server. - err = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + string(basePort+i))) + err = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + strconv.Itoa(basePort+i))) require.NoError(t, err) } @@ -277,13 +279,14 @@ func TestRetryWebsocket(t *testing.T) { t.Fatalf("Error creating load balancer: %v", err) } - basePort := 33444 + // out of range port + basePort := 1133444 for i := 0; i < test.amountFaultyEndpoints; i++ { // 192.0.2.0 is a non-routable IP for testing purposes. // See: https://stackoverflow.com/questions/528538/non-routable-ip-address/18436928#18436928 // We only use the port specification here because the URL is used as identifier // in the load balancer and using the exact same URL would not add a new server. - _ = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + string(basePort+i))) + _ = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + strconv.Itoa(basePort+i))) } // add the functioning server to the end of the load balancer list diff --git a/pkg/middlewares/stripprefix/strip_prefix.go b/pkg/middlewares/stripprefix/strip_prefix.go index 94c8de90e..42a113206 100644 --- a/pkg/middlewares/stripprefix/strip_prefix.go +++ b/pkg/middlewares/stripprefix/strip_prefix.go @@ -5,9 +5,9 @@ import ( "net/http" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/stripprefix/strip_prefix_test.go b/pkg/middlewares/stripprefix/strip_prefix_test.go index e1aed92cb..31d417162 100644 --- a/pkg/middlewares/stripprefix/strip_prefix_test.go +++ b/pkg/middlewares/stripprefix/strip_prefix_test.go @@ -6,8 +6,8 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/stripprefixregex/strip_prefix_regex.go b/pkg/middlewares/stripprefixregex/strip_prefix_regex.go index 6af3bb090..c2c98328e 100644 --- a/pkg/middlewares/stripprefixregex/strip_prefix_regex.go +++ b/pkg/middlewares/stripprefixregex/strip_prefix_regex.go @@ -5,11 +5,11 @@ import ( "net/http" "strings" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/stripprefix" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/stripprefix" + "github.com/containous/traefik/v2/pkg/tracing" + "github.com/gorilla/mux" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go b/pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go index 01ba9224e..df67d9f57 100644 --- a/pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go +++ b/pkg/middlewares/stripprefixregex/strip_prefix_regex_test.go @@ -6,9 +6,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares/stripprefix" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares/stripprefix" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/middlewares/tracing/entrypoint.go b/pkg/middlewares/tracing/entrypoint.go index 9fcc9471e..f7eeb7dc9 100644 --- a/pkg/middlewares/tracing/entrypoint.go +++ b/pkg/middlewares/tracing/entrypoint.go @@ -5,8 +5,8 @@ import ( "net/http" "github.com/containous/alice" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/tracing/entrypoint_test.go b/pkg/middlewares/tracing/entrypoint_test.go index 9d0ffd1dd..2fe090448 100644 --- a/pkg/middlewares/tracing/entrypoint_test.go +++ b/pkg/middlewares/tracing/entrypoint_test.go @@ -6,7 +6,7 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/middlewares/tracing/forwarder.go b/pkg/middlewares/tracing/forwarder.go index c485f927d..25f8ba8bc 100644 --- a/pkg/middlewares/tracing/forwarder.go +++ b/pkg/middlewares/tracing/forwarder.go @@ -4,8 +4,8 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/middlewares/tracing/forwarder_test.go b/pkg/middlewares/tracing/forwarder_test.go index f9253d859..7bf911aa0 100644 --- a/pkg/middlewares/tracing/forwarder_test.go +++ b/pkg/middlewares/tracing/forwarder_test.go @@ -6,7 +6,7 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/middlewares/tracing/wrapper.go b/pkg/middlewares/tracing/wrapper.go index a0686bf76..1e4204914 100644 --- a/pkg/middlewares/tracing/wrapper.go +++ b/pkg/middlewares/tracing/wrapper.go @@ -5,8 +5,8 @@ import ( "net/http" "github.com/containous/alice" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/tracing" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/tracing" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/ping/ping.go b/pkg/ping/ping.go index 4477c71c7..44383d8bc 100644 --- a/pkg/ping/ping.go +++ b/pkg/ping/ping.go @@ -5,7 +5,7 @@ import ( "fmt" "net/http" - "github.com/containous/mux" + "github.com/gorilla/mux" ) // Handler expose ping routes. diff --git a/pkg/provider/acme/account.go b/pkg/provider/acme/account.go index a997a92b5..1959745be 100644 --- a/pkg/provider/acme/account.go +++ b/pkg/provider/acme/account.go @@ -7,9 +7,9 @@ import ( "crypto/rsa" "crypto/x509" - "github.com/containous/traefik/pkg/log" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/registration" + "github.com/containous/traefik/v2/pkg/log" + "github.com/go-acme/lego/v3/certcrypto" + "github.com/go-acme/lego/v3/registration" ) // Account is used to store lets encrypt registration info diff --git a/pkg/provider/acme/challenge_http.go b/pkg/provider/acme/challenge_http.go index e370883d0..c224e3de5 100644 --- a/pkg/provider/acme/challenge_http.go +++ b/pkg/provider/acme/challenge_http.go @@ -6,12 +6,12 @@ import ( "net/http" "time" - "github.com/cenkalti/backoff" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/http01" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/go-acme/lego/v3/challenge" + "github.com/go-acme/lego/v3/challenge/http01" + "github.com/gorilla/mux" ) var _ challenge.ProviderTimeout = (*challengeHTTP)(nil) diff --git a/pkg/provider/acme/challenge_tls.go b/pkg/provider/acme/challenge_tls.go index 196d2d256..2adba5537 100644 --- a/pkg/provider/acme/challenge_tls.go +++ b/pkg/provider/acme/challenge_tls.go @@ -3,10 +3,10 @@ package acme import ( "crypto/tls" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/types" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/tlsalpn01" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/types" + "github.com/go-acme/lego/v3/challenge" + "github.com/go-acme/lego/v3/challenge/tlsalpn01" ) var _ challenge.Provider = (*challengeTLSALPN)(nil) diff --git a/pkg/provider/acme/local_store.go b/pkg/provider/acme/local_store.go index 717f30c2c..e0786911b 100644 --- a/pkg/provider/acme/local_store.go +++ b/pkg/provider/acme/local_store.go @@ -7,8 +7,8 @@ import ( "os" "sync" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" ) var _ Store = (*LocalStore)(nil) diff --git a/pkg/provider/acme/provider.go b/pkg/provider/acme/provider.go index b20b8e8e0..2025eb5ff 100644 --- a/pkg/provider/acme/provider.go +++ b/pkg/provider/acme/provider.go @@ -12,19 +12,19 @@ import ( "sync" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/rules" - "github.com/containous/traefik/pkg/safe" - traefiktls "github.com/containous/traefik/pkg/tls" - "github.com/containous/traefik/pkg/types" - "github.com/containous/traefik/pkg/version" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/lego" - "github.com/go-acme/lego/providers/dns" - "github.com/go-acme/lego/registration" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/rules" + "github.com/containous/traefik/v2/pkg/safe" + traefiktls "github.com/containous/traefik/v2/pkg/tls" + "github.com/containous/traefik/v2/pkg/types" + "github.com/containous/traefik/v2/pkg/version" + "github.com/go-acme/lego/v3/certificate" + "github.com/go-acme/lego/v3/challenge" + "github.com/go-acme/lego/v3/challenge/dns01" + "github.com/go-acme/lego/v3/lego" + "github.com/go-acme/lego/v3/providers/dns" + "github.com/go-acme/lego/v3/registration" ) var ( diff --git a/pkg/provider/acme/provider_test.go b/pkg/provider/acme/provider_test.go index 2629dda10..49df9ac5b 100644 --- a/pkg/provider/acme/provider_test.go +++ b/pkg/provider/acme/provider_test.go @@ -5,9 +5,9 @@ import ( "crypto/tls" "testing" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" - "github.com/go-acme/lego/certcrypto" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" + "github.com/go-acme/lego/v3/certcrypto" "github.com/stretchr/testify/assert" ) diff --git a/pkg/provider/aggregator/aggregator.go b/pkg/provider/aggregator/aggregator.go index 403dc1416..5cc7ede82 100644 --- a/pkg/provider/aggregator/aggregator.go +++ b/pkg/provider/aggregator/aggregator.go @@ -3,12 +3,12 @@ package aggregator import ( "encoding/json" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/provider/file" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/provider/file" + "github.com/containous/traefik/v2/pkg/safe" ) // ProviderAggregator aggregates providers. diff --git a/pkg/provider/configuration.go b/pkg/provider/configuration.go index 882a58255..7146e9d3e 100644 --- a/pkg/provider/configuration.go +++ b/pkg/provider/configuration.go @@ -10,8 +10,8 @@ import ( "unicode" "github.com/Masterminds/sprig" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" ) // Merge Merges multiple configurations. diff --git a/pkg/provider/docker/config.go b/pkg/provider/docker/config.go index d8474e60d..aa5aaf376 100644 --- a/pkg/provider/docker/config.go +++ b/pkg/provider/docker/config.go @@ -7,11 +7,11 @@ import ( "net" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/label" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/provider/constraints" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/label" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/provider/constraints" "github.com/docker/go-connections/nat" ) @@ -99,7 +99,7 @@ func (p *Provider) buildServiceConfiguration(ctx context.Context, container dock if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.Service) - lb := &dynamic.LoadBalancerService{} + lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() configuration.Services[serviceName] = &dynamic.Service{ LoadBalancer: lb, @@ -171,7 +171,7 @@ func (p *Provider) addServerTCP(ctx context.Context, container dockerData, loadB return nil } -func (p *Provider) addServer(ctx context.Context, container dockerData, loadBalancer *dynamic.LoadBalancerService) error { +func (p *Provider) addServer(ctx context.Context, container dockerData, loadBalancer *dynamic.ServersLoadBalancer) error { serverPort := getLBServerPort(loadBalancer) ip, port, err := p.getIPPort(ctx, container, serverPort) if err != nil { @@ -291,7 +291,7 @@ func (p *Provider) getPortBinding(container dockerData, serverPort string) (*nat return nil, fmt.Errorf("unable to find the external IP:Port for the container %q", container.Name) } -func getLBServerPort(loadBalancer *dynamic.LoadBalancerService) string { +func getLBServerPort(loadBalancer *dynamic.ServersLoadBalancer) string { if loadBalancer != nil && len(loadBalancer.Servers) > 0 { return loadBalancer.Servers[0].Port } diff --git a/pkg/provider/docker/config_test.go b/pkg/provider/docker/config_test.go index 107e9c4c6..c7c9bbdb5 100644 --- a/pkg/provider/docker/config_test.go +++ b/pkg/provider/docker/config_test.go @@ -5,7 +5,7 @@ import ( "strconv" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" docker "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" "github.com/docker/go-connections/nat" @@ -56,7 +56,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -105,7 +105,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -156,7 +156,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -200,7 +200,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -244,7 +244,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -293,7 +293,7 @@ func TestDefaultRule(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -376,7 +376,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -444,7 +444,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -454,7 +454,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Test2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.2:80", @@ -520,7 +520,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -573,7 +573,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -625,7 +625,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -669,7 +669,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -726,7 +726,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -773,7 +773,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -783,7 +783,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Service2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -990,7 +990,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1007,13 +1007,13 @@ func Test_buildConfiguration(t *testing.T) { }, }, { - desc: "one container with MaxConn in label (default value)", + desc: "one container with InFlightReq in label (default value)", containers: []dockerData{ { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1042,7 +1042,7 @@ func Test_buildConfiguration(t *testing.T) { }, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1054,9 +1054,11 @@ func Test_buildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{ "Middleware1": { - MaxConn: &dynamic.MaxConn{ - Amount: 42, - ExtractorFunc: "request.host", + InFlightReq: &dynamic.InFlightReq{ + Amount: 42, + SourceCriterion: &dynamic.SourceCriterion{ + RequestHost: true, + }, }, }, }, @@ -1071,7 +1073,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1090,7 +1092,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1119,15 +1121,17 @@ func Test_buildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{ "Middleware1": { - MaxConn: &dynamic.MaxConn{ - Amount: 42, - ExtractorFunc: "request.host", + InFlightReq: &dynamic.InFlightReq{ + Amount: 42, + SourceCriterion: &dynamic.SourceCriterion{ + RequestHost: true, + }, }, }, }, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1151,7 +1155,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1170,7 +1174,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "41", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "41", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1200,7 +1204,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1224,7 +1228,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1243,7 +1247,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "41", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "41", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1262,7 +1266,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "40", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "40", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{ @@ -1292,7 +1296,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1363,7 +1367,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1450,7 +1454,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1526,7 +1530,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1592,7 +1596,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1602,7 +1606,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Test2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.2:80", @@ -1652,7 +1656,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1703,7 +1707,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "h2c://127.0.0.1:8080", @@ -1749,7 +1753,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -1759,7 +1763,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Service2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8080", @@ -1809,7 +1813,7 @@ func Test_buildConfiguration(t *testing.T) { ServiceName: "Test", Name: "Test", Labels: map[string]string{ - "traefik.http.middlewares.Middleware1.maxconn.amount": "42", + "traefik.http.middlewares.Middleware1.inflightreq.amount": "42", }, NetworkSettings: networkSettings{ Ports: nat.PortMap{}, @@ -1974,7 +1978,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -2035,7 +2039,7 @@ func Test_buildConfiguration(t *testing.T) { }, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -2278,7 +2282,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", diff --git a/pkg/provider/docker/docker.go b/pkg/provider/docker/docker.go index dc7dff779..9d3d4c038 100644 --- a/pkg/provider/docker/docker.go +++ b/pkg/provider/docker/docker.go @@ -11,14 +11,14 @@ import ( "text/template" "time" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/job" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" - "github.com/containous/traefik/pkg/version" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/job" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" + "github.com/containous/traefik/v2/pkg/version" dockertypes "github.com/docker/docker/api/types" dockercontainertypes "github.com/docker/docker/api/types/container" eventtypes "github.com/docker/docker/api/types/events" diff --git a/pkg/provider/docker/label.go b/pkg/provider/docker/label.go index 53705c0a7..131d852a3 100644 --- a/pkg/provider/docker/label.go +++ b/pkg/provider/docker/label.go @@ -3,7 +3,7 @@ package docker import ( "fmt" - "github.com/containous/traefik/pkg/config/label" + "github.com/containous/traefik/v2/pkg/config/label" ) const ( diff --git a/pkg/provider/file/file.go b/pkg/provider/file/file.go index 6133a6eb9..2ab456373 100644 --- a/pkg/provider/file/file.go +++ b/pkg/provider/file/file.go @@ -13,11 +13,11 @@ import ( "github.com/BurntSushi/toml" "github.com/Masterminds/sprig" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/tls" "gopkg.in/fsnotify.v1" "gopkg.in/yaml.v2" ) diff --git a/pkg/provider/file/file_test.go b/pkg/provider/file/file_test.go index cb4131d1b..fab3f6d1d 100644 --- a/pkg/provider/file/file_test.go +++ b/pkg/provider/file/file_test.go @@ -10,8 +10,8 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/safe" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/provider/file/fixtures/yaml/template_file.yml b/pkg/provider/file/fixtures/yaml/template_file.yml index 66903fbc8..f427dac71 100644 --- a/pkg/provider/file/fixtures/yaml/template_file.yml +++ b/pkg/provider/file/fixtures/yaml/template_file.yml @@ -1,6 +1,6 @@ http: -{{ range $i, $e := until 20 }} routers: + {{ range $i, $e := until 20 }} router{{ $e }}: service: application-1 -{{ end }} \ No newline at end of file + {{ end }} \ No newline at end of file diff --git a/pkg/provider/kubernetes/crd/client.go b/pkg/provider/kubernetes/crd/client.go index ab5fb3f0e..fd662019d 100644 --- a/pkg/provider/kubernetes/crd/client.go +++ b/pkg/provider/kubernetes/crd/client.go @@ -6,10 +6,10 @@ import ( "io/ioutil" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions" - "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" corev1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" kubeerror "k8s.io/apimachinery/pkg/api/errors" diff --git a/pkg/provider/kubernetes/crd/client_mock_test.go b/pkg/provider/kubernetes/crd/client_mock_test.go index 9d0478bf7..da85f03d8 100644 --- a/pkg/provider/kubernetes/crd/client_mock_test.go +++ b/pkg/provider/kubernetes/crd/client_mock_test.go @@ -5,8 +5,8 @@ import ( "io/ioutil" "path/filepath" - "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" - "github.com/containous/traefik/pkg/provider/kubernetes/k8s" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/k8s" corev1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" v1beta12 "k8s.io/api/extensions/v1beta1" diff --git a/pkg/provider/kubernetes/crd/fixtures/services.yml b/pkg/provider/kubernetes/crd/fixtures/services.yml index 1c89a9c00..b5d785193 100644 --- a/pkg/provider/kubernetes/crd/fixtures/services.yml +++ b/pkg/provider/kubernetes/crd/fixtures/services.yml @@ -68,6 +68,7 @@ spec: ports: - name: web-secure port: 443 + targetPort: 8443 selector: app: containous task: whoami2 @@ -85,7 +86,7 @@ subsets: - ip: 10.10.0.6 ports: - name: web-secure - port: 443 + port: 8443 --- apiVersion: v1 diff --git a/pkg/provider/kubernetes/crd/fixtures/with_two_services_weight.yml b/pkg/provider/kubernetes/crd/fixtures/with_two_services_weight.yml new file mode 100644 index 000000000..76a5c7c3e --- /dev/null +++ b/pkg/provider/kubernetes/crd/fixtures/with_two_services_weight.yml @@ -0,0 +1,22 @@ +apiVersion: traefik.containo.us/v1alpha1 +kind: IngressRoute +metadata: + name: test.route + namespace: default + +spec: + entryPoints: + - web + + routes: + - match: Host(`foo.com`) && PathPrefix(`/foo`) + kind: Rule + priority: 12 + services: + - name: whoami + port: 80 + weight: 10 + - name: whoami2 + port: 8080 + weight: 0 + diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/clientset.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/clientset.go index 8757738a4..d0c83077f 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/clientset.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/clientset.go @@ -27,7 +27,7 @@ THE SOFTWARE. package versioned import ( - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" discovery "k8s.io/client-go/discovery" rest "k8s.io/client-go/rest" flowcontrol "k8s.io/client-go/util/flowcontrol" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/clientset_generated.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/clientset_generated.go index d02f889a0..695f82e01 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/clientset_generated.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/clientset_generated.go @@ -27,9 +27,9 @@ THE SOFTWARE. package fake import ( - clientset "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" - faketraefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake" + clientset "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" + faketraefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/watch" "k8s.io/client-go/discovery" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/register.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/register.go index 7b70355a2..f203f1751 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/register.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/fake/register.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme/register.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme/register.go index d54dbbb83..17ec0dd01 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme/register.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme/register.go @@ -27,7 +27,7 @@ THE SOFTWARE. package scheme import ( - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroute.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroute.go index fb579061c..85bf5990e 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroute.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroute.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroutetcp.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroutetcp.go index c87a5073e..7013fa49e 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroutetcp.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_ingressroutetcp.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_middleware.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_middleware.go index 08e9cf022..07428eabd 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_middleware.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_middleware.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_tlsoption.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_tlsoption.go index 885fc8367..9f2560c6e 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_tlsoption.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_tlsoption.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_traefik_client.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_traefik_client.go index 92998021f..aeb1ddd26 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_traefik_client.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/fake/fake_traefik_client.go @@ -27,7 +27,7 @@ THE SOFTWARE. package fake import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1" rest "k8s.io/client-go/rest" testing "k8s.io/client-go/testing" ) diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroute.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroute.go index 090a9622f..8691d7dfa 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroute.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroute.go @@ -29,8 +29,8 @@ package v1alpha1 import ( "time" - scheme "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + scheme "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroutetcp.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroutetcp.go index e789c9189..e98f82073 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroutetcp.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/ingressroutetcp.go @@ -29,8 +29,8 @@ package v1alpha1 import ( "time" - scheme "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + scheme "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/middleware.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/middleware.go index e8a0c7ef8..6c56f0fcd 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/middleware.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/middleware.go @@ -29,8 +29,8 @@ package v1alpha1 import ( "time" - scheme "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + scheme "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/tlsoption.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/tlsoption.go index 9f5e779ad..deda19d30 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/tlsoption.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/tlsoption.go @@ -29,8 +29,8 @@ package v1alpha1 import ( "time" - scheme "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + scheme "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/traefik_client.go b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/traefik_client.go index 5617e9596..51c42b06e 100644 --- a/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/traefik_client.go +++ b/pkg/provider/kubernetes/crd/generated/clientset/versioned/typed/traefik/v1alpha1/traefik_client.go @@ -27,8 +27,8 @@ THE SOFTWARE. package v1alpha1 import ( - "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned/scheme" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" rest "k8s.io/client-go/rest" ) diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/factory.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/factory.go index bf5ddeab3..5df045346 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/factory.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/factory.go @@ -31,9 +31,9 @@ import ( sync "sync" time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - traefik "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + traefik "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/generic.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/generic.go index 70060f80a..daee522b5 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/generic.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/generic.go @@ -29,7 +29,7 @@ package externalversions import ( "fmt" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" schema "k8s.io/apimachinery/pkg/runtime/schema" cache "k8s.io/client-go/tools/cache" ) diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces/factory_interfaces.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces/factory_interfaces.go index b7c46e786..d07e4d945 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces/factory_interfaces.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces/factory_interfaces.go @@ -29,7 +29,7 @@ package internalinterfaces import ( time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" cache "k8s.io/client-go/tools/cache" diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/interface.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/interface.go index 907cc9a03..7f254f123 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/interface.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/interface.go @@ -27,8 +27,8 @@ THE SOFTWARE. package traefik import ( - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1" ) // Interface provides access to each of this group's versions. diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroute.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroute.go index 3c5c64ff6..acc6a8048 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroute.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroute.go @@ -29,10 +29,10 @@ package v1alpha1 import ( time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroutetcp.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroutetcp.go index f4b328d01..9ec652929 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroutetcp.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/ingressroutetcp.go @@ -29,10 +29,10 @@ package v1alpha1 import ( time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/interface.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/interface.go index 54b02039a..06e742230 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/interface.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/interface.go @@ -27,7 +27,7 @@ THE SOFTWARE. package v1alpha1 import ( - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" ) // Interface provides access to all the informers in this group version. diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/middleware.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/middleware.go index a5ae6de39..dc1cffd14 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/middleware.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/middleware.go @@ -29,10 +29,10 @@ package v1alpha1 import ( time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/tlsoption.go b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/tlsoption.go index 4bbf1d981..aab823607 100644 --- a/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/tlsoption.go +++ b/pkg/provider/kubernetes/crd/generated/informers/externalversions/traefik/v1alpha1/tlsoption.go @@ -29,10 +29,10 @@ package v1alpha1 import ( time "time" - versioned "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/clientset/versioned" - internalinterfaces "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" - traefikv1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + versioned "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/clientset/versioned" + internalinterfaces "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/informers/externalversions/internalinterfaces" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1" + traefikv1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" diff --git a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroute.go b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroute.go index b796931b0..ea12c715a 100644 --- a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroute.go +++ b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroute.go @@ -27,7 +27,7 @@ THE SOFTWARE. package v1alpha1 import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" diff --git a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroutetcp.go b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroutetcp.go index c3c758ba1..e21ad0e4d 100644 --- a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroutetcp.go +++ b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/ingressroutetcp.go @@ -27,7 +27,7 @@ THE SOFTWARE. package v1alpha1 import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" diff --git a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/middleware.go b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/middleware.go index 70f1e39f7..eeed37d84 100644 --- a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/middleware.go +++ b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/middleware.go @@ -27,7 +27,7 @@ THE SOFTWARE. package v1alpha1 import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" diff --git a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/tlsoption.go b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/tlsoption.go index d8e2ca80b..11693fe4a 100644 --- a/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/tlsoption.go +++ b/pkg/provider/kubernetes/crd/generated/listers/traefik/v1alpha1/tlsoption.go @@ -27,7 +27,7 @@ THE SOFTWARE. package v1alpha1 import ( - v1alpha1 "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" + v1alpha1 "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" diff --git a/pkg/provider/kubernetes/crd/kubernetes.go b/pkg/provider/kubernetes/crd/kubernetes.go index 5bec9bca1..f3307ab8d 100644 --- a/pkg/provider/kubernetes/crd/kubernetes.go +++ b/pkg/provider/kubernetes/crd/kubernetes.go @@ -3,7 +3,6 @@ package crd import ( "context" "crypto/sha256" - "errors" "fmt" "os" "reflect" @@ -12,13 +11,12 @@ import ( "strings" "time" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/job" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider/kubernetes/crd/traefik/v1alpha1" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/tls" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/job" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/tls" corev1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/labels" ) @@ -136,159 +134,22 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe. return nil } -func checkStringQuoteValidity(value string) error { - _, err := strconv.Unquote(`"` + value + `"`) - return err -} - -func loadTCPServers(client Client, namespace string, svc v1alpha1.ServiceTCP) ([]dynamic.TCPServer, error) { - service, exists, err := client.GetService(namespace, svc.Name) - if err != nil { - return nil, err +func (p *Provider) loadConfigurationFromCRD(ctx context.Context, client Client) *dynamic.Configuration { + tlsConfigs := make(map[string]*tls.CertAndStores) + conf := &dynamic.Configuration{ + HTTP: p.loadIngressRouteConfiguration(ctx, client, tlsConfigs), + TCP: p.loadIngressRouteTCPConfiguration(ctx, client, tlsConfigs), + TLS: &dynamic.TLSConfiguration{ + Certificates: getTLSConfig(tlsConfigs), + Options: buildTLSOptions(ctx, client), + }, } - if !exists { - return nil, errors.New("service not found") + for _, middleware := range client.GetMiddlewares() { + conf.HTTP.Middlewares[makeID(middleware.Namespace, middleware.Name)] = &middleware.Spec } - var portSpec *corev1.ServicePort - for _, p := range service.Spec.Ports { - if svc.Port == p.Port { - portSpec = &p - break - } - } - - if portSpec == nil { - return nil, errors.New("service port not found") - } - - var servers []dynamic.TCPServer - if service.Spec.Type == corev1.ServiceTypeExternalName { - servers = append(servers, dynamic.TCPServer{ - Address: fmt.Sprintf("%s:%d", service.Spec.ExternalName, portSpec.Port), - }) - } else { - endpoints, endpointsExists, endpointsErr := client.GetEndpoints(namespace, svc.Name) - if endpointsErr != nil { - return nil, endpointsErr - } - - if !endpointsExists { - return nil, errors.New("endpoints not found") - } - - if len(endpoints.Subsets) == 0 { - return nil, errors.New("subset not found") - } - - var port int32 - for _, subset := range endpoints.Subsets { - for _, p := range subset.Ports { - if portSpec.Name == p.Name { - port = p.Port - break - } - } - - if port == 0 { - return nil, errors.New("cannot define a port") - } - - for _, addr := range subset.Addresses { - servers = append(servers, dynamic.TCPServer{ - Address: fmt.Sprintf("%s:%d", addr.IP, port), - }) - } - } - } - - return servers, nil -} - -func loadServers(client Client, namespace string, svc v1alpha1.Service) ([]dynamic.Server, error) { - strategy := svc.Strategy - if strategy == "" { - strategy = "RoundRobin" - } - if strategy != "RoundRobin" { - return nil, fmt.Errorf("load balancing strategy %v is not supported", strategy) - } - - service, exists, err := client.GetService(namespace, svc.Name) - if err != nil { - return nil, err - } - - if !exists { - return nil, errors.New("service not found") - } - - var portSpec *corev1.ServicePort - for _, p := range service.Spec.Ports { - if svc.Port == p.Port { - portSpec = &p - break - } - } - - if portSpec == nil { - return nil, errors.New("service port not found") - } - - var servers []dynamic.Server - if service.Spec.Type == corev1.ServiceTypeExternalName { - servers = append(servers, dynamic.Server{ - URL: fmt.Sprintf("http://%s:%d", service.Spec.ExternalName, portSpec.Port), - }) - } else { - endpoints, endpointsExists, endpointsErr := client.GetEndpoints(namespace, svc.Name) - if endpointsErr != nil { - return nil, endpointsErr - } - - if !endpointsExists { - return nil, errors.New("endpoints not found") - } - - if len(endpoints.Subsets) == 0 { - return nil, errors.New("subset not found") - } - - var port int32 - for _, subset := range endpoints.Subsets { - for _, p := range subset.Ports { - if portSpec.Name == p.Name { - port = p.Port - break - } - } - - if port == 0 { - return nil, errors.New("cannot define a port") - } - - protocol := "http" - switch svc.Scheme { - case "http", "https", "h2c": - protocol = svc.Scheme - case "": - if port == 443 || strings.HasPrefix(portSpec.Name, "https") { - protocol = "https" - } - default: - return nil, fmt.Errorf("invalid scheme %q specified", svc.Scheme) - } - - for _, addr := range subset.Addresses { - servers = append(servers, dynamic.Server{ - URL: fmt.Sprintf("%s://%s:%d", protocol, addr.IP, port), - }) - } - } - } - - return servers, nil + return conf } func buildTLSOptions(ctx context.Context, client Client) map[string]tls.Options { @@ -338,250 +199,9 @@ func buildTLSOptions(ctx context.Context, client Client) map[string]tls.Options return tlsOptions } -func (p *Provider) loadIngressRouteConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.HTTPConfiguration { - conf := &dynamic.HTTPConfiguration{ - Routers: map[string]*dynamic.Router{}, - Middlewares: map[string]*dynamic.Middleware{}, - Services: map[string]*dynamic.Service{}, - } - - for _, ingressRoute := range client.GetIngressRoutes() { - logger := log.FromContext(log.With(ctx, log.Str("ingress", ingressRoute.Name), log.Str("namespace", ingressRoute.Namespace))) - - // TODO keep the name ingressClass? - if !shouldProcessIngress(p.IngressClass, ingressRoute.Annotations[annotationKubernetesIngressClass]) { - continue - } - - err := getTLSHTTP(ctx, ingressRoute, client, tlsConfigs) - if err != nil { - logger.Errorf("Error configuring TLS: %v", err) - } - - ingressName := ingressRoute.Name - if len(ingressName) == 0 { - ingressName = ingressRoute.GenerateName - } - - for _, route := range ingressRoute.Spec.Routes { - if route.Kind != "Rule" { - logger.Errorf("Unsupported match kind: %s. Only \"Rule\" is supported for now.", route.Kind) - continue - } - - if len(route.Match) == 0 { - logger.Errorf("Empty match rule") - continue - } - - if err := checkStringQuoteValidity(route.Match); err != nil { - logger.Errorf("Invalid syntax for match rule: %s", route.Match) - continue - } - - var allServers []dynamic.Server - for _, service := range route.Services { - servers, err := loadServers(client, ingressRoute.Namespace, service) - if err != nil { - logger. - WithField("serviceName", service.Name). - WithField("servicePort", service.Port). - Errorf("Cannot create service: %v", err) - continue - } - - allServers = append(allServers, servers...) - } - - var mds []string - for _, mi := range route.Middlewares { - if strings.Contains(mi.Name, "@") { - if len(mi.Namespace) > 0 { - logger. - WithField(log.MiddlewareName, mi.Name). - Warnf("namespace %q is ignored in cross-provider context", mi.Namespace) - } - mds = append(mds, mi.Name) - continue - } - - ns := mi.Namespace - if len(ns) == 0 { - ns = ingressRoute.Namespace - } - mds = append(mds, makeID(ns, mi.Name)) - } - - key, err := makeServiceKey(route.Match, ingressName) - if err != nil { - logger.Error(err) - continue - } - - serviceName := makeID(ingressRoute.Namespace, key) - - conf.Routers[serviceName] = &dynamic.Router{ - Middlewares: mds, - Priority: route.Priority, - EntryPoints: ingressRoute.Spec.EntryPoints, - Rule: route.Match, - Service: serviceName, - } - - if ingressRoute.Spec.TLS != nil { - tlsConf := &dynamic.RouterTLSConfig{ - CertResolver: ingressRoute.Spec.TLS.CertResolver, - } - - if ingressRoute.Spec.TLS.Options != nil && len(ingressRoute.Spec.TLS.Options.Name) > 0 { - tlsOptionsName := ingressRoute.Spec.TLS.Options.Name - // Is a Kubernetes CRD reference, (i.e. not a cross-provider reference) - ns := ingressRoute.Spec.TLS.Options.Namespace - if !strings.Contains(tlsOptionsName, "@") { - if len(ns) == 0 { - ns = ingressRoute.Namespace - } - tlsOptionsName = makeID(ns, tlsOptionsName) - } else if len(ns) > 0 { - logger. - WithField("TLSoptions", ingressRoute.Spec.TLS.Options.Name). - Warnf("namespace %q is ignored in cross-provider context", ns) - } - - tlsConf.Options = tlsOptionsName - } - conf.Routers[serviceName].TLS = tlsConf - } - - conf.Services[serviceName] = &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ - Servers: allServers, - // TODO: support other strategies. - PassHostHeader: true, - }, - } - } - } - - return conf -} - -func (p *Provider) loadIngressRouteTCPConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.TCPConfiguration { - conf := &dynamic.TCPConfiguration{ - Routers: map[string]*dynamic.TCPRouter{}, - Services: map[string]*dynamic.TCPService{}, - } - - for _, ingressRouteTCP := range client.GetIngressRouteTCPs() { - logger := log.FromContext(log.With(ctx, log.Str("ingress", ingressRouteTCP.Name), log.Str("namespace", ingressRouteTCP.Namespace))) - - if !shouldProcessIngress(p.IngressClass, ingressRouteTCP.Annotations[annotationKubernetesIngressClass]) { - continue - } - - if ingressRouteTCP.Spec.TLS != nil && !ingressRouteTCP.Spec.TLS.Passthrough { - err := getTLSTCP(ctx, ingressRouteTCP, client, tlsConfigs) - if err != nil { - logger.Errorf("Error configuring TLS: %v", err) - } - } - - ingressName := ingressRouteTCP.Name - if len(ingressName) == 0 { - ingressName = ingressRouteTCP.GenerateName - } - - for _, route := range ingressRouteTCP.Spec.Routes { - if len(route.Match) == 0 { - logger.Errorf("Empty match rule") - continue - } - - if err := checkStringQuoteValidity(route.Match); err != nil { - logger.Errorf("Invalid syntax for match rule: %s", route.Match) - continue - } - - var allServers []dynamic.TCPServer - for _, service := range route.Services { - servers, err := loadTCPServers(client, ingressRouteTCP.Namespace, service) - if err != nil { - logger. - WithField("serviceName", service.Name). - WithField("servicePort", service.Port). - Errorf("Cannot create service: %v", err) - continue - } - - allServers = append(allServers, servers...) - } - - key, e := makeServiceKey(route.Match, ingressName) - if e != nil { - logger.Error(e) - continue - } - - serviceName := makeID(ingressRouteTCP.Namespace, key) - conf.Routers[serviceName] = &dynamic.TCPRouter{ - EntryPoints: ingressRouteTCP.Spec.EntryPoints, - Rule: route.Match, - Service: serviceName, - } - - if ingressRouteTCP.Spec.TLS != nil { - conf.Routers[serviceName].TLS = &dynamic.RouterTCPTLSConfig{ - Passthrough: ingressRouteTCP.Spec.TLS.Passthrough, - CertResolver: ingressRouteTCP.Spec.TLS.CertResolver, - } - - if ingressRouteTCP.Spec.TLS.Options != nil && len(ingressRouteTCP.Spec.TLS.Options.Name) > 0 { - tlsOptionsName := ingressRouteTCP.Spec.TLS.Options.Name - // Is a Kubernetes CRD reference (i.e. not a cross-provider reference) - ns := ingressRouteTCP.Spec.TLS.Options.Namespace - if !strings.Contains(tlsOptionsName, "@") { - if len(ns) == 0 { - ns = ingressRouteTCP.Namespace - } - tlsOptionsName = makeID(ns, tlsOptionsName) - } else if len(ns) > 0 { - logger. - WithField("TLSoptions", ingressRouteTCP.Spec.TLS.Options.Name). - Warnf("namespace %q is ignored in cross-provider context", ns) - } - - conf.Routers[serviceName].TLS.Options = tlsOptionsName - - } - } - - conf.Services[serviceName] = &dynamic.TCPService{ - LoadBalancer: &dynamic.TCPLoadBalancerService{ - Servers: allServers, - }, - } - } - } - - return conf -} - -func (p *Provider) loadConfigurationFromCRD(ctx context.Context, client Client) *dynamic.Configuration { - tlsConfigs := make(map[string]*tls.CertAndStores) - conf := &dynamic.Configuration{ - HTTP: p.loadIngressRouteConfiguration(ctx, client, tlsConfigs), - TCP: p.loadIngressRouteTCPConfiguration(ctx, client, tlsConfigs), - TLS: &dynamic.TLSConfiguration{ - Certificates: getTLSConfig(tlsConfigs), - Options: buildTLSOptions(ctx, client), - }, - } - - for _, middleware := range client.GetMiddlewares() { - conf.HTTP.Middlewares[makeID(middleware.Namespace, middleware.Name)] = &middleware.Spec - } - - return conf +func checkStringQuoteValidity(value string) error { + _, err := strconv.Unquote(`"` + value + `"`) + return err } func makeServiceKey(rule, ingressName string) (string, error) { @@ -608,50 +228,6 @@ func shouldProcessIngress(ingressClass string, ingressClassAnnotation string) bo (len(ingressClass) == 0 && ingressClassAnnotation == traefikDefaultIngressClass) } -func getTLSHTTP(ctx context.Context, ingressRoute *v1alpha1.IngressRoute, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { - if ingressRoute.Spec.TLS == nil { - return nil - } - if ingressRoute.Spec.TLS.SecretName == "" { - log.FromContext(ctx).Debugf("Skipping TLS sub-section: No secret name provided") - return nil - } - - configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName - if _, tlsExists := tlsConfigs[configKey]; !tlsExists { - tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) - if err != nil { - return err - } - - tlsConfigs[configKey] = tlsConf - } - - return nil -} - -func getTLSTCP(ctx context.Context, ingressRoute *v1alpha1.IngressRouteTCP, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { - if ingressRoute.Spec.TLS == nil { - return nil - } - if ingressRoute.Spec.TLS.SecretName == "" { - log.FromContext(ctx).Debugf("Skipping TLS sub-section for TCP: No secret name provided") - return nil - } - - configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName - if _, tlsExists := tlsConfigs[configKey]; !tlsExists { - tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) - if err != nil { - return err - } - - tlsConfigs[configKey] = tlsConf - } - - return nil -} - func getTLS(k8sClient Client, secretName, namespace string) (*tls.CertAndStores, error) { secret, exists, err := k8sClient.GetSecret(namespace, secretName) if err != nil { diff --git a/pkg/provider/kubernetes/crd/kubernetes_http.go b/pkg/provider/kubernetes/crd/kubernetes_http.go new file mode 100644 index 000000000..52d18dd30 --- /dev/null +++ b/pkg/provider/kubernetes/crd/kubernetes_http.go @@ -0,0 +1,274 @@ +package crd + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" + "github.com/containous/traefik/v2/pkg/tls" + corev1 "k8s.io/api/core/v1" +) + +func (p *Provider) loadIngressRouteConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.HTTPConfiguration { + conf := &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{}, + Middlewares: map[string]*dynamic.Middleware{}, + Services: map[string]*dynamic.Service{}, + } + + for _, ingressRoute := range client.GetIngressRoutes() { + ctxRt := log.With(ctx, log.Str("ingress", ingressRoute.Name), log.Str("namespace", ingressRoute.Namespace)) + logger := log.FromContext(ctxRt) + + // TODO keep the name ingressClass? + if !shouldProcessIngress(p.IngressClass, ingressRoute.Annotations[annotationKubernetesIngressClass]) { + continue + } + + err := getTLSHTTP(ctx, ingressRoute, client, tlsConfigs) + if err != nil { + logger.Errorf("Error configuring TLS: %v", err) + } + + ingressName := ingressRoute.Name + if len(ingressName) == 0 { + ingressName = ingressRoute.GenerateName + } + + for _, route := range ingressRoute.Spec.Routes { + if route.Kind != "Rule" { + logger.Errorf("Unsupported match kind: %s. Only \"Rule\" is supported for now.", route.Kind) + continue + } + + if len(route.Match) == 0 { + logger.Errorf("Empty match rule") + continue + } + + if err := checkStringQuoteValidity(route.Match); err != nil { + logger.Errorf("Invalid syntax for match rule: %s", route.Match) + continue + } + + key, err := makeServiceKey(route.Match, ingressName) + if err != nil { + logger.Error(err) + continue + } + + serviceName := makeID(ingressRoute.Namespace, key) + + for _, service := range route.Services { + balancerServerHTTP, err := createLoadBalancerServerHTTP(client, ingressRoute, service) + if err != nil { + logger. + WithField("serviceName", service.Name). + WithField("servicePort", service.Port). + Errorf("Cannot create service: %v", err) + continue + } + + if len(route.Services) == 1 { + conf.Services[serviceName] = balancerServerHTTP + break + } + + serviceKey := fmt.Sprintf("%s-%s-%d", serviceName, service.Name, service.Port) + conf.Services[serviceKey] = balancerServerHTTP + + srv := dynamic.WRRService{Name: serviceKey} + srv.SetDefaults() + if service.Weight != nil { + srv.Weight = service.Weight + } + + if conf.Services[serviceName] == nil { + conf.Services[serviceName] = &dynamic.Service{Weighted: &dynamic.WeightedRoundRobin{}} + } + conf.Services[serviceName].Weighted.Services = append(conf.Services[serviceName].Weighted.Services, srv) + } + + var mds []string + for _, mi := range route.Middlewares { + if strings.Contains(mi.Name, "@") { + if len(mi.Namespace) > 0 { + logger. + WithField(log.MiddlewareName, mi.Name). + Warnf("namespace %q is ignored in cross-provider context", mi.Namespace) + } + mds = append(mds, mi.Name) + continue + } + + ns := mi.Namespace + if len(ns) == 0 { + ns = ingressRoute.Namespace + } + mds = append(mds, makeID(ns, mi.Name)) + } + + conf.Routers[serviceName] = &dynamic.Router{ + Middlewares: mds, + Priority: route.Priority, + EntryPoints: ingressRoute.Spec.EntryPoints, + Rule: route.Match, + Service: serviceName, + } + + if ingressRoute.Spec.TLS != nil { + tlsConf := &dynamic.RouterTLSConfig{ + CertResolver: ingressRoute.Spec.TLS.CertResolver, + } + + if ingressRoute.Spec.TLS.Options != nil && len(ingressRoute.Spec.TLS.Options.Name) > 0 { + tlsOptionsName := ingressRoute.Spec.TLS.Options.Name + // Is a Kubernetes CRD reference, (i.e. not a cross-provider reference) + ns := ingressRoute.Spec.TLS.Options.Namespace + if !strings.Contains(tlsOptionsName, "@") { + if len(ns) == 0 { + ns = ingressRoute.Namespace + } + tlsOptionsName = makeID(ns, tlsOptionsName) + } else if len(ns) > 0 { + logger. + WithField("TLSoptions", ingressRoute.Spec.TLS.Options.Name). + Warnf("namespace %q is ignored in cross-provider context", ns) + } + + tlsConf.Options = tlsOptionsName + } + conf.Routers[serviceName].TLS = tlsConf + } + + } + } + + return conf +} + +func createLoadBalancerServerHTTP(client Client, ingressRoute *v1alpha1.IngressRoute, service v1alpha1.Service) (*dynamic.Service, error) { + servers, err := loadServers(client, ingressRoute.Namespace, service) + if err != nil { + return nil, err + } + + return &dynamic.Service{ + LoadBalancer: &dynamic.ServersLoadBalancer{ + Servers: servers, + // TODO: support other strategies. + PassHostHeader: true, + }, + }, nil +} + +func loadServers(client Client, namespace string, svc v1alpha1.Service) ([]dynamic.Server, error) { + strategy := svc.Strategy + if strategy == "" { + strategy = "RoundRobin" + } + if strategy != "RoundRobin" { + return nil, fmt.Errorf("load balancing strategy %v is not supported", strategy) + } + + service, exists, err := client.GetService(namespace, svc.Name) + if err != nil { + return nil, err + } + + if !exists { + return nil, errors.New("service not found") + } + + var portSpec *corev1.ServicePort + for _, p := range service.Spec.Ports { + if svc.Port == p.Port { + portSpec = &p + break + } + } + + if portSpec == nil { + return nil, errors.New("service port not found") + } + + var servers []dynamic.Server + if service.Spec.Type == corev1.ServiceTypeExternalName { + servers = append(servers, dynamic.Server{ + URL: fmt.Sprintf("http://%s:%d", service.Spec.ExternalName, portSpec.Port), + }) + } else { + endpoints, endpointsExists, endpointsErr := client.GetEndpoints(namespace, svc.Name) + if endpointsErr != nil { + return nil, endpointsErr + } + + if !endpointsExists { + return nil, errors.New("endpoints not found") + } + + if len(endpoints.Subsets) == 0 { + return nil, errors.New("subset not found") + } + + var port int32 + for _, subset := range endpoints.Subsets { + for _, p := range subset.Ports { + if portSpec.Name == p.Name { + port = p.Port + break + } + } + + if port == 0 { + return nil, errors.New("cannot define a port") + } + + protocol := "http" + switch svc.Scheme { + case "http", "https", "h2c": + protocol = svc.Scheme + case "": + if portSpec.Port == 443 || strings.HasPrefix(portSpec.Name, "https") { + protocol = "https" + } + default: + return nil, fmt.Errorf("invalid scheme %q specified", svc.Scheme) + } + + for _, addr := range subset.Addresses { + servers = append(servers, dynamic.Server{ + URL: fmt.Sprintf("%s://%s:%d", protocol, addr.IP, port), + }) + } + } + } + + return servers, nil +} + +func getTLSHTTP(ctx context.Context, ingressRoute *v1alpha1.IngressRoute, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { + if ingressRoute.Spec.TLS == nil { + return nil + } + if ingressRoute.Spec.TLS.SecretName == "" { + log.FromContext(ctx).Debugf("No secret name provided") + return nil + } + + configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName + if _, tlsExists := tlsConfigs[configKey]; !tlsExists { + tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) + if err != nil { + return err + } + + tlsConfigs[configKey] = tlsConf + } + + return nil +} diff --git a/pkg/provider/kubernetes/crd/kubernetes_tcp.go b/pkg/provider/kubernetes/crd/kubernetes_tcp.go new file mode 100644 index 000000000..ea64d89ca --- /dev/null +++ b/pkg/provider/kubernetes/crd/kubernetes_tcp.go @@ -0,0 +1,201 @@ +package crd + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" + "github.com/containous/traefik/v2/pkg/tls" + corev1 "k8s.io/api/core/v1" +) + +func (p *Provider) loadIngressRouteTCPConfiguration(ctx context.Context, client Client, tlsConfigs map[string]*tls.CertAndStores) *dynamic.TCPConfiguration { + conf := &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{}, + Services: map[string]*dynamic.TCPService{}, + } + + for _, ingressRouteTCP := range client.GetIngressRouteTCPs() { + logger := log.FromContext(log.With(ctx, log.Str("ingress", ingressRouteTCP.Name), log.Str("namespace", ingressRouteTCP.Namespace))) + + if !shouldProcessIngress(p.IngressClass, ingressRouteTCP.Annotations[annotationKubernetesIngressClass]) { + continue + } + + if ingressRouteTCP.Spec.TLS != nil && !ingressRouteTCP.Spec.TLS.Passthrough { + err := getTLSTCP(ctx, ingressRouteTCP, client, tlsConfigs) + if err != nil { + logger.Errorf("Error configuring TLS: %v", err) + } + } + + ingressName := ingressRouteTCP.Name + if len(ingressName) == 0 { + ingressName = ingressRouteTCP.GenerateName + } + + for _, route := range ingressRouteTCP.Spec.Routes { + if len(route.Match) == 0 { + logger.Errorf("Empty match rule") + continue + } + + if err := checkStringQuoteValidity(route.Match); err != nil { + logger.Errorf("Invalid syntax for match rule: %s", route.Match) + continue + } + + var allServers []dynamic.TCPServer + for _, service := range route.Services { + servers, err := loadTCPServers(client, ingressRouteTCP.Namespace, service) + if err != nil { + logger. + WithField("serviceName", service.Name). + WithField("servicePort", service.Port). + Errorf("Cannot create service: %v", err) + continue + } + + allServers = append(allServers, servers...) + } + + key, e := makeServiceKey(route.Match, ingressName) + if e != nil { + logger.Error(e) + continue + } + + serviceName := makeID(ingressRouteTCP.Namespace, key) + conf.Routers[serviceName] = &dynamic.TCPRouter{ + EntryPoints: ingressRouteTCP.Spec.EntryPoints, + Rule: route.Match, + Service: serviceName, + } + + if ingressRouteTCP.Spec.TLS != nil { + conf.Routers[serviceName].TLS = &dynamic.RouterTCPTLSConfig{ + Passthrough: ingressRouteTCP.Spec.TLS.Passthrough, + CertResolver: ingressRouteTCP.Spec.TLS.CertResolver, + } + + if ingressRouteTCP.Spec.TLS.Options != nil && len(ingressRouteTCP.Spec.TLS.Options.Name) > 0 { + tlsOptionsName := ingressRouteTCP.Spec.TLS.Options.Name + // Is a Kubernetes CRD reference (i.e. not a cross-provider reference) + ns := ingressRouteTCP.Spec.TLS.Options.Namespace + if !strings.Contains(tlsOptionsName, "@") { + if len(ns) == 0 { + ns = ingressRouteTCP.Namespace + } + tlsOptionsName = makeID(ns, tlsOptionsName) + } else if len(ns) > 0 { + logger. + WithField("TLSoptions", ingressRouteTCP.Spec.TLS.Options.Name). + Warnf("namespace %q is ignored in cross-provider context", ns) + } + + conf.Routers[serviceName].TLS.Options = tlsOptionsName + + } + } + + conf.Services[serviceName] = &dynamic.TCPService{ + LoadBalancer: &dynamic.TCPLoadBalancerService{ + Servers: allServers, + }, + } + } + } + + return conf +} + +func loadTCPServers(client Client, namespace string, svc v1alpha1.ServiceTCP) ([]dynamic.TCPServer, error) { + service, exists, err := client.GetService(namespace, svc.Name) + if err != nil { + return nil, err + } + + if !exists { + return nil, errors.New("service not found") + } + + var portSpec *corev1.ServicePort + for _, p := range service.Spec.Ports { + if svc.Port == p.Port { + portSpec = &p + break + } + } + + if portSpec == nil { + return nil, errors.New("service port not found") + } + + var servers []dynamic.TCPServer + if service.Spec.Type == corev1.ServiceTypeExternalName { + servers = append(servers, dynamic.TCPServer{ + Address: fmt.Sprintf("%s:%d", service.Spec.ExternalName, portSpec.Port), + }) + } else { + endpoints, endpointsExists, endpointsErr := client.GetEndpoints(namespace, svc.Name) + if endpointsErr != nil { + return nil, endpointsErr + } + + if !endpointsExists { + return nil, errors.New("endpoints not found") + } + + if len(endpoints.Subsets) == 0 { + return nil, errors.New("subset not found") + } + + var port int32 + for _, subset := range endpoints.Subsets { + for _, p := range subset.Ports { + if portSpec.Name == p.Name { + port = p.Port + break + } + } + + if port == 0 { + return nil, errors.New("cannot define a port") + } + + for _, addr := range subset.Addresses { + servers = append(servers, dynamic.TCPServer{ + Address: fmt.Sprintf("%s:%d", addr.IP, port), + }) + } + } + } + + return servers, nil +} + +func getTLSTCP(ctx context.Context, ingressRoute *v1alpha1.IngressRouteTCP, k8sClient Client, tlsConfigs map[string]*tls.CertAndStores) error { + if ingressRoute.Spec.TLS == nil { + return nil + } + if ingressRoute.Spec.TLS.SecretName == "" { + log.FromContext(ctx).Debugf("No secret name provided") + return nil + } + + configKey := ingressRoute.Namespace + "/" + ingressRoute.Spec.TLS.SecretName + if _, tlsExists := tlsConfigs[configKey]; !tlsExists { + tlsConf, err := getTLS(k8sClient, ingressRoute.Spec.TLS.SecretName, ingressRoute.Namespace) + if err != nil { + return err + } + + tlsConfigs[configKey] = tlsConf + } + + return nil +} diff --git a/pkg/provider/kubernetes/crd/kubernetes_test.go b/pkg/provider/kubernetes/crd/kubernetes_test.go index 25557beb1..cb9d87408 100644 --- a/pkg/provider/kubernetes/crd/kubernetes_test.go +++ b/pkg/provider/kubernetes/crd/kubernetes_test.go @@ -4,14 +4,16 @@ import ( "context" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/tls" "github.com/stretchr/testify/assert" ) var _ provider.Provider = (*Provider)(nil) +func Int(v int) *int { return &v } + func TestLoadIngressRouteTCPs(t *testing.T) { testCases := []struct { desc string @@ -671,7 +673,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -720,7 +722,7 @@ func TestLoadIngressRoutes(t *testing.T) { }, Services: map[string]*dynamic.Service{ "default/test2.route-23c7f4c450289ee29016": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -770,7 +772,7 @@ func TestLoadIngressRoutes(t *testing.T) { }, Services: map[string]*dynamic.Service{ "default/test2.route-23c7f4c450289ee29016": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -812,7 +814,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -825,7 +827,7 @@ func TestLoadIngressRoutes(t *testing.T) { }, }, "default/test.route-77c62dfe9517144aeeaa": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -843,7 +845,7 @@ func TestLoadIngressRoutes(t *testing.T) { }, }, { - desc: "One ingress Route with two different services, their servers will merge", + desc: "One ingress Route with two different services", paths: []string{"services.yml", "with_two_services.yml"}, expected: &dynamic.Configuration{ TLS: &dynamic.TLSConfiguration{}, @@ -863,7 +865,21 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-77c62dfe9517144aeeaa": { - LoadBalancer: &dynamic.LoadBalancerService{ + Weighted: &dynamic.WeightedRoundRobin{ + Services: []dynamic.WRRService{ + { + Name: "default/test.route-77c62dfe9517144aeeaa-whoami-80", + Weight: func(i int) *int { return &i }(1), + }, + { + Name: "default/test.route-77c62dfe9517144aeeaa-whoami2-8080", + Weight: func(i int) *int { return &i }(1), + }, + }, + }, + }, + "default/test.route-77c62dfe9517144aeeaa-whoami-80": { + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -871,6 +887,77 @@ func TestLoadIngressRoutes(t *testing.T) { { URL: "http://10.10.0.2:80", }, + }, + PassHostHeader: true, + }, + }, + "default/test.route-77c62dfe9517144aeeaa-whoami2-8080": { + LoadBalancer: &dynamic.ServersLoadBalancer{ + Servers: []dynamic.Server{ + { + URL: "http://10.10.0.3:8080", + }, + { + URL: "http://10.10.0.4:8080", + }, + }, + PassHostHeader: true, + }, + }, + }, + }, + }, + }, + { + desc: "One ingress Route with two different services, with weights", + paths: []string{"services.yml", "with_two_services_weight.yml"}, + expected: &dynamic.Configuration{ + TLS: &dynamic.TLSConfiguration{}, + TCP: &dynamic.TCPConfiguration{ + Routers: map[string]*dynamic.TCPRouter{}, + Services: map[string]*dynamic.TCPService{}, + }, + HTTP: &dynamic.HTTPConfiguration{ + Routers: map[string]*dynamic.Router{ + "default/test.route-77c62dfe9517144aeeaa": { + EntryPoints: []string{"web"}, + Service: "default/test.route-77c62dfe9517144aeeaa", + Rule: "Host(`foo.com`) && PathPrefix(`/foo`)", + Priority: 12, + }, + }, + Middlewares: map[string]*dynamic.Middleware{}, + Services: map[string]*dynamic.Service{ + "default/test.route-77c62dfe9517144aeeaa": { + Weighted: &dynamic.WeightedRoundRobin{ + Services: []dynamic.WRRService{ + { + Name: "default/test.route-77c62dfe9517144aeeaa-whoami-80", + Weight: Int(10), + }, + { + Name: "default/test.route-77c62dfe9517144aeeaa-whoami2-8080", + Weight: Int(0), + }, + }, + }, + }, + "default/test.route-77c62dfe9517144aeeaa-whoami-80": { + LoadBalancer: &dynamic.ServersLoadBalancer{ + Servers: []dynamic.Server{ + { + URL: "http://10.10.0.1:80", + }, + { + URL: "http://10.10.0.2:80", + }, + }, + PassHostHeader: true, + }, + }, + "default/test.route-77c62dfe9517144aeeaa-whoami2-8080": { + LoadBalancer: &dynamic.ServersLoadBalancer{ + Servers: []dynamic.Server{ { URL: "http://10.10.0.3:8080", }, @@ -981,7 +1068,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1039,7 +1126,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1097,7 +1184,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1154,7 +1241,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1200,7 +1287,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1246,7 +1333,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1284,7 +1371,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://10.10.0.1:80", @@ -1321,13 +1408,13 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { - URL: "https://10.10.0.5:443", + URL: "https://10.10.0.5:8443", }, { - URL: "https://10.10.0.6:443", + URL: "https://10.10.0.6:8443", }, }, PassHostHeader: true, @@ -1358,7 +1445,7 @@ func TestLoadIngressRoutes(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "default/test.route-6b204d94623b3df4370c": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "https://10.10.0.7:8443", diff --git a/pkg/provider/kubernetes/crd/traefik/v1alpha1/ingressroute.go b/pkg/provider/kubernetes/crd/traefik/v1alpha1/ingressroute.go index ac7eb32e3..bf6074039 100644 --- a/pkg/provider/kubernetes/crd/traefik/v1alpha1/ingressroute.go +++ b/pkg/provider/kubernetes/crd/traefik/v1alpha1/ingressroute.go @@ -49,6 +49,7 @@ type Service struct { Scheme string `json:"scheme,omitempty"` HealthCheck *HealthCheck `json:"healthCheck,omitempty"` Strategy string `json:"strategy,omitempty"` + Weight *int `json:"weight,omitempty"` } // MiddlewareRef is a ref to the Middleware resources. diff --git a/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go b/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go index eeb4b9d06..c01f12c99 100644 --- a/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go +++ b/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go @@ -1,7 +1,7 @@ package v1alpha1 import ( - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) diff --git a/pkg/provider/kubernetes/crd/traefik/v1alpha1/zz_generated.deepcopy.go b/pkg/provider/kubernetes/crd/traefik/v1alpha1/zz_generated.deepcopy.go index 502a1d854..047f0fcaa 100644 --- a/pkg/provider/kubernetes/crd/traefik/v1alpha1/zz_generated.deepcopy.go +++ b/pkg/provider/kubernetes/crd/traefik/v1alpha1/zz_generated.deepcopy.go @@ -395,6 +395,11 @@ func (in *Service) DeepCopyInto(out *Service) { *out = new(HealthCheck) (*in).DeepCopyInto(*out) } + if in.Weight != nil { + in, out := &in.Weight, &out.Weight + *out = new(int) + **out = **in + } return } diff --git a/pkg/provider/kubernetes/ingress/client.go b/pkg/provider/kubernetes/ingress/client.go index 18b7321f1..18725c964 100644 --- a/pkg/provider/kubernetes/ingress/client.go +++ b/pkg/provider/kubernetes/ingress/client.go @@ -6,7 +6,7 @@ import ( "io/ioutil" "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" corev1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" kubeerror "k8s.io/apimachinery/pkg/api/errors" diff --git a/pkg/provider/kubernetes/ingress/client_mock_test.go b/pkg/provider/kubernetes/ingress/client_mock_test.go index 1b5cc49cb..5acf5f5ab 100644 --- a/pkg/provider/kubernetes/ingress/client_mock_test.go +++ b/pkg/provider/kubernetes/ingress/client_mock_test.go @@ -4,7 +4,7 @@ import ( "fmt" "io/ioutil" - "github.com/containous/traefik/pkg/provider/kubernetes/k8s" + "github.com/containous/traefik/v2/pkg/provider/kubernetes/k8s" corev1 "k8s.io/api/core/v1" extensionsv1beta1 "k8s.io/api/extensions/v1beta1" v1beta12 "k8s.io/api/extensions/v1beta1" diff --git a/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_endpoint.yml b/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_endpoint.yml index 3719a0777..2c5387099 100644 --- a/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_endpoint.yml +++ b/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_endpoint.yml @@ -8,8 +8,8 @@ subsets: - addresses: - ip: 10.10.0.1 ports: - - port: 443 + - port: 8443 - addresses: - ip: 10.21.0.1 ports: - - port: 443 + - port: 8443 diff --git a/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_service.yml b/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_service.yml index 078a79689..f26256b02 100644 --- a/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_service.yml +++ b/pkg/provider/kubernetes/ingress/fixtures/Ingress-with-a-basic-rule-on-one-path-with-https-(port-==-443)_service.yml @@ -7,4 +7,5 @@ metadata: spec: ports: - port: 443 + targetPort: 8443 clusterIp: 10.0.0.1 diff --git a/pkg/provider/kubernetes/ingress/kubernetes.go b/pkg/provider/kubernetes/ingress/kubernetes.go index 1b3dd8c77..8f17bf174 100644 --- a/pkg/provider/kubernetes/ingress/kubernetes.go +++ b/pkg/provider/kubernetes/ingress/kubernetes.go @@ -12,12 +12,12 @@ import ( "strings" "time" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/job" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/tls" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/job" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/tls" corev1 "k8s.io/api/core/v1" "k8s.io/api/extensions/v1beta1" "k8s.io/apimachinery/pkg/labels" @@ -216,7 +216,7 @@ func loadService(client Client, namespace string, backend v1beta1.IngressBackend } protocol := "http" - if port == 443 || strings.HasPrefix(portName, "https") { + if portSpec.Port == 443 || strings.HasPrefix(portName, "https") { protocol = "https" } @@ -229,7 +229,7 @@ func loadService(client Client, namespace string, backend v1beta1.IngressBackend } return &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: servers, PassHostHeader: true, }, @@ -323,6 +323,15 @@ func (p *Provider) loadConfigurationFromIngresses(ctx context.Context, client Cl Service: serviceName, } + if len(ingress.Spec.TLS) > 0 { + // TLS enabled for this ingress, add TLS router + conf.HTTP.Routers[strings.Replace(rule.Host, ".", "-", -1)+p.Path+"-tls"] = &dynamic.Router{ + Rule: strings.Join(rules, " && "), + Service: serviceName, + TLS: &dynamic.RouterTLSConfig{}, + } + + } conf.HTTP.Services[serviceName] = service } err := p.updateIngressStatus(ingress, client) diff --git a/pkg/provider/kubernetes/ingress/kubernetes_test.go b/pkg/provider/kubernetes/ingress/kubernetes_test.go index c9d434e2c..bc20a25b1 100644 --- a/pkg/provider/kubernetes/ingress/kubernetes_test.go +++ b/pkg/provider/kubernetes/ingress/kubernetes_test.go @@ -8,9 +8,9 @@ import ( "strings" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/tls" "github.com/stretchr/testify/assert" corev1 "k8s.io/api/core/v1" "k8s.io/api/extensions/v1beta1" @@ -50,7 +50,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -84,7 +84,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -118,7 +118,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -148,7 +148,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -177,7 +177,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/example-com/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -208,7 +208,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -242,7 +242,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -276,7 +276,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -317,7 +317,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -362,7 +362,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -375,7 +375,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, }, "testing/service2/8082": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -428,7 +428,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "default-backend": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -458,7 +458,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -488,7 +488,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/tchouk": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -518,7 +518,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/tchouk": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -552,7 +552,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/tchouk": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -565,7 +565,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, }, "testing/service1/carotte": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -599,7 +599,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/tchouk": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -612,7 +612,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, }, "toto/service1/tchouk": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -664,7 +664,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/8080": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -688,10 +688,15 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { Rule: "Host(`example.com`)", Service: "testing/example-com/80", }, + "example-com-tls": { + Rule: "Host(`example.com`)", + Service: "testing/example-com/80", + TLS: &dynamic.RouterTLSConfig{}, + }, }, Services: map[string]*dynamic.Service{ "testing/example-com/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -728,14 +733,14 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/443": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { - URL: "https://10.10.0.1:443", + URL: "https://10.10.0.1:8443", }, { - URL: "https://10.21.0.1:443", + URL: "https://10.21.0.1:8443", }, }, }, @@ -758,7 +763,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/8443": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -789,7 +794,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/8443": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -820,7 +825,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "default-backend": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { @@ -850,7 +855,7 @@ func TestLoadConfigurationFromIngresses(t *testing.T) { }, Services: map[string]*dynamic.Service{ "testing/service1/80": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ PassHostHeader: true, Servers: []dynamic.Server{ { diff --git a/pkg/provider/kubernetes/k8s/parser.go b/pkg/provider/kubernetes/k8s/parser.go index 0c4ae4cd1..b154872fe 100644 --- a/pkg/provider/kubernetes/k8s/parser.go +++ b/pkg/provider/kubernetes/k8s/parser.go @@ -5,7 +5,7 @@ import ( "regexp" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/scheme" ) diff --git a/pkg/provider/marathon/config.go b/pkg/provider/marathon/config.go index 43ce3016d..3f9adfebe 100644 --- a/pkg/provider/marathon/config.go +++ b/pkg/provider/marathon/config.go @@ -9,11 +9,11 @@ import ( "strconv" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/label" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/provider/constraints" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/label" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/provider/constraints" "github.com/gambol99/go-marathon" ) @@ -98,7 +98,7 @@ func (p *Provider) buildServiceConfiguration(ctx context.Context, app marathon.A if len(conf.Services) == 0 { conf.Services = make(map[string]*dynamic.Service) - lb := &dynamic.LoadBalancerService{} + lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() conf.Services[appName] = &dynamic.Service{ LoadBalancer: lb, diff --git a/pkg/provider/marathon/config_test.go b/pkg/provider/marathon/config_test.go index 83ce1e89a..296490f08 100644 --- a/pkg/provider/marathon/config_test.go +++ b/pkg/provider/marathon/config_test.go @@ -5,7 +5,7 @@ import ( "math" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/gambol99/go-marathon" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -56,7 +56,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "app": {LoadBalancer: &dynamic.LoadBalancerService{ + "app": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -110,7 +110,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "app": {LoadBalancer: &dynamic.LoadBalancerService{ + "app": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -156,7 +156,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, Services: map[string]*dynamic.Service{ - "app": {LoadBalancer: &dynamic.LoadBalancerService{ + "app": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -200,7 +200,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "Service1": {LoadBalancer: &dynamic.LoadBalancerService{ + "Service1": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:8080", @@ -249,7 +249,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "Service1": {LoadBalancer: &dynamic.LoadBalancerService{ + "Service1": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:8080", @@ -300,7 +300,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "foo": {LoadBalancer: &dynamic.LoadBalancerService{ + "foo": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:8080", @@ -308,7 +308,7 @@ func TestBuildConfiguration(t *testing.T) { }, PassHostHeader: true, }}, - "bar": {LoadBalancer: &dynamic.LoadBalancerService{ + "bar": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:8081", @@ -343,7 +343,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -382,7 +382,7 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ - "Service1": {LoadBalancer: &dynamic.LoadBalancerService{ + "Service1": {LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -420,7 +420,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -451,7 +451,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -495,7 +495,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -529,7 +529,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -539,7 +539,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "Service2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -595,13 +595,13 @@ func TestBuildConfiguration(t *testing.T) { appID("/app"), appPorts(80, 81), withTasks(localhostTask(taskPorts(80, 81))), - withLabel("traefik.http.middlewares.Middleware1.maxconn.amount", "42"), + withLabel("traefik.http.middlewares.Middleware1.inflightreq.amount", "42"), ), application( appID("/app2"), appPorts(80, 81), withTasks(localhostTask(taskPorts(80, 81))), - withLabel("traefik.http.middlewares.Middleware1.maxconn.amount", "42"), + withLabel("traefik.http.middlewares.Middleware1.inflightreq.amount", "42"), )), expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ @@ -621,15 +621,17 @@ func TestBuildConfiguration(t *testing.T) { }, Middlewares: map[string]*dynamic.Middleware{ "Middleware1": { - MaxConn: &dynamic.MaxConn{ - Amount: 42, - ExtractorFunc: "request.host", + InFlightReq: &dynamic.InFlightReq{ + Amount: 42, + SourceCriterion: &dynamic.SourceCriterion{ + RequestHost: true, + }, }, }, }, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -639,7 +641,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "app2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -659,13 +661,13 @@ func TestBuildConfiguration(t *testing.T) { appID("/app"), appPorts(80, 81), withTasks(localhostTask(taskPorts(80, 81))), - withLabel("traefik.http.middlewares.Middleware1.maxconn.amount", "42"), + withLabel("traefik.http.middlewares.Middleware1.inflightreq.amount", "42"), ), application( appID("/app2"), appPorts(80, 81), withTasks(localhostTask(taskPorts(80, 81))), - withLabel("traefik.http.middlewares.Middleware1.maxconn.amount", "41"), + withLabel("traefik.http.middlewares.Middleware1.inflightreq.amount", "41"), )), expected: &dynamic.Configuration{ TCP: &dynamic.TCPConfiguration{ @@ -686,7 +688,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -696,7 +698,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "app2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -734,7 +736,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -744,7 +746,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "app2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -789,7 +791,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -830,7 +832,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -840,7 +842,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "app2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -877,7 +879,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -915,7 +917,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "h2c://localhost:90", @@ -948,7 +950,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -958,7 +960,7 @@ func TestBuildConfiguration(t *testing.T) { }, }, "Service2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:8080", @@ -1123,7 +1125,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -1161,7 +1163,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -1198,7 +1200,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "a_b_app": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", @@ -1362,7 +1364,7 @@ func TestBuildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "bar": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://localhost:80", diff --git a/pkg/provider/marathon/fake_client_test.go b/pkg/provider/marathon/fake_client_test.go index 86b671081..978f5d57c 100644 --- a/pkg/provider/marathon/fake_client_test.go +++ b/pkg/provider/marathon/fake_client_test.go @@ -3,7 +3,7 @@ package marathon import ( "errors" - "github.com/containous/traefik/pkg/provider/marathon/mocks" + "github.com/containous/traefik/v2/pkg/provider/marathon/mocks" "github.com/gambol99/go-marathon" "github.com/stretchr/testify/mock" ) diff --git a/pkg/provider/marathon/label.go b/pkg/provider/marathon/label.go index 3dba526db..eb7773ed6 100644 --- a/pkg/provider/marathon/label.go +++ b/pkg/provider/marathon/label.go @@ -3,7 +3,7 @@ package marathon import ( "math" - "github.com/containous/traefik/pkg/config/label" + "github.com/containous/traefik/v2/pkg/config/label" "github.com/gambol99/go-marathon" ) diff --git a/pkg/provider/marathon/marathon.go b/pkg/provider/marathon/marathon.go index 379d61d57..adef44ab4 100644 --- a/pkg/provider/marathon/marathon.go +++ b/pkg/provider/marathon/marathon.go @@ -9,13 +9,13 @@ import ( "text/template" "time" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/job" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/types" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/job" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/types" "github.com/gambol99/go-marathon" "github.com/sirupsen/logrus" ) diff --git a/pkg/provider/marathon/readiness.go b/pkg/provider/marathon/readiness.go index af1228ae6..1d462115f 100644 --- a/pkg/provider/marathon/readiness.go +++ b/pkg/provider/marathon/readiness.go @@ -3,7 +3,7 @@ package marathon import ( "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/gambol99/go-marathon" ) diff --git a/pkg/provider/provider.go b/pkg/provider/provider.go index e9c1b64ed..df7d65734 100644 --- a/pkg/provider/provider.go +++ b/pkg/provider/provider.go @@ -1,8 +1,8 @@ package provider import ( - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/safe" ) // Provider defines methods of a provider. diff --git a/pkg/provider/rancher/config.go b/pkg/provider/rancher/config.go index 08c48406a..4d6f63a13 100644 --- a/pkg/provider/rancher/config.go +++ b/pkg/provider/rancher/config.go @@ -7,11 +7,11 @@ import ( "net" "strings" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/label" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/provider/constraints" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/label" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/provider/constraints" ) func (p *Provider) buildConfiguration(ctx context.Context, services []rancherData) *dynamic.Configuration { @@ -96,7 +96,7 @@ func (p *Provider) buildServiceConfiguration(ctx context.Context, service ranche if len(configuration.Services) == 0 { configuration.Services = make(map[string]*dynamic.Service) - lb := &dynamic.LoadBalancerService{} + lb := &dynamic.ServersLoadBalancer{} lb.SetDefaults() configuration.Services[serviceName] = &dynamic.Service{ LoadBalancer: lb, @@ -183,7 +183,7 @@ func (p *Provider) addServerTCP(ctx context.Context, service rancherData, loadBa } -func (p *Provider) addServers(ctx context.Context, service rancherData, loadBalancer *dynamic.LoadBalancerService) error { +func (p *Provider) addServers(ctx context.Context, service rancherData, loadBalancer *dynamic.ServersLoadBalancer) error { log.FromContext(ctx).Debugf("Trying to add servers for service %s \n", service.Name) serverPort := getLBServerPort(loadBalancer) @@ -216,7 +216,7 @@ func (p *Provider) addServers(ctx context.Context, service rancherData, loadBala return nil } -func getLBServerPort(loadBalancer *dynamic.LoadBalancerService) string { +func getLBServerPort(loadBalancer *dynamic.ServersLoadBalancer) string { if loadBalancer != nil && len(loadBalancer.Servers) > 0 { return loadBalancer.Servers[0].Port } diff --git a/pkg/provider/rancher/config_test.go b/pkg/provider/rancher/config_test.go index 7a180260c..31fb29ddc 100644 --- a/pkg/provider/rancher/config_test.go +++ b/pkg/provider/rancher/config_test.go @@ -4,7 +4,7 @@ import ( "context" "testing" - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -43,7 +43,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -95,7 +95,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -105,7 +105,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Test2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.2:80", @@ -157,7 +157,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -170,7 +170,7 @@ func Test_buildConfiguration(t *testing.T) { }, }, "Test2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://128.0.0.1:80", @@ -214,7 +214,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -302,7 +302,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -372,7 +372,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -425,7 +425,7 @@ func Test_buildConfiguration(t *testing.T) { }, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -467,7 +467,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Test": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", @@ -652,7 +652,7 @@ func Test_buildConfiguration(t *testing.T) { Middlewares: map[string]*dynamic.Middleware{}, Services: map[string]*dynamic.Service{ "Service1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:80", diff --git a/pkg/provider/rancher/label.go b/pkg/provider/rancher/label.go index bd42ff51c..bf4749f0d 100644 --- a/pkg/provider/rancher/label.go +++ b/pkg/provider/rancher/label.go @@ -1,7 +1,7 @@ package rancher import ( - "github.com/containous/traefik/pkg/config/label" + "github.com/containous/traefik/v2/pkg/config/label" ) type configuration struct { diff --git a/pkg/provider/rancher/rancher.go b/pkg/provider/rancher/rancher.go index 8d1c118a5..f69d0cbde 100644 --- a/pkg/provider/rancher/rancher.go +++ b/pkg/provider/rancher/rancher.go @@ -6,12 +6,12 @@ import ( "text/template" "time" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/job" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/job" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" rancher "github.com/rancher/go-rancher-metadata/metadata" ) diff --git a/pkg/provider/rest/rest.go b/pkg/provider/rest/rest.go index 175e89dbd..8c3c082a6 100644 --- a/pkg/provider/rest/rest.go +++ b/pkg/provider/rest/rest.go @@ -6,11 +6,11 @@ import ( "io/ioutil" "net/http" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/gorilla/mux" "github.com/unrolled/render" ) diff --git a/pkg/responsemodifiers/headers.go b/pkg/responsemodifiers/headers.go index c7eaa8ee3..403785eea 100644 --- a/pkg/responsemodifiers/headers.go +++ b/pkg/responsemodifiers/headers.go @@ -3,8 +3,8 @@ package responsemodifiers import ( "net/http" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/middlewares/headers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/middlewares/headers" "github.com/unrolled/secure" ) diff --git a/pkg/responsemodifiers/log.go b/pkg/responsemodifiers/log.go index fb2e2316e..b9ae3639f 100644 --- a/pkg/responsemodifiers/log.go +++ b/pkg/responsemodifiers/log.go @@ -3,7 +3,7 @@ package responsemodifiers import ( "context" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/sirupsen/logrus" ) diff --git a/pkg/responsemodifiers/response_modifier.go b/pkg/responsemodifiers/response_modifier.go index e12bddf9c..507627d69 100644 --- a/pkg/responsemodifiers/response_modifier.go +++ b/pkg/responsemodifiers/response_modifier.go @@ -4,7 +4,7 @@ import ( "context" "net/http" - "github.com/containous/traefik/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/runtime" ) // NewBuilder creates a builder. diff --git a/pkg/responsemodifiers/response_modifier_test.go b/pkg/responsemodifiers/response_modifier_test.go index de48fc4b3..79c1f1132 100644 --- a/pkg/responsemodifiers/response_modifier_test.go +++ b/pkg/responsemodifiers/response_modifier_test.go @@ -6,9 +6,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/middlewares/headers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/middlewares/headers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/rules/rules.go b/pkg/rules/rules.go index 36458f4f7..441c4b668 100644 --- a/pkg/rules/rules.go +++ b/pkg/rules/rules.go @@ -5,9 +5,9 @@ import ( "net/http" "strings" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares/requestdecorator" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares/requestdecorator" + "github.com/gorilla/mux" "github.com/vulcand/predicate" ) diff --git a/pkg/rules/rules_test.go b/pkg/rules/rules_test.go index 3f459f2a2..3b44a4cc9 100644 --- a/pkg/rules/rules_test.go +++ b/pkg/rules/rules_test.go @@ -5,9 +5,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/middlewares/requestdecorator" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/middlewares/requestdecorator" + "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/safe/routine.go b/pkg/safe/routine.go index d9e213166..83f33b872 100644 --- a/pkg/safe/routine.go +++ b/pkg/safe/routine.go @@ -6,8 +6,8 @@ import ( "runtime/debug" "sync" - "github.com/cenkalti/backoff" - "github.com/containous/traefik/pkg/log" + "github.com/cenkalti/backoff/v3" + "github.com/containous/traefik/v2/pkg/log" ) type routine struct { @@ -59,12 +59,23 @@ func (p *Pool) GoCtx(goroutine routineCtx) { p.routinesCtx = append(p.routinesCtx, goroutine) p.waitGroup.Add(1) Go(func() { + defer p.waitGroup.Done() goroutine(p.ctx) - p.waitGroup.Done() }) p.lock.Unlock() } +// addGo adds a recoverable goroutine, and can be stopped with stop chan +func (p *Pool) addGo(goroutine func(stop chan bool)) { + p.lock.Lock() + newRoutine := routine{ + goroutine: goroutine, + stop: make(chan bool, 1), + } + p.routines = append(p.routines, newRoutine) + p.lock.Unlock() +} + // Go starts a recoverable goroutine, and can be stopped with stop chan func (p *Pool) Go(goroutine func(stop chan bool)) { p.lock.Lock() @@ -75,8 +86,8 @@ func (p *Pool) Go(goroutine func(stop chan bool)) { p.routines = append(p.routines, newRoutine) p.waitGroup.Add(1) Go(func() { + defer p.waitGroup.Done() goroutine(newRoutine.stop) - p.waitGroup.Done() }) p.lock.Unlock() } @@ -112,16 +123,16 @@ func (p *Pool) Start() { p.waitGroup.Add(1) p.routines[i].stop = make(chan bool, 1) Go(func() { + defer p.waitGroup.Done() p.routines[i].goroutine(p.routines[i].stop) - p.waitGroup.Done() }) } for _, routine := range p.routinesCtx { p.waitGroup.Add(1) Go(func() { + defer p.waitGroup.Done() routine(p.ctx) - p.waitGroup.Done() }) } } diff --git a/pkg/safe/routine_test.go b/pkg/safe/routine_test.go index deaa3fc66..d44d03f58 100644 --- a/pkg/safe/routine_test.go +++ b/pkg/safe/routine_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/cenkalti/backoff" + "github.com/cenkalti/backoff/v3" ) func TestNewPoolContext(t *testing.T) { @@ -173,6 +173,73 @@ func TestPoolStartWithStopChan(t *testing.T) { } } +func TestPoolCleanupWithGoPanicking(t *testing.T) { + testRoutine := func(stop chan bool) { + panic("BOOM") + } + + testCtxRoutine := func(ctx context.Context) { + panic("BOOM") + } + + testCases := []struct { + desc string + fn func(*Pool) + }{ + { + desc: "Go()", + fn: func(p *Pool) { + p.Go(testRoutine) + }, + }, + { + desc: "addGo() and Start()", + fn: func(p *Pool) { + p.addGo(testRoutine) + p.Start() + }, + }, + { + desc: "GoCtx()", + fn: func(p *Pool) { + p.GoCtx(testCtxRoutine) + }, + }, + { + desc: "AddGoCtx() and Start()", + fn: func(p *Pool) { + p.AddGoCtx(testCtxRoutine) + p.Start() + }, + }, + } + + for _, test := range testCases { + test := test + t.Run(test.desc, func(t *testing.T) { + p := NewPool(context.Background()) + + timer := time.NewTimer(500 * time.Millisecond) + defer timer.Stop() + + test.fn(p) + + testDone := make(chan bool, 1) + go func() { + p.Cleanup() + testDone <- true + }() + + select { + case <-timer.C: + t.Fatalf("Pool.Cleanup() did not complete in time with a panicking goroutine") + case <-testDone: + return + } + }) + } +} + func TestGoroutineRecover(t *testing.T) { // if recover fails the test will panic Go(func() { diff --git a/pkg/server/aggregator.go b/pkg/server/aggregator.go index c00255ec3..7ae5d6c2e 100644 --- a/pkg/server/aggregator.go +++ b/pkg/server/aggregator.go @@ -1,10 +1,10 @@ package server import ( - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/server/internal" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/tls" ) func mergeConfiguration(configurations dynamic.Configurations) dynamic.Configuration { diff --git a/pkg/server/aggregator_test.go b/pkg/server/aggregator_test.go index 98e92166f..9bfb1310d 100644 --- a/pkg/server/aggregator_test.go +++ b/pkg/server/aggregator_test.go @@ -3,8 +3,8 @@ package server import ( "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/tls" "github.com/stretchr/testify/assert" ) diff --git a/pkg/server/cookie/cookie.go b/pkg/server/cookie/cookie.go index b1d0e28ee..632763a8f 100644 --- a/pkg/server/cookie/cookie.go +++ b/pkg/server/cookie/cookie.go @@ -5,7 +5,7 @@ import ( "fmt" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) const cookieNameLength = 6 diff --git a/pkg/server/internal/provider.go b/pkg/server/internal/provider.go index 3750d339a..c8e9a53e6 100644 --- a/pkg/server/internal/provider.go +++ b/pkg/server/internal/provider.go @@ -4,7 +4,7 @@ import ( "context" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) type contextKey int diff --git a/pkg/server/middleware/middlewares.go b/pkg/server/middleware/middlewares.go index a887d2854..4fd747780 100644 --- a/pkg/server/middleware/middlewares.go +++ b/pkg/server/middleware/middlewares.go @@ -8,26 +8,27 @@ import ( "strings" "github.com/containous/alice" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/middlewares/addprefix" - "github.com/containous/traefik/pkg/middlewares/auth" - "github.com/containous/traefik/pkg/middlewares/buffering" - "github.com/containous/traefik/pkg/middlewares/chain" - "github.com/containous/traefik/pkg/middlewares/circuitbreaker" - "github.com/containous/traefik/pkg/middlewares/compress" - "github.com/containous/traefik/pkg/middlewares/customerrors" - "github.com/containous/traefik/pkg/middlewares/headers" - "github.com/containous/traefik/pkg/middlewares/ipwhitelist" - "github.com/containous/traefik/pkg/middlewares/maxconnection" - "github.com/containous/traefik/pkg/middlewares/passtlsclientcert" - "github.com/containous/traefik/pkg/middlewares/redirect" - "github.com/containous/traefik/pkg/middlewares/replacepath" - "github.com/containous/traefik/pkg/middlewares/replacepathregex" - "github.com/containous/traefik/pkg/middlewares/retry" - "github.com/containous/traefik/pkg/middlewares/stripprefix" - "github.com/containous/traefik/pkg/middlewares/stripprefixregex" - "github.com/containous/traefik/pkg/middlewares/tracing" - "github.com/containous/traefik/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/middlewares/addprefix" + "github.com/containous/traefik/v2/pkg/middlewares/auth" + "github.com/containous/traefik/v2/pkg/middlewares/buffering" + "github.com/containous/traefik/v2/pkg/middlewares/chain" + "github.com/containous/traefik/v2/pkg/middlewares/circuitbreaker" + "github.com/containous/traefik/v2/pkg/middlewares/compress" + "github.com/containous/traefik/v2/pkg/middlewares/customerrors" + "github.com/containous/traefik/v2/pkg/middlewares/headers" + "github.com/containous/traefik/v2/pkg/middlewares/inflightreq" + "github.com/containous/traefik/v2/pkg/middlewares/ipwhitelist" + "github.com/containous/traefik/v2/pkg/middlewares/passtlsclientcert" + "github.com/containous/traefik/v2/pkg/middlewares/ratelimiter" + "github.com/containous/traefik/v2/pkg/middlewares/redirect" + "github.com/containous/traefik/v2/pkg/middlewares/replacepath" + "github.com/containous/traefik/v2/pkg/middlewares/replacepathregex" + "github.com/containous/traefik/v2/pkg/middlewares/retry" + "github.com/containous/traefik/v2/pkg/middlewares/stripprefix" + "github.com/containous/traefik/v2/pkg/middlewares/stripprefixregex" + "github.com/containous/traefik/v2/pkg/middlewares/tracing" + "github.com/containous/traefik/v2/pkg/server/internal" ) type middlewareStackType int @@ -122,7 +123,7 @@ func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) ( } // Buffering - if config.Buffering != nil && config.MaxConn.Amount != 0 { + if config.Buffering != nil && config.InFlightReq.Amount != 0 { if middleware != nil { return nil, badConf } @@ -211,13 +212,13 @@ func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) ( } } - // MaxConn - if config.MaxConn != nil && config.MaxConn.Amount != 0 { + // InFlightReq + if config.InFlightReq != nil && config.InFlightReq.Amount != 0 { if middleware != nil { return nil, badConf } middleware = func(next http.Handler) (http.Handler, error) { - return maxconnection.New(ctx, next, *config.MaxConn, middlewareName) + return inflightreq.New(ctx, next, *config.InFlightReq, middlewareName) } } @@ -231,16 +232,15 @@ func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) ( } } - // TODO: disable temporarily (rateLimit) // RateLimit - // if config.RateLimit != nil { - // if middleware != nil { - // return nil, badConf - // } - // middleware = func(next http.Handler) (http.Handler, error) { - // return ratelimiter.New(ctx, next, *config.RateLimit, middlewareName) - // } - // } + if config.RateLimit != nil { + if middleware != nil { + return nil, badConf + } + middleware = func(next http.Handler) (http.Handler, error) { + return ratelimiter.New(ctx, next, *config.RateLimit, middlewareName) + } + } // RedirectRegex if config.RedirectRegex != nil { diff --git a/pkg/server/middleware/middlewares_test.go b/pkg/server/middleware/middlewares_test.go index 5da03c335..a3d855c44 100644 --- a/pkg/server/middleware/middlewares_test.go +++ b/pkg/server/middleware/middlewares_test.go @@ -7,9 +7,9 @@ import ( "net/http/httptest" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/server/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/server/roundtripper.go b/pkg/server/roundtripper.go index f5a99f61f..165476029 100644 --- a/pkg/server/roundtripper.go +++ b/pkg/server/roundtripper.go @@ -8,9 +8,9 @@ import ( "net/http" "time" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - traefiktls "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + traefiktls "github.com/containous/traefik/v2/pkg/tls" "golang.org/x/net/http2" ) diff --git a/pkg/server/router/route_appender_aggregator.go b/pkg/server/router/route_appender_aggregator.go index 80bb02583..71702a6d6 100644 --- a/pkg/server/router/route_appender_aggregator.go +++ b/pkg/server/router/route_appender_aggregator.go @@ -4,13 +4,13 @@ import ( "context" "github.com/containous/alice" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/api" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/metrics" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/api" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/metrics" + "github.com/containous/traefik/v2/pkg/types" + "github.com/gorilla/mux" ) // chainBuilder The contract of the middleware builder diff --git a/pkg/server/router/route_appender_aggregator_test.go b/pkg/server/router/route_appender_aggregator_test.go index 7e948262c..ffc9c9d6f 100644 --- a/pkg/server/router/route_appender_aggregator_test.go +++ b/pkg/server/router/route_appender_aggregator_test.go @@ -7,9 +7,9 @@ import ( "testing" "github.com/containous/alice" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/ping" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/ping" + "github.com/gorilla/mux" "github.com/stretchr/testify/assert" ) diff --git a/pkg/server/router/route_appender_factory.go b/pkg/server/router/route_appender_factory.go index 2391fea79..7831e3b34 100644 --- a/pkg/server/router/route_appender_factory.go +++ b/pkg/server/router/route_appender_factory.go @@ -3,11 +3,11 @@ package router import ( "context" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/provider/acme" - "github.com/containous/traefik/pkg/server/middleware" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/provider/acme" + "github.com/containous/traefik/v2/pkg/server/middleware" + "github.com/containous/traefik/v2/pkg/types" ) // NewRouteAppenderFactory Creates a new RouteAppenderFactory diff --git a/pkg/server/router/router.go b/pkg/server/router/router.go index 6f69e0e6e..9b08cff95 100644 --- a/pkg/server/router/router.go +++ b/pkg/server/router/router.go @@ -6,16 +6,16 @@ import ( "net/http" "github.com/containous/alice" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/middlewares/recovery" - "github.com/containous/traefik/pkg/middlewares/tracing" - "github.com/containous/traefik/pkg/responsemodifiers" - "github.com/containous/traefik/pkg/rules" - "github.com/containous/traefik/pkg/server/internal" - "github.com/containous/traefik/pkg/server/middleware" - "github.com/containous/traefik/pkg/server/service" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/middlewares/recovery" + "github.com/containous/traefik/v2/pkg/middlewares/tracing" + "github.com/containous/traefik/v2/pkg/responsemodifiers" + "github.com/containous/traefik/v2/pkg/rules" + "github.com/containous/traefik/v2/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/server/middleware" + "github.com/containous/traefik/v2/pkg/server/service" ) const ( diff --git a/pkg/server/router/router_test.go b/pkg/server/router/router_test.go index 21a475aa9..1ff4c43f4 100644 --- a/pkg/server/router/router_test.go +++ b/pkg/server/router/router_test.go @@ -8,15 +8,15 @@ import ( "strings" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/middlewares/requestdecorator" - "github.com/containous/traefik/pkg/responsemodifiers" - "github.com/containous/traefik/pkg/server/middleware" - "github.com/containous/traefik/pkg/server/service" - "github.com/containous/traefik/pkg/testhelpers" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/middlewares/requestdecorator" + "github.com/containous/traefik/v2/pkg/responsemodifiers" + "github.com/containous/traefik/v2/pkg/server/middleware" + "github.com/containous/traefik/v2/pkg/server/service" + "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -48,7 +48,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -85,7 +85,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -108,7 +108,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -132,7 +132,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -173,7 +173,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -213,7 +213,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -236,7 +236,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-2": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -260,7 +260,7 @@ func TestRouterManager_Get(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service@provider-1": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -306,7 +306,7 @@ func TestRouterManager_Get(t *testing.T) { Middlewares: test.middlewaresConfig, }, }) - serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil) + serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager) responseModifierFactory := responsemodifiers.NewBuilder(rtConf.Middlewares) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, responseModifierFactory) @@ -355,7 +355,7 @@ func TestAccessLog(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -383,7 +383,7 @@ func TestAccessLog(t *testing.T) { }, serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -407,7 +407,7 @@ func TestAccessLog(t *testing.T) { Middlewares: test.middlewaresConfig, }, }) - serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil) + serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager) responseModifierFactory := responsemodifiers.NewBuilder(rtConf.Middlewares) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, responseModifierFactory) @@ -448,7 +448,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "No error", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1:8085", @@ -482,7 +482,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "One router with wrong rule", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -509,7 +509,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "All router with wrong rule", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -536,7 +536,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "Router with unknown service", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -579,7 +579,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "Router with middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -619,7 +619,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "Router with unknown middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -650,7 +650,7 @@ func TestRuntimeConfiguration(t *testing.T) { desc: "Router with broken middleware", serviceConfig: map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://127.0.0.1", @@ -693,7 +693,7 @@ func TestRuntimeConfiguration(t *testing.T) { Middlewares: test.middlewareConfig, }, }) - serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil) + serviceManager := service.NewManager(rtConf.Services, http.DefaultTransport, nil, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager) responseModifierFactory := responsemodifiers.NewBuilder(map[string]*runtime.MiddlewareInfo{}) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, responseModifierFactory) @@ -749,7 +749,7 @@ func BenchmarkRouterServe(b *testing.B) { } serviceConfig := map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server.URL, @@ -767,7 +767,7 @@ func BenchmarkRouterServe(b *testing.B) { Middlewares: map[string]*dynamic.Middleware{}, }, }) - serviceManager := service.NewManager(rtConf.Services, &staticTransport{res}, nil) + serviceManager := service.NewManager(rtConf.Services, &staticTransport{res}, nil, nil) middlewaresBuilder := middleware.NewBuilder(rtConf.Middlewares, serviceManager) responseModifierFactory := responsemodifiers.NewBuilder(rtConf.Middlewares) routerManager := NewManager(rtConf, serviceManager, middlewaresBuilder, responseModifierFactory) @@ -793,7 +793,7 @@ func BenchmarkService(b *testing.B) { serviceConfig := map[string]*dynamic.Service{ "foo-service": { - LoadBalancer: &dynamic.LoadBalancerService{ + LoadBalancer: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "tchouck", @@ -808,7 +808,7 @@ func BenchmarkService(b *testing.B) { Services: serviceConfig, }, }) - serviceManager := service.NewManager(rtConf.Services, &staticTransport{res}, nil) + serviceManager := service.NewManager(rtConf.Services, &staticTransport{res}, nil, nil) w := httptest.NewRecorder() req := testhelpers.MustNewRequest(http.MethodGet, "http://foo.bar/", nil) diff --git a/pkg/server/router/tcp/router.go b/pkg/server/router/tcp/router.go index e60d8995e..bf4931695 100644 --- a/pkg/server/router/tcp/router.go +++ b/pkg/server/router/tcp/router.go @@ -7,13 +7,13 @@ import ( "fmt" "net/http" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/rules" - "github.com/containous/traefik/pkg/server/internal" - tcpservice "github.com/containous/traefik/pkg/server/service/tcp" - "github.com/containous/traefik/pkg/tcp" - traefiktls "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/rules" + "github.com/containous/traefik/v2/pkg/server/internal" + tcpservice "github.com/containous/traefik/v2/pkg/server/service/tcp" + "github.com/containous/traefik/v2/pkg/tcp" + traefiktls "github.com/containous/traefik/v2/pkg/tls" ) // NewManager Creates a new Manager diff --git a/pkg/server/router/tcp/router_test.go b/pkg/server/router/tcp/router_test.go index cb4c66640..86fb882c6 100644 --- a/pkg/server/router/tcp/router_test.go +++ b/pkg/server/router/tcp/router_test.go @@ -4,10 +4,10 @@ import ( "context" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/server/service/tcp" - "github.com/containous/traefik/pkg/tls" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/server/service/tcp" + "github.com/containous/traefik/v2/pkg/tls" "github.com/stretchr/testify/assert" ) diff --git a/pkg/server/server.go b/pkg/server/server.go index 99e925e07..59dca31b3 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -9,20 +9,20 @@ import ( "sync" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/metrics" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/middlewares/requestdecorator" - "github.com/containous/traefik/pkg/provider" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/server/middleware" - "github.com/containous/traefik/pkg/tls" - "github.com/containous/traefik/pkg/tracing" - "github.com/containous/traefik/pkg/tracing/jaeger" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/metrics" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/middlewares/requestdecorator" + "github.com/containous/traefik/v2/pkg/provider" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/server/middleware" + "github.com/containous/traefik/v2/pkg/tls" + "github.com/containous/traefik/v2/pkg/tracing" + "github.com/containous/traefik/v2/pkg/tracing/jaeger" + "github.com/containous/traefik/v2/pkg/types" ) // Server is the reverse-proxy/load-balancer engine diff --git a/pkg/server/server_configuration.go b/pkg/server/server_configuration.go index 84009edc5..cc9acc707 100644 --- a/pkg/server/server_configuration.go +++ b/pkg/server/server_configuration.go @@ -8,23 +8,23 @@ import ( "time" "github.com/containous/alice" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/metrics" - "github.com/containous/traefik/pkg/middlewares/accesslog" - metricsmiddleware "github.com/containous/traefik/pkg/middlewares/metrics" - "github.com/containous/traefik/pkg/middlewares/requestdecorator" - "github.com/containous/traefik/pkg/middlewares/tracing" - "github.com/containous/traefik/pkg/responsemodifiers" - "github.com/containous/traefik/pkg/server/middleware" - "github.com/containous/traefik/pkg/server/router" - routertcp "github.com/containous/traefik/pkg/server/router/tcp" - "github.com/containous/traefik/pkg/server/service" - "github.com/containous/traefik/pkg/server/service/tcp" - tcpCore "github.com/containous/traefik/pkg/tcp" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/metrics" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + metricsmiddleware "github.com/containous/traefik/v2/pkg/middlewares/metrics" + "github.com/containous/traefik/v2/pkg/middlewares/requestdecorator" + "github.com/containous/traefik/v2/pkg/middlewares/tracing" + "github.com/containous/traefik/v2/pkg/responsemodifiers" + "github.com/containous/traefik/v2/pkg/server/middleware" + "github.com/containous/traefik/v2/pkg/server/router" + routertcp "github.com/containous/traefik/v2/pkg/server/router/tcp" + "github.com/containous/traefik/v2/pkg/server/service" + "github.com/containous/traefik/v2/pkg/server/service/tcp" + tcpCore "github.com/containous/traefik/v2/pkg/tcp" "github.com/eapache/channels" + "github.com/gorilla/mux" "github.com/sirupsen/logrus" ) @@ -97,7 +97,7 @@ func (s *Server) createTCPRouters(ctx context.Context, configuration *runtime.Co // createHTTPHandlers returns, for the given configuration and entryPoints, the HTTP handlers for non-TLS connections, and for the TLS ones. the given configuration must not be nil. its fields will get mutated. func (s *Server) createHTTPHandlers(ctx context.Context, configuration *runtime.Configuration, entryPoints []string) (map[string]http.Handler, map[string]http.Handler) { - serviceManager := service.NewManager(configuration.Services, s.defaultRoundTripper, s.metricsRegistry) + serviceManager := service.NewManager(configuration.Services, s.defaultRoundTripper, s.metricsRegistry, s.routinesPool) middlewaresBuilder := middleware.NewBuilder(configuration.Middlewares, serviceManager) responseModifierFactory := responsemodifiers.NewBuilder(configuration.Middlewares) routerManager := router.NewManager(configuration, serviceManager, middlewaresBuilder, responseModifierFactory) diff --git a/pkg/server/server_configuration_test.go b/pkg/server/server_configuration_test.go index 9d12b725c..732529f8e 100644 --- a/pkg/server/server_configuration_test.go +++ b/pkg/server/server_configuration_test.go @@ -7,10 +7,10 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - th "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + th "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" ) diff --git a/pkg/server/server_entrypoint_tcp.go b/pkg/server/server_entrypoint_tcp.go index 98a56800e..17dbc5c81 100644 --- a/pkg/server/server_entrypoint_tcp.go +++ b/pkg/server/server_entrypoint_tcp.go @@ -8,14 +8,14 @@ import ( "sync" "time" - "github.com/armon/go-proxyproto" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/ip" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/middlewares" - "github.com/containous/traefik/pkg/middlewares/forwardedheaders" - "github.com/containous/traefik/pkg/safe" - "github.com/containous/traefik/pkg/tcp" + proxyprotocol "github.com/c0va23/go-proxyprotocol" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/ip" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/middlewares" + "github.com/containous/traefik/v2/pkg/middlewares/forwardedheaders" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/tcp" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) @@ -240,10 +240,9 @@ func buildProxyProtocolListener(ctx context.Context, entryPoint *static.EntryPoi log.FromContext(ctx).Infof("Enabling ProxyProtocol for trusted IPs %v", entryPoint.ProxyProtocol.TrustedIPs) - return &proxyproto.Listener{ - Listener: listener, - SourceCheck: sourceCheck, - }, nil + return proxyprotocol.NewDefaultListener(listener). + WithSourceChecker(sourceCheck). + WithLogger(log.FromContext(ctx)), nil } func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.Listener, error) { diff --git a/pkg/server/server_entrypoint_tcp_test.go b/pkg/server/server_entrypoint_tcp_test.go index 041ecdcfd..525cea4f9 100644 --- a/pkg/server/server_entrypoint_tcp_test.go +++ b/pkg/server/server_entrypoint_tcp_test.go @@ -8,9 +8,9 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/static" - "github.com/containous/traefik/pkg/tcp" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/static" + "github.com/containous/traefik/v2/pkg/tcp" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/server/server_signals.go b/pkg/server/server_signals.go index 63bf9d5c0..a1411dc65 100644 --- a/pkg/server/server_signals.go +++ b/pkg/server/server_signals.go @@ -6,7 +6,7 @@ import ( "os/signal" "syscall" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) func (s *Server) configureSignals() { diff --git a/pkg/server/server_test.go b/pkg/server/server_test.go index 4756a197e..868e282be 100644 --- a/pkg/server/server_test.go +++ b/pkg/server/server_test.go @@ -7,11 +7,11 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/config/static" - th "github.com/containous/traefik/pkg/testhelpers" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/config/static" + th "github.com/containous/traefik/v2/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/types" "github.com/stretchr/testify/assert" ) @@ -199,7 +199,7 @@ func TestServerResponseEmptyBackend(t *testing.T) { th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar", - th.WithStickiness("test")), + th.WithSticky("test")), ), ) }, @@ -229,7 +229,7 @@ func TestServerResponseEmptyBackend(t *testing.T) { th.WithRule(routeRule)), ), th.WithLoadBalancerServices(th.WithService("bar", - th.WithStickiness("test")), + th.WithSticky("test")), ), ) }, diff --git a/pkg/server/service/loadbalancer/mirror/mirror.go b/pkg/server/service/loadbalancer/mirror/mirror.go new file mode 100644 index 000000000..593f20858 --- /dev/null +++ b/pkg/server/service/loadbalancer/mirror/mirror.go @@ -0,0 +1,104 @@ +package mirror + +import ( + "context" + "errors" + "net/http" + "sync" + + "github.com/containous/traefik/v2/pkg/safe" +) + +// Mirroring is an http.Handler that can mirror requests. +type Mirroring struct { + handler http.Handler + mirrorHandlers []*mirrorHandler + rw http.ResponseWriter + routinePool *safe.Pool + + lock sync.RWMutex + total uint64 +} + +// New returns a new instance of *Mirroring. +func New(handler http.Handler, pool *safe.Pool) *Mirroring { + return &Mirroring{ + routinePool: pool, + handler: handler, + rw: blackholeResponseWriter{}, + } +} + +func (m *Mirroring) inc() uint64 { + m.lock.Lock() + defer m.lock.Unlock() + m.total++ + return m.total +} + +type mirrorHandler struct { + http.Handler + percent int + + lock sync.RWMutex + count uint64 +} + +func (m *Mirroring) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + m.handler.ServeHTTP(rw, req) + + select { + case <-req.Context().Done(): + // No mirroring if request has been canceled during main handler ServeHTTP + return + default: + } + + m.routinePool.GoCtx(func(_ context.Context) { + total := m.inc() + for _, handler := range m.mirrorHandlers { + handler.lock.Lock() + if handler.count*100 < total*uint64(handler.percent) { + handler.count++ + handler.lock.Unlock() + // When a request served by m.handler is successful, req.Context will be cancelled, + // which would trigger a cancellation of the ongoing mirrored requests. + // Therefore, we give a new, non-cancellable context to each of the mirrored calls, + // so they can terminate by themselves. + handler.ServeHTTP(m.rw, req.WithContext(contextStopPropagation{req.Context()})) + } else { + handler.lock.Unlock() + } + } + }) +} + +// AddMirror adds an httpHandler to mirror to. +func (m *Mirroring) AddMirror(handler http.Handler, percent int) error { + if percent < 0 || percent >= 100 { + return errors.New("percent must be between 0 and 100") + } + m.mirrorHandlers = append(m.mirrorHandlers, &mirrorHandler{Handler: handler, percent: percent}) + return nil +} + +type blackholeResponseWriter struct{} + +func (b blackholeResponseWriter) Header() http.Header { + return http.Header{} +} + +func (b blackholeResponseWriter) Write(bytes []byte) (int, error) { + return len(bytes), nil +} + +func (b blackholeResponseWriter) WriteHeader(statusCode int) { +} + +type contextStopPropagation struct { + context.Context +} + +func (c contextStopPropagation) Done() <-chan struct{} { + return make(chan struct{}) +} diff --git a/pkg/server/service/loadbalancer/mirror/mirror_test.go b/pkg/server/service/loadbalancer/mirror/mirror_test.go new file mode 100644 index 000000000..fb2c516c5 --- /dev/null +++ b/pkg/server/service/loadbalancer/mirror/mirror_test.go @@ -0,0 +1,79 @@ +package mirror + +import ( + "context" + "net/http" + "net/http/httptest" + "sync/atomic" + "testing" + + "github.com/containous/traefik/v2/pkg/safe" + "github.com/stretchr/testify/assert" +) + +func TestMirroringOn100(t *testing.T) { + var countMirror1, countMirror2 int32 + handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.WriteHeader(http.StatusOK) + }) + pool := safe.NewPool(context.Background()) + mirror := New(handler, pool) + err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror1, 1) + }), 10) + assert.NoError(t, err) + + err = mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror2, 1) + }), 50) + assert.NoError(t, err) + + for i := 0; i < 100; i++ { + mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + } + + pool.Stop() + + val1 := atomic.LoadInt32(&countMirror1) + val2 := atomic.LoadInt32(&countMirror2) + assert.Equal(t, 10, int(val1)) + assert.Equal(t, 50, int(val2)) +} + +func TestMirroringOn10(t *testing.T) { + var countMirror1, countMirror2 int32 + handler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.WriteHeader(http.StatusOK) + }) + pool := safe.NewPool(context.Background()) + mirror := New(handler, pool) + err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror1, 1) + }), 10) + assert.NoError(t, err) + + err = mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + atomic.AddInt32(&countMirror2, 1) + }), 50) + assert.NoError(t, err) + + for i := 0; i < 10; i++ { + mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) + } + + pool.Stop() + + val1 := atomic.LoadInt32(&countMirror1) + val2 := atomic.LoadInt32(&countMirror2) + assert.Equal(t, 1, int(val1)) + assert.Equal(t, 5, int(val2)) +} + +func TestInvalidPercent(t *testing.T) { + mirror := New(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), safe.NewPool(context.Background())) + err := mirror.AddMirror(nil, -1) + assert.Error(t, err) + + err = mirror.AddMirror(nil, 101) + assert.Error(t, err) +} diff --git a/pkg/server/service/loadbalancer/wrr/wrr.go b/pkg/server/service/loadbalancer/wrr/wrr.go new file mode 100644 index 000000000..a805c66a9 --- /dev/null +++ b/pkg/server/service/loadbalancer/wrr/wrr.go @@ -0,0 +1,155 @@ +package wrr + +import ( + "fmt" + "net/http" + "sync" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" +) + +type namedHandler struct { + http.Handler + name string + weight int +} + +type stickyCookie struct { + name string + secure bool + httpOnly bool +} + +// New creates a new load balancer. +func New(sticky *dynamic.Sticky) *Balancer { + balancer := &Balancer{ + mutex: &sync.Mutex{}, + index: -1, + } + if sticky != nil && sticky.Cookie != nil { + balancer.stickyCookie = &stickyCookie{ + name: sticky.Cookie.Name, + secure: sticky.Cookie.Secure, + httpOnly: sticky.Cookie.HTTPOnly, + } + } + return balancer +} + +// Balancer is a WeightedRoundRobin load balancer. +type Balancer struct { + handlers []*namedHandler + mutex *sync.Mutex + // Current index (starts from -1) + index int + currentWeight int + stickyCookie *stickyCookie +} + +func (b *Balancer) maxWeight() int { + max := -1 + for _, s := range b.handlers { + if s.weight > max { + max = s.weight + } + } + return max +} + +func (b *Balancer) weightGcd() int { + divisor := -1 + for _, s := range b.handlers { + if divisor == -1 { + divisor = s.weight + } else { + divisor = gcd(divisor, s.weight) + } + } + return divisor +} + +func gcd(a, b int) int { + for b != 0 { + a, b = b, a%b + } + return a +} + +func (b *Balancer) nextServer() (*namedHandler, error) { + b.mutex.Lock() + defer b.mutex.Unlock() + + if len(b.handlers) == 0 { + return nil, fmt.Errorf("no servers in the pool") + } + + // The algo below may look messy, but is actually very simple + // it calculates the GCD and subtracts it on every iteration, what interleaves servers + // and allows us not to build an iterator every time we readjust weights + + // GCD across all enabled servers + gcd := b.weightGcd() + // Maximum weight across all enabled servers + max := b.maxWeight() + + for { + b.index = (b.index + 1) % len(b.handlers) + if b.index == 0 { + b.currentWeight -= gcd + if b.currentWeight <= 0 { + b.currentWeight = max + if b.currentWeight == 0 { + return nil, fmt.Errorf("all servers have 0 weight") + } + } + } + srv := b.handlers[b.index] + if srv.weight >= b.currentWeight { + log.WithoutContext().Debugf("Service Select: %s", srv.name) + return srv, nil + } + } +} + +func (b *Balancer) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if b.stickyCookie != nil { + cookie, err := req.Cookie(b.stickyCookie.name) + + if err != nil && err != http.ErrNoCookie { + log.WithoutContext().Warnf("Error while reading cookie: %v", err) + } + + if err == nil && cookie != nil { + for _, handler := range b.handlers { + if handler.name == cookie.Value { + handler.ServeHTTP(w, req) + return + } + } + } + } + + server, err := b.nextServer() + if err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError)+err.Error(), http.StatusInternalServerError) + return + } + + if b.stickyCookie != nil { + cookie := &http.Cookie{Name: b.stickyCookie.name, Value: server.name, Path: "/", HttpOnly: b.stickyCookie.httpOnly, Secure: b.stickyCookie.secure} + http.SetCookie(w, cookie) + } + + server.ServeHTTP(w, req) +} + +// AddService adds a handler. +// It is not thread safe with ServeHTTP. +func (b *Balancer) AddService(name string, handler http.Handler, weight *int) { + w := 1 + if weight != nil { + w = *weight + } + b.handlers = append(b.handlers, &namedHandler{Handler: handler, name: name, weight: w}) +} diff --git a/pkg/server/service/loadbalancer/wrr/wrr_test.go b/pkg/server/service/loadbalancer/wrr/wrr_test.go new file mode 100644 index 000000000..b2eb65e5a --- /dev/null +++ b/pkg/server/service/loadbalancer/wrr/wrr_test.go @@ -0,0 +1,115 @@ +package wrr + +import ( + "net/http" + "net/http/httptest" + "testing" + + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/stretchr/testify/assert" +) + +func Int(v int) *int { return &v } + +type responseRecorder struct { + *httptest.ResponseRecorder + save map[string]int +} + +func (r *responseRecorder) WriteHeader(statusCode int) { + r.save[r.Header().Get("server")]++ + r.ResponseRecorder.WriteHeader(statusCode) + +} + +func TestBalancer(t *testing.T) { + balancer := New(nil) + + balancer.AddService("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Header().Set("server", "first") + rw.WriteHeader(http.StatusOK) + }), Int(3)) + + balancer.AddService("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Header().Set("server", "second") + rw.WriteHeader(http.StatusOK) + }), Int(1)) + + recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} + for i := 0; i < 4; i++ { + balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + } + + assert.Equal(t, 3, recorder.save["first"]) + assert.Equal(t, 1, recorder.save["second"]) +} + +func TestBalancerNoService(t *testing.T) { + balancer := New(nil) + + recorder := httptest.NewRecorder() + balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + + assert.Equal(t, http.StatusInternalServerError, recorder.Result().StatusCode) +} + +func TestBalancerOneServerZeroWeight(t *testing.T) { + balancer := New(nil) + + balancer.AddService("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Header().Set("server", "first") + rw.WriteHeader(http.StatusOK) + }), Int(1)) + + balancer.AddService("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0)) + + recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} + for i := 0; i < 3; i++ { + balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + } + + assert.Equal(t, 3, recorder.save["first"]) +} + +func TestBalancerAllServersZeroWeight(t *testing.T) { + balancer := New(nil) + + balancer.AddService("test", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0)) + balancer.AddService("test2", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0)) + + recorder := httptest.NewRecorder() + balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + + assert.Equal(t, http.StatusInternalServerError, recorder.Result().StatusCode) +} + +func TestSticky(t *testing.T) { + balancer := New(&dynamic.Sticky{ + Cookie: &dynamic.Cookie{Name: "test"}, + }) + + balancer.AddService("first", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Header().Set("server", "first") + rw.WriteHeader(http.StatusOK) + }), Int(1)) + + balancer.AddService("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { + rw.Header().Set("server", "second") + rw.WriteHeader(http.StatusOK) + }), Int(2)) + + recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} + + req := httptest.NewRequest(http.MethodGet, "/", nil) + for i := 0; i < 3; i++ { + for _, cookie := range recorder.Result().Cookies() { + req.AddCookie(cookie) + } + recorder.ResponseRecorder = httptest.NewRecorder() + + balancer.ServeHTTP(recorder, req) + } + + assert.Equal(t, 0, recorder.save["first"]) + assert.Equal(t, 3, recorder.save["second"]) +} diff --git a/pkg/server/service/proxy.go b/pkg/server/service/proxy.go index 2c59c6475..a305fbb1d 100644 --- a/pkg/server/service/proxy.go +++ b/pkg/server/service/proxy.go @@ -10,9 +10,9 @@ import ( "net/url" "time" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/types" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/types" ) // StatusClientClosedRequest non-standard HTTP status code for client disconnection diff --git a/pkg/server/service/proxy_test.go b/pkg/server/service/proxy_test.go index 5201741ab..53d8b5d14 100644 --- a/pkg/server/service/proxy_test.go +++ b/pkg/server/service/proxy_test.go @@ -7,7 +7,7 @@ import ( "strings" "testing" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/testhelpers" ) type staticTransport struct { diff --git a/pkg/server/service/service.go b/pkg/server/service/service.go index 1a8fab5a6..1595d0452 100644 --- a/pkg/server/service/service.go +++ b/pkg/server/service/service.go @@ -2,24 +2,29 @@ package service import ( "context" + "errors" "fmt" "net/http" "net/http/httputil" "net/url" + "reflect" "time" "github.com/containous/alice" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/healthcheck" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/metrics" - "github.com/containous/traefik/pkg/middlewares/accesslog" - "github.com/containous/traefik/pkg/middlewares/emptybackendhandler" - metricsMiddle "github.com/containous/traefik/pkg/middlewares/metrics" - "github.com/containous/traefik/pkg/middlewares/pipelining" - "github.com/containous/traefik/pkg/server/cookie" - "github.com/containous/traefik/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/healthcheck" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/metrics" + "github.com/containous/traefik/v2/pkg/middlewares/accesslog" + "github.com/containous/traefik/v2/pkg/middlewares/emptybackendhandler" + metricsMiddle "github.com/containous/traefik/v2/pkg/middlewares/metrics" + "github.com/containous/traefik/v2/pkg/middlewares/pipelining" + "github.com/containous/traefik/v2/pkg/safe" + "github.com/containous/traefik/v2/pkg/server/cookie" + "github.com/containous/traefik/v2/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/server/service/loadbalancer/mirror" + "github.com/containous/traefik/v2/pkg/server/service/loadbalancer/wrr" "github.com/vulcand/oxy/roundrobin" ) @@ -29,8 +34,9 @@ const ( ) // NewManager creates a new Manager -func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper http.RoundTripper, metricsRegistry metrics.Registry) *Manager { +func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper http.RoundTripper, metricsRegistry metrics.Registry, routinePool *safe.Pool) *Manager { return &Manager{ + routinePool: routinePool, metricsRegistry: metricsRegistry, bufferPool: newBufferPool(), defaultRoundTripper: defaultRoundTripper, @@ -41,6 +47,7 @@ func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper htt // Manager The service manager type Manager struct { + routinePool *safe.Pool metricsRegistry metrics.Registry bufferPool httputil.BufferPool defaultRoundTripper http.RoundTripper @@ -60,27 +67,93 @@ func (m *Manager) BuildHTTP(rootCtx context.Context, serviceName string, respons return nil, fmt.Errorf("the service %q does not exist", serviceName) } - // TODO Should handle multiple service types - // FIXME Check if the service is declared multiple times with different types - if conf.LoadBalancer == nil { - sErr := fmt.Errorf("the service %q doesn't have any load balancer", serviceName) - conf.AddError(sErr, true) - return nil, sErr + value := reflect.ValueOf(*conf.Service) + var count int + for i := 0; i < value.NumField(); i++ { + if !value.Field(i).IsNil() { + count++ + } + } + if count > 1 { + return nil, errors.New("cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") } - lb, err := m.getLoadBalancerServiceHandler(ctx, serviceName, conf.LoadBalancer, responseModifier) - if err != nil { - conf.AddError(err, true) - return nil, err + var lb http.Handler + + switch { + case conf.LoadBalancer != nil: + var err error + lb, err = m.getLoadBalancerServiceHandler(ctx, serviceName, conf.LoadBalancer, responseModifier) + if err != nil { + conf.AddError(err, true) + return nil, err + } + case conf.Weighted != nil: + var err error + lb, err = m.getLoadBalancerWRRServiceHandler(ctx, serviceName, conf.Weighted, responseModifier) + if err != nil { + conf.AddError(err, true) + return nil, err + } + case conf.Mirroring != nil: + var err error + lb, err = m.getLoadBalancerMirrorServiceHandler(ctx, serviceName, conf.Mirroring, responseModifier) + if err != nil { + conf.AddError(err, true) + return nil, err + } + default: + sErr := fmt.Errorf("the service %q does not have any type defined", serviceName) + conf.AddError(sErr, true) + return nil, sErr } return lb, nil } +func (m *Manager) getLoadBalancerMirrorServiceHandler(ctx context.Context, serviceName string, config *dynamic.Mirroring, responseModifier func(*http.Response) error) (http.Handler, error) { + serviceHandler, err := m.BuildHTTP(ctx, config.Service, responseModifier) + if err != nil { + return nil, err + } + + handler := mirror.New(serviceHandler, m.routinePool) + for _, mirrorConfig := range config.Mirrors { + mirrorHandler, err := m.BuildHTTP(ctx, mirrorConfig.Name, responseModifier) + if err != nil { + return nil, err + } + + err = handler.AddMirror(mirrorHandler, mirrorConfig.Percent) + if err != nil { + return nil, err + } + } + return handler, nil +} + +func (m *Manager) getLoadBalancerWRRServiceHandler(ctx context.Context, serviceName string, config *dynamic.WeightedRoundRobin, responseModifier func(*http.Response) error) (http.Handler, error) { + // TODO Handle accesslog and metrics with multiple service name + if config.Sticky != nil && config.Sticky.Cookie != nil { + config.Sticky.Cookie.Name = cookie.GetName(config.Sticky.Cookie.Name, serviceName) + } + + balancer := wrr.New(config.Sticky) + for _, service := range config.Services { + serviceHandler, err := m.BuildHTTP(ctx, service.Name, responseModifier) + if err != nil { + return nil, err + } + + balancer.AddService(service.Name, serviceHandler, service.Weight) + } + return balancer, nil +} + func (m *Manager) getLoadBalancerServiceHandler( ctx context.Context, serviceName string, - service *dynamic.LoadBalancerService, + service *dynamic.ServersLoadBalancer, responseModifier func(*http.Response) error, ) (http.Handler, error) { fwd, err := buildProxy(service.PassHostHeader, service.ResponseForwarding, m.defaultRoundTripper, m.bufferPool, responseModifier) @@ -193,16 +266,16 @@ func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler } } -func (m *Manager) getLoadBalancer(ctx context.Context, serviceName string, service *dynamic.LoadBalancerService, fwd http.Handler) (healthcheck.BalancerHandler, error) { +func (m *Manager) getLoadBalancer(ctx context.Context, serviceName string, service *dynamic.ServersLoadBalancer, fwd http.Handler) (healthcheck.BalancerHandler, error) { logger := log.FromContext(ctx) logger.Debug("Creating load-balancer") var options []roundrobin.LBOption var cookieName string - if stickiness := service.Stickiness; stickiness != nil { - cookieName = cookie.GetName(stickiness.CookieName, serviceName) - opts := roundrobin.CookieOptions{HTTPOnly: stickiness.HTTPOnlyCookie, Secure: stickiness.SecureCookie} + if service.Sticky != nil && service.Sticky.Cookie != nil { + cookieName = cookie.GetName(service.Sticky.Cookie.Name, serviceName) + opts := roundrobin.CookieOptions{HTTPOnly: service.Sticky.Cookie.HTTPOnly, Secure: service.Sticky.Cookie.Secure} options = append(options, roundrobin.EnableStickySession(roundrobin.NewStickySessionWithOptions(cookieName, opts))) logger.Debugf("Sticky session cookie name: %v", cookieName) } diff --git a/pkg/server/service/service_test.go b/pkg/server/service/service_test.go index 9dd4344fd..c2bb707b7 100644 --- a/pkg/server/service/service_test.go +++ b/pkg/server/service/service_test.go @@ -7,10 +7,10 @@ import ( "strings" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/server/internal" - "github.com/containous/traefik/pkg/testhelpers" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/testhelpers" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -27,14 +27,14 @@ func TestGetLoadBalancer(t *testing.T) { testCases := []struct { desc string serviceName string - service *dynamic.LoadBalancerService + service *dynamic.ServersLoadBalancer fwd http.Handler expectError bool }{ { desc: "Fails when provided an invalid URL", serviceName: "test", - service: &dynamic.LoadBalancerService{ + service: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: ":", @@ -47,15 +47,15 @@ func TestGetLoadBalancer(t *testing.T) { { desc: "Succeeds when there are no servers", serviceName: "test", - service: &dynamic.LoadBalancerService{}, + service: &dynamic.ServersLoadBalancer{}, fwd: &MockForwarder{}, expectError: false, }, { - desc: "Succeeds when stickiness is set", + desc: "Succeeds when sticky.cookie is set", serviceName: "test", - service: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{}, + service: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, }, fwd: &MockForwarder{}, expectError: false, @@ -80,7 +80,7 @@ func TestGetLoadBalancer(t *testing.T) { } func TestGetLoadBalancerServiceHandler(t *testing.T) { - sm := NewManager(nil, http.DefaultTransport, nil) + sm := NewManager(nil, http.DefaultTransport, nil, nil) server1 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", "first") @@ -114,7 +114,7 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { testCases := []struct { desc string serviceName string - service *dynamic.LoadBalancerService + service *dynamic.ServersLoadBalancer responseModifier func(*http.Response) error expected []ExpectedResult @@ -122,7 +122,7 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "Load balances between the two servers", serviceName: "test", - service: &dynamic.LoadBalancerService{ + service: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: server1.URL, @@ -146,7 +146,7 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "StatusBadGateway when the server is not reachable", serviceName: "test", - service: &dynamic.LoadBalancerService{ + service: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{ { URL: "http://foo", @@ -162,7 +162,7 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "ServiceUnavailable when no servers are available", serviceName: "test", - service: &dynamic.LoadBalancerService{ + service: &dynamic.ServersLoadBalancer{ Servers: []dynamic.Server{}, }, expected: []ExpectedResult{ @@ -172,10 +172,10 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { }, }, { - desc: "Always call the same server when stickiness is true", + desc: "Always call the same server when sticky.cookie is true", serviceName: "test", - service: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{}, + service: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, Servers: []dynamic.Server{ { URL: server1.URL, @@ -199,8 +199,8 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "Sticky Cookie's options set correctly", serviceName: "test", - service: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{HTTPOnlyCookie: true, SecureCookie: true}, + service: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{HTTPOnly: true, Secure: true}}, Servers: []dynamic.Server{ { URL: server1.URL, @@ -219,8 +219,8 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "PassHost passes the host instead of the IP", serviceName: "test", - service: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{}, + service: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, PassHostHeader: true, Servers: []dynamic.Server{ { @@ -238,8 +238,8 @@ func TestGetLoadBalancerServiceHandler(t *testing.T) { { desc: "PassHost doesn't passe the host instead of the IP", serviceName: "test", - service: &dynamic.LoadBalancerService{ - Stickiness: &dynamic.Stickiness{}, + service: &dynamic.ServersLoadBalancer{ + Sticky: &dynamic.Sticky{Cookie: &dynamic.Cookie{}}, Servers: []dynamic.Server{ { URL: serverPassHostFalse.URL, @@ -297,7 +297,7 @@ func TestManager_Build(t *testing.T) { configs: map[string]*runtime.ServiceInfo{ "serviceName": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{}, + LoadBalancer: &dynamic.ServersLoadBalancer{}, }, }, }, @@ -308,7 +308,7 @@ func TestManager_Build(t *testing.T) { configs: map[string]*runtime.ServiceInfo{ "serviceName@provider-1": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{}, + LoadBalancer: &dynamic.ServersLoadBalancer{}, }, }, }, @@ -319,7 +319,7 @@ func TestManager_Build(t *testing.T) { configs: map[string]*runtime.ServiceInfo{ "serviceName@provider-1": { Service: &dynamic.Service{ - LoadBalancer: &dynamic.LoadBalancerService{}, + LoadBalancer: &dynamic.ServersLoadBalancer{}, }, }, }, @@ -332,7 +332,7 @@ func TestManager_Build(t *testing.T) { t.Run(test.desc, func(t *testing.T) { t.Parallel() - manager := NewManager(test.configs, http.DefaultTransport, nil) + manager := NewManager(test.configs, http.DefaultTransport, nil, nil) ctx := context.Background() if len(test.providerName) > 0 { @@ -345,4 +345,18 @@ func TestManager_Build(t *testing.T) { } } +func TestMultipleTypeOnBuildHTTP(t *testing.T) { + manager := NewManager(map[string]*runtime.ServiceInfo{ + "test@file": { + Service: &dynamic.Service{ + LoadBalancer: &dynamic.ServersLoadBalancer{}, + Weighted: &dynamic.WeightedRoundRobin{}, + }, + }, + }, http.DefaultTransport, nil, nil) + + _, err := manager.BuildHTTP(context.Background(), "test@file", nil) + assert.Error(t, err, "cannot create service: multi-types service not supported, consider declaring two different pieces of service instead") +} + // FIXME Add healthcheck tests diff --git a/pkg/server/service/tcp/service.go b/pkg/server/service/tcp/service.go index 59d159a11..e5311a7eb 100644 --- a/pkg/server/service/tcp/service.go +++ b/pkg/server/service/tcp/service.go @@ -5,10 +5,10 @@ import ( "fmt" "net" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/server/internal" - "github.com/containous/traefik/pkg/tcp" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/tcp" ) // Manager is the TCPHandlers factory diff --git a/pkg/server/service/tcp/service_test.go b/pkg/server/service/tcp/service_test.go index a4ec678d6..8d680f11f 100644 --- a/pkg/server/service/tcp/service_test.go +++ b/pkg/server/service/tcp/service_test.go @@ -4,9 +4,9 @@ import ( "context" "testing" - "github.com/containous/traefik/pkg/config/dynamic" - "github.com/containous/traefik/pkg/config/runtime" - "github.com/containous/traefik/pkg/server/internal" + "github.com/containous/traefik/v2/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/runtime" + "github.com/containous/traefik/v2/pkg/server/internal" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) diff --git a/pkg/tcp/proxy.go b/pkg/tcp/proxy.go index 0338508c6..76a20aa91 100644 --- a/pkg/tcp/proxy.go +++ b/pkg/tcp/proxy.go @@ -4,7 +4,7 @@ import ( "io" "net" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) // Proxy forwards a TCP request to a TCP service diff --git a/pkg/tcp/router.go b/pkg/tcp/router.go index dd7eb5020..7dc379373 100644 --- a/pkg/tcp/router.go +++ b/pkg/tcp/router.go @@ -9,7 +9,7 @@ import ( "net/http" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) // Router is a TCP router diff --git a/pkg/tcp/rr_load_balancer.go b/pkg/tcp/rr_load_balancer.go index 84fb63596..6187d5417 100644 --- a/pkg/tcp/rr_load_balancer.go +++ b/pkg/tcp/rr_load_balancer.go @@ -4,7 +4,7 @@ import ( "net" "sync" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) // RRLoadBalancer is a naive RoundRobin load balancer for TCP services diff --git a/pkg/tcp/switcher.go b/pkg/tcp/switcher.go index 9ff7e31d9..330fc993f 100644 --- a/pkg/tcp/switcher.go +++ b/pkg/tcp/switcher.go @@ -3,7 +3,7 @@ package tcp import ( "net" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/safe" ) // HandlerSwitcher is a TCP handler switcher diff --git a/pkg/testhelpers/config.go b/pkg/testhelpers/config.go index 6cfcbbb43..5f6c48165 100644 --- a/pkg/testhelpers/config.go +++ b/pkg/testhelpers/config.go @@ -1,7 +1,7 @@ package testhelpers import ( - "github.com/containous/traefik/pkg/config/dynamic" + "github.com/containous/traefik/v2/pkg/config/dynamic" ) // BuildConfiguration is a helper to create a configuration. @@ -50,11 +50,11 @@ func WithServiceName(serviceName string) func(*dynamic.Router) { } // WithLoadBalancerServices is a helper to create a configuration. -func WithLoadBalancerServices(opts ...func(service *dynamic.LoadBalancerService) string) func(*dynamic.HTTPConfiguration) { +func WithLoadBalancerServices(opts ...func(service *dynamic.ServersLoadBalancer) string) func(*dynamic.HTTPConfiguration) { return func(c *dynamic.HTTPConfiguration) { c.Services = make(map[string]*dynamic.Service) for _, opt := range opts { - b := &dynamic.LoadBalancerService{} + b := &dynamic.ServersLoadBalancer{} name := opt(b) c.Services[name] = &dynamic.Service{ LoadBalancer: b, @@ -64,8 +64,8 @@ func WithLoadBalancerServices(opts ...func(service *dynamic.LoadBalancerService) } // WithService is a helper to create a configuration. -func WithService(name string, opts ...func(*dynamic.LoadBalancerService)) func(*dynamic.LoadBalancerService) string { - return func(r *dynamic.LoadBalancerService) string { +func WithService(name string, opts ...func(*dynamic.ServersLoadBalancer)) func(*dynamic.ServersLoadBalancer) string { + return func(r *dynamic.ServersLoadBalancer) string { for _, opt := range opts { opt(r) } @@ -117,8 +117,8 @@ func WithRule(rule string) func(*dynamic.Router) { } // WithServers is a helper to create a configuration. -func WithServers(opts ...func(*dynamic.Server)) func(*dynamic.LoadBalancerService) { - return func(b *dynamic.LoadBalancerService) { +func WithServers(opts ...func(*dynamic.Server)) func(*dynamic.ServersLoadBalancer) { + return func(b *dynamic.ServersLoadBalancer) { for _, opt := range opts { server := dynamic.Server{} opt(&server) @@ -137,11 +137,11 @@ func WithServer(url string, opts ...func(*dynamic.Server)) func(*dynamic.Server) } } -// WithStickiness is a helper to create a configuration. -func WithStickiness(cookieName string) func(*dynamic.LoadBalancerService) { - return func(b *dynamic.LoadBalancerService) { - b.Stickiness = &dynamic.Stickiness{ - CookieName: cookieName, +// WithSticky is a helper to create a configuration. +func WithSticky(cookieName string) func(*dynamic.ServersLoadBalancer) { + return func(b *dynamic.ServersLoadBalancer) { + b.Sticky = &dynamic.Sticky{ + Cookie: &dynamic.Cookie{Name: cookieName}, } } } diff --git a/pkg/tls/certificate.go b/pkg/tls/certificate.go index 4b59fee49..7f739e38b 100644 --- a/pkg/tls/certificate.go +++ b/pkg/tls/certificate.go @@ -9,8 +9,8 @@ import ( "sort" "strings" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/tls/generate" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/tls/generate" ) var ( diff --git a/pkg/tls/certificate_store.go b/pkg/tls/certificate_store.go index 040d2b978..da16472b3 100644 --- a/pkg/tls/certificate_store.go +++ b/pkg/tls/certificate_store.go @@ -8,8 +8,8 @@ import ( "strings" "time" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/safe" "github.com/patrickmn/go-cache" ) diff --git a/pkg/tls/certificate_store_test.go b/pkg/tls/certificate_store_test.go index b67ac3cff..9ee0339b6 100644 --- a/pkg/tls/certificate_store_test.go +++ b/pkg/tls/certificate_store_test.go @@ -7,7 +7,7 @@ import ( "testing" "time" - "github.com/containous/traefik/pkg/safe" + "github.com/containous/traefik/v2/pkg/safe" "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" diff --git a/pkg/tls/generate/generate.go b/pkg/tls/generate/generate.go index 91d73a731..fd0744ade 100644 --- a/pkg/tls/generate/generate.go +++ b/pkg/tls/generate/generate.go @@ -85,7 +85,7 @@ func derCert(privKey *rsa.PrivateKey, expiration time.Time, domain string) ([]by NotBefore: time.Now(), NotAfter: expiration, - KeyUsage: x509.KeyUsageKeyEncipherment, + KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement | x509.KeyUsageDataEncipherment, BasicConstraintsValid: true, DNSNames: []string{domain}, } diff --git a/pkg/tls/tlsmanager.go b/pkg/tls/tlsmanager.go index 90914998b..27fdbb1eb 100644 --- a/pkg/tls/tlsmanager.go +++ b/pkg/tls/tlsmanager.go @@ -7,10 +7,10 @@ import ( "fmt" "sync" - "github.com/containous/traefik/pkg/log" - "github.com/containous/traefik/pkg/tls/generate" - "github.com/containous/traefik/pkg/types" - "github.com/go-acme/lego/challenge/tlsalpn01" + "github.com/containous/traefik/v2/pkg/log" + "github.com/containous/traefik/v2/pkg/tls/generate" + "github.com/containous/traefik/v2/pkg/types" + "github.com/go-acme/lego/v3/challenge/tlsalpn01" "github.com/sirupsen/logrus" ) diff --git a/pkg/tracing/datadog/datadog.go b/pkg/tracing/datadog/datadog.go index 466df2ca9..d297fe916 100644 --- a/pkg/tracing/datadog/datadog.go +++ b/pkg/tracing/datadog/datadog.go @@ -4,7 +4,7 @@ import ( "io" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/opentracing/opentracing-go" ddtracer "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/opentracer" datadog "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" diff --git a/pkg/tracing/haystack/haystack.go b/pkg/tracing/haystack/haystack.go index 19038fff9..aa48375de 100644 --- a/pkg/tracing/haystack/haystack.go +++ b/pkg/tracing/haystack/haystack.go @@ -6,7 +6,7 @@ import ( "time" "github.com/ExpediaDotCom/haystack-client-go" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/opentracing/opentracing-go" ) diff --git a/pkg/tracing/haystack/logger.go b/pkg/tracing/haystack/logger.go index f88089d5b..aa223fcb8 100644 --- a/pkg/tracing/haystack/logger.go +++ b/pkg/tracing/haystack/logger.go @@ -1,7 +1,7 @@ package haystack import ( - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) /*NullLogger does nothing*/ diff --git a/pkg/tracing/instana/instana.go b/pkg/tracing/instana/instana.go index 34df22f16..e2912bbdd 100644 --- a/pkg/tracing/instana/instana.go +++ b/pkg/tracing/instana/instana.go @@ -3,7 +3,7 @@ package instana import ( "io" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" instana "github.com/instana/go-sensor" "github.com/opentracing/opentracing-go" ) diff --git a/pkg/tracing/jaeger/jaeger.go b/pkg/tracing/jaeger/jaeger.go index 2c463adbf..ba8c702e0 100644 --- a/pkg/tracing/jaeger/jaeger.go +++ b/pkg/tracing/jaeger/jaeger.go @@ -4,7 +4,7 @@ import ( "fmt" "io" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/opentracing/opentracing-go" jaeger "github.com/uber/jaeger-client-go" jaegercli "github.com/uber/jaeger-client-go" diff --git a/pkg/tracing/jaeger/logger.go b/pkg/tracing/jaeger/logger.go index 6e6d8a439..2df321b8c 100644 --- a/pkg/tracing/jaeger/logger.go +++ b/pkg/tracing/jaeger/logger.go @@ -1,7 +1,7 @@ package jaeger import ( - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/sirupsen/logrus" ) diff --git a/pkg/tracing/operation_name.go b/pkg/tracing/operation_name.go index 8d0887a04..a076e4e45 100644 --- a/pkg/tracing/operation_name.go +++ b/pkg/tracing/operation_name.go @@ -5,7 +5,7 @@ import ( "fmt" "strings" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) // TraceNameHashLength defines the number of characters to use from the head of the generated hash. diff --git a/pkg/tracing/tracing.go b/pkg/tracing/tracing.go index c370c05b9..82d5f2226 100644 --- a/pkg/tracing/tracing.go +++ b/pkg/tracing/tracing.go @@ -7,7 +7,7 @@ import ( "io" "net/http" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/opentracing/opentracing-go" "github.com/opentracing/opentracing-go/ext" ) diff --git a/pkg/tracing/zipkin/zipkin.go b/pkg/tracing/zipkin/zipkin.go index 3d246be9f..52885ca4a 100644 --- a/pkg/tracing/zipkin/zipkin.go +++ b/pkg/tracing/zipkin/zipkin.go @@ -4,7 +4,7 @@ import ( "io" "time" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" "github.com/opentracing/opentracing-go" zipkin "github.com/openzipkin-contrib/zipkin-go-opentracing" ) diff --git a/pkg/types/route_appender.go b/pkg/types/route_appender.go index 01e24a3bf..3549bef5e 100644 --- a/pkg/types/route_appender.go +++ b/pkg/types/route_appender.go @@ -1,7 +1,7 @@ package types import ( - "github.com/containous/mux" + "github.com/gorilla/mux" ) // RouteAppender appends routes on a router (/api, /ping ...) diff --git a/pkg/types/tls.go b/pkg/types/tls.go index 492225003..2610345c0 100644 --- a/pkg/types/tls.go +++ b/pkg/types/tls.go @@ -8,7 +8,7 @@ import ( "io/ioutil" "os" - "github.com/containous/traefik/pkg/log" + "github.com/containous/traefik/v2/pkg/log" ) // ClientTLS holds TLS specific configurations as client diff --git a/pkg/version/version.go b/pkg/version/version.go index 386df6153..478c4f132 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -5,9 +5,9 @@ import ( "net/http" "net/url" - "github.com/containous/mux" - "github.com/containous/traefik/pkg/log" - "github.com/google/go-github/github" + "github.com/containous/traefik/v2/pkg/log" + "github.com/google/go-github/v27/github" + "github.com/gorilla/mux" goversion "github.com/hashicorp/go-version" "github.com/unrolled/render" ) diff --git a/script/binary b/script/binary index 40bf4f941..82c6ebe3b 100755 --- a/script/binary +++ b/script/binary @@ -28,7 +28,7 @@ fi # Build binaries # shellcheck disable=SC2086 CGO_ENABLED=0 GOGC=off go build ${FLAGS[*]} -ldflags "-s -w \ - -X github.com/containous/traefik/pkg/version.Version=$VERSION \ - -X github.com/containous/traefik/pkg/version.Codename=$CODENAME \ - -X github.com/containous/traefik/pkg/version.BuildDate=$DATE" \ + -X github.com/containous/traefik/pkg/v2/version.Version=$VERSION \ + -X github.com/containous/traefik/pkg/v2/version.Codename=$CODENAME \ + -X github.com/containous/traefik/pkg/v2/version.BuildDate=$DATE" \ -a -installsuffix nocgo -o dist/traefik ./cmd/traefik diff --git a/script/make.sh b/script/make.sh index cad63e6d4..6f670ff3b 100755 --- a/script/make.sh +++ b/script/make.sh @@ -1,6 +1,9 @@ #!/usr/bin/env bash set -e +export GO111MODULE=on +export GOPROXY=https://proxy.golang.org + # List of bundles to create when no argument is passed DEFAULT_BUNDLES=( generate diff --git a/script/prune-dep.sh b/script/prune-dep.sh deleted file mode 100755 index 2653b5adc..000000000 --- a/script/prune-dep.sh +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env bash - -set -o errexit -set -o pipefail -set -o nounset - -echo "Prune dependencies" - -find vendor -name '*_test.go' -exec rm {} \; - -find vendor -type f \( ! -iname 'licen[cs]e*' \ - -a ! -iname '*notice*' \ - -a ! -iname '*patent*' \ - -a ! -iname '*copying*' \ - -a ! -iname '*unlicense*' \ - -a ! -iname '*copyright*' \ - -a ! -iname '*copyleft*' \ - -a ! -iname '*legal*' \ - -a ! -iname 'disclaimer*' \ - -a ! -iname 'third-party*' \ - -a ! -iname 'thirdparty*' \ - -a ! -iname '*.go' \ - -a ! -iname '*.c' \ - -a ! -iname '*.s' \ - -a ! -iname '*.pl' \ - -a ! -iname '*.cc' \ - -a ! -iname '*.cpp' \ - -a ! -iname '*.cxx' \ - -a ! -iname '*.h' \ - -a ! -iname '*.hh' \ - -a ! -iname '*.hpp' \ - -a ! -iname '*.hxx' \ - -a ! -wholename 'vendor/k8s.io/code-generator/*' \ - -a ! -iname '*.s' \) -exec rm -f {} + - -find . -type d \( -iname '*Godeps*' \) -exec rm -rf {} + - -find vendor -type l \( ! -iname 'licen[cs]e*' \ - -a ! -iname '*notice*' \ - -a ! -iname '*patent*' \ - -a ! -iname '*copying*' \ - -a ! -iname '*unlicense*' \ - -a ! -iname '*copyright*' \ - -a ! -iname '*copyleft*' \ - -a ! -iname '*legal*' \ - -a ! -iname 'disclaimer*' \ - -a ! -iname 'third-party*' \ - -a ! -iname 'thirdparty*' \ - -a ! -iname '*.go' \ - -a ! -iname '*.c' \ - -a ! -iname '*.S' \ - -a ! -iname '*.cc' \ - -a ! -iname '*.cpp' \ - -a ! -iname '*.cxx' \ - -a ! -iname '*.h' \ - -a ! -iname '*.hh' \ - -a ! -iname '*.hpp' \ - -a ! -iname '*.hxx' \ - -a ! -iname '*.s' \) -exec rm -f {} + diff --git a/script/update-generated-crd-code.sh b/script/update-generated-crd-code.sh index b19eceb63..81dbee5ad 100755 --- a/script/update-generated-crd-code.sh +++ b/script/update-generated-crd-code.sh @@ -2,17 +2,27 @@ HACK_DIR="$( cd "$( dirname "${0}" )" && pwd -P)"; export HACK_DIR REPO_ROOT=${HACK_DIR}/.. +TRAEFIK_MODULE_VERSION=v2 + +rm -rf "${REPO_ROOT}"/vendor +go mod vendor +chmod +x "${REPO_ROOT}"/vendor/k8s.io/code-generator/*.sh "${REPO_ROOT}"/vendor/k8s.io/code-generator/generate-groups.sh \ all \ - github.com/containous/traefik/pkg/provider/kubernetes/crd/generated \ - github.com/containous/traefik/pkg/provider/kubernetes/crd \ + github.com/containous/traefik/${TRAEFIK_MODULE_VERSION}/pkg/provider/kubernetes/crd/generated \ + github.com/containous/traefik/${TRAEFIK_MODULE_VERSION}/pkg/provider/kubernetes/crd \ traefik:v1alpha1 \ --go-header-file "${HACK_DIR}"/boilerplate.go.tmpl \ "$@" deepcopy-gen \ ---input-dirs github.com/containous/traefik/pkg/config/dynamic \ ---input-dirs github.com/containous/traefik/pkg/tls \ ---input-dirs github.com/containous/traefik/pkg/types \ +--input-dirs github.com/containous/traefik/${TRAEFIK_MODULE_VERSION}/pkg/config/dynamic \ +--input-dirs github.com/containous/traefik/${TRAEFIK_MODULE_VERSION}/pkg/tls \ +--input-dirs github.com/containous/traefik/${TRAEFIK_MODULE_VERSION}/pkg/types \ +--output-package github.com/containous/traefik \ -O zz_generated.deepcopy --go-header-file "${HACK_DIR}"/boilerplate.go.tmpl + +cp -r "${REPO_ROOT}"/"${TRAEFIK_MODULE_VERSION:?}"/* "${REPO_ROOT}"; rm -rf "${REPO_ROOT}"/"${TRAEFIK_MODULE_VERSION:?}" + +rm -rf "${REPO_ROOT}"/vendor diff --git a/script/validate-vendor b/script/validate-vendor index 580ca7253..8c9b0815e 100755 --- a/script/validate-vendor +++ b/script/validate-vendor @@ -4,26 +4,11 @@ set -o pipefail set -o nounset SCRIPT_DIR="$( cd "$( dirname "${0}" )" && pwd -P)"; export SCRIPT_DIR -vendor_dir="./vendor/" -# We run dep install to and see if we have a diff afterwards -echo "checking ${vendor_dir} for unintentional changes..." +echo "checking go modules for unintentional changes..." -dep ensure -v -("${SCRIPT_DIR}"/prune-dep.sh) +go mod tidy +git diff --exit-code go.mod +git diff --exit-code go.sum -# Let see if the working directory is clean -diffs="$(git status --porcelain -- ${vendor_dir} 2>/dev/null)" -if [[ "$diffs" ]]; then - { - echo "The result of 'dep ensure' for vendor directory '${vendor_dir}' differs" - echo - echo "$diffs" - echo - echo 'Please vendor your package(s) with dep.' - echo - } >&2 - exit 2 -fi - -echo 'Congratulations! All vendoring changes are done the right way.' +echo 'Congratulations! All go modules changes are done the right way.' diff --git a/tools.go b/tools.go new file mode 100644 index 000000000..1185af9e3 --- /dev/null +++ b/tools.go @@ -0,0 +1,7 @@ +// +build tools + +package main + +import ( + _ "k8s.io/code-generator" +) diff --git a/vendor/cloud.google.com/go/LICENSE b/vendor/cloud.google.com/go/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/cloud.google.com/go/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/cloud.google.com/go/compute/metadata/metadata.go b/vendor/cloud.google.com/go/compute/metadata/metadata.go deleted file mode 100644 index e708c031b..000000000 --- a/vendor/cloud.google.com/go/compute/metadata/metadata.go +++ /dev/null @@ -1,437 +0,0 @@ -// Copyright 2014 Google Inc. All Rights Reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Package metadata provides access to Google Compute Engine (GCE) -// metadata and API service accounts. -// -// This package is a wrapper around the GCE metadata service, -// as documented at https://developers.google.com/compute/docs/metadata. -package metadata // import "cloud.google.com/go/compute/metadata" - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "net/url" - "os" - "runtime" - "strings" - "sync" - "time" - - "golang.org/x/net/context" - "golang.org/x/net/context/ctxhttp" -) - -const ( - // metadataIP is the documented metadata server IP address. - metadataIP = "169.254.169.254" - - // metadataHostEnv is the environment variable specifying the - // GCE metadata hostname. If empty, the default value of - // metadataIP ("169.254.169.254") is used instead. - // This is variable name is not defined by any spec, as far as - // I know; it was made up for the Go package. - metadataHostEnv = "GCE_METADATA_HOST" - - userAgent = "gcloud-golang/0.1" -) - -type cachedValue struct { - k string - trim bool - mu sync.Mutex - v string -} - -var ( - projID = &cachedValue{k: "project/project-id", trim: true} - projNum = &cachedValue{k: "project/numeric-project-id", trim: true} - instID = &cachedValue{k: "instance/id", trim: true} -) - -var ( - metaClient = &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - ResponseHeaderTimeout: 2 * time.Second, - }, - } - subscribeClient = &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 2 * time.Second, - KeepAlive: 30 * time.Second, - }).Dial, - }, - } -) - -// NotDefinedError is returned when requested metadata is not defined. -// -// The underlying string is the suffix after "/computeMetadata/v1/". -// -// This error is not returned if the value is defined to be the empty -// string. -type NotDefinedError string - -func (suffix NotDefinedError) Error() string { - return fmt.Sprintf("metadata: GCE metadata %q not defined", string(suffix)) -} - -// Get returns a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// -// If the GCE_METADATA_HOST environment variable is not defined, a default of -// 169.254.169.254 will be used instead. -// -// If the requested metadata is not defined, the returned error will -// be of type NotDefinedError. -func Get(suffix string) (string, error) { - val, _, err := getETag(metaClient, suffix) - return val, err -} - -// getETag returns a value from the metadata service as well as the associated -// ETag using the provided client. This func is otherwise equivalent to Get. -func getETag(client *http.Client, suffix string) (value, etag string, err error) { - // Using a fixed IP makes it very difficult to spoof the metadata service in - // a container, which is an important use-case for local testing of cloud - // deployments. To enable spoofing of the metadata service, the environment - // variable GCE_METADATA_HOST is first inspected to decide where metadata - // requests shall go. - host := os.Getenv(metadataHostEnv) - if host == "" { - // Using 169.254.169.254 instead of "metadata" here because Go - // binaries built with the "netgo" tag and without cgo won't - // know the search suffix for "metadata" is - // ".google.internal", and this IP address is documented as - // being stable anyway. - host = metadataIP - } - url := "http://" + host + "/computeMetadata/v1/" + suffix - req, _ := http.NewRequest("GET", url, nil) - req.Header.Set("Metadata-Flavor", "Google") - req.Header.Set("User-Agent", userAgent) - res, err := client.Do(req) - if err != nil { - return "", "", err - } - defer res.Body.Close() - if res.StatusCode == http.StatusNotFound { - return "", "", NotDefinedError(suffix) - } - if res.StatusCode != 200 { - return "", "", fmt.Errorf("status code %d trying to fetch %s", res.StatusCode, url) - } - all, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", err - } - return string(all), res.Header.Get("Etag"), nil -} - -func getTrimmed(suffix string) (s string, err error) { - s, err = Get(suffix) - s = strings.TrimSpace(s) - return -} - -func (c *cachedValue) get() (v string, err error) { - defer c.mu.Unlock() - c.mu.Lock() - if c.v != "" { - return c.v, nil - } - if c.trim { - v, err = getTrimmed(c.k) - } else { - v, err = Get(c.k) - } - if err == nil { - c.v = v - } - return -} - -var ( - onGCEOnce sync.Once - onGCE bool -) - -// OnGCE reports whether this process is running on Google Compute Engine. -func OnGCE() bool { - onGCEOnce.Do(initOnGCE) - return onGCE -} - -func initOnGCE() { - onGCE = testOnGCE() -} - -func testOnGCE() bool { - // The user explicitly said they're on GCE, so trust them. - if os.Getenv(metadataHostEnv) != "" { - return true - } - - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - resc := make(chan bool, 2) - - // Try two strategies in parallel. - // See https://github.com/GoogleCloudPlatform/google-cloud-go/issues/194 - go func() { - req, _ := http.NewRequest("GET", "http://"+metadataIP, nil) - req.Header.Set("User-Agent", userAgent) - res, err := ctxhttp.Do(ctx, metaClient, req) - if err != nil { - resc <- false - return - } - defer res.Body.Close() - resc <- res.Header.Get("Metadata-Flavor") == "Google" - }() - - go func() { - addrs, err := net.LookupHost("metadata.google.internal") - if err != nil || len(addrs) == 0 { - resc <- false - return - } - resc <- strsContains(addrs, metadataIP) - }() - - tryHarder := systemInfoSuggestsGCE() - if tryHarder { - res := <-resc - if res { - // The first strategy succeeded, so let's use it. - return true - } - // Wait for either the DNS or metadata server probe to - // contradict the other one and say we are running on - // GCE. Give it a lot of time to do so, since the system - // info already suggests we're running on a GCE BIOS. - timer := time.NewTimer(5 * time.Second) - defer timer.Stop() - select { - case res = <-resc: - return res - case <-timer.C: - // Too slow. Who knows what this system is. - return false - } - } - - // There's no hint from the system info that we're running on - // GCE, so use the first probe's result as truth, whether it's - // true or false. The goal here is to optimize for speed for - // users who are NOT running on GCE. We can't assume that - // either a DNS lookup or an HTTP request to a blackholed IP - // address is fast. Worst case this should return when the - // metaClient's Transport.ResponseHeaderTimeout or - // Transport.Dial.Timeout fires (in two seconds). - return <-resc -} - -// systemInfoSuggestsGCE reports whether the local system (without -// doing network requests) suggests that we're running on GCE. If this -// returns true, testOnGCE tries a bit harder to reach its metadata -// server. -func systemInfoSuggestsGCE() bool { - if runtime.GOOS != "linux" { - // We don't have any non-Linux clues available, at least yet. - return false - } - slurp, _ := ioutil.ReadFile("/sys/class/dmi/id/product_name") - name := strings.TrimSpace(string(slurp)) - return name == "Google" || name == "Google Compute Engine" -} - -// Subscribe subscribes to a value from the metadata service. -// The suffix is appended to "http://${GCE_METADATA_HOST}/computeMetadata/v1/". -// The suffix may contain query parameters. -// -// Subscribe calls fn with the latest metadata value indicated by the provided -// suffix. If the metadata value is deleted, fn is called with the empty string -// and ok false. Subscribe blocks until fn returns a non-nil error or the value -// is deleted. Subscribe returns the error value returned from the last call to -// fn, which may be nil when ok == false. -func Subscribe(suffix string, fn func(v string, ok bool) error) error { - const failedSubscribeSleep = time.Second * 5 - - // First check to see if the metadata value exists at all. - val, lastETag, err := getETag(subscribeClient, suffix) - if err != nil { - return err - } - - if err := fn(val, true); err != nil { - return err - } - - ok := true - if strings.ContainsRune(suffix, '?') { - suffix += "&wait_for_change=true&last_etag=" - } else { - suffix += "?wait_for_change=true&last_etag=" - } - for { - val, etag, err := getETag(subscribeClient, suffix+url.QueryEscape(lastETag)) - if err != nil { - if _, deleted := err.(NotDefinedError); !deleted { - time.Sleep(failedSubscribeSleep) - continue // Retry on other errors. - } - ok = false - } - lastETag = etag - - if err := fn(val, ok); err != nil || !ok { - return err - } - } -} - -// ProjectID returns the current instance's project ID string. -func ProjectID() (string, error) { return projID.get() } - -// NumericProjectID returns the current instance's numeric project ID. -func NumericProjectID() (string, error) { return projNum.get() } - -// InternalIP returns the instance's primary internal IP address. -func InternalIP() (string, error) { - return getTrimmed("instance/network-interfaces/0/ip") -} - -// ExternalIP returns the instance's primary external (public) IP address. -func ExternalIP() (string, error) { - return getTrimmed("instance/network-interfaces/0/access-configs/0/external-ip") -} - -// Hostname returns the instance's hostname. This will be of the form -// ".c..internal". -func Hostname() (string, error) { - return getTrimmed("instance/hostname") -} - -// InstanceTags returns the list of user-defined instance tags, -// assigned when initially creating a GCE instance. -func InstanceTags() ([]string, error) { - var s []string - j, err := Get("instance/tags") - if err != nil { - return nil, err - } - if err := json.NewDecoder(strings.NewReader(j)).Decode(&s); err != nil { - return nil, err - } - return s, nil -} - -// InstanceID returns the current VM's numeric instance ID. -func InstanceID() (string, error) { - return instID.get() -} - -// InstanceName returns the current VM's instance ID string. -func InstanceName() (string, error) { - host, err := Hostname() - if err != nil { - return "", err - } - return strings.Split(host, ".")[0], nil -} - -// Zone returns the current VM's zone, such as "us-central1-b". -func Zone() (string, error) { - zone, err := getTrimmed("instance/zone") - // zone is of the form "projects//zones/". - if err != nil { - return "", err - } - return zone[strings.LastIndex(zone, "/")+1:], nil -} - -// InstanceAttributes returns the list of user-defined attributes, -// assigned when initially creating a GCE VM instance. The value of an -// attribute can be obtained with InstanceAttributeValue. -func InstanceAttributes() ([]string, error) { return lines("instance/attributes/") } - -// ProjectAttributes returns the list of user-defined attributes -// applying to the project as a whole, not just this VM. The value of -// an attribute can be obtained with ProjectAttributeValue. -func ProjectAttributes() ([]string, error) { return lines("project/attributes/") } - -func lines(suffix string) ([]string, error) { - j, err := Get(suffix) - if err != nil { - return nil, err - } - s := strings.Split(strings.TrimSpace(j), "\n") - for i := range s { - s[i] = strings.TrimSpace(s[i]) - } - return s, nil -} - -// InstanceAttributeValue returns the value of the provided VM -// instance attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// InstanceAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func InstanceAttributeValue(attr string) (string, error) { - return Get("instance/attributes/" + attr) -} - -// ProjectAttributeValue returns the value of the provided -// project attribute. -// -// If the requested attribute is not defined, the returned error will -// be of type NotDefinedError. -// -// ProjectAttributeValue may return ("", nil) if the attribute was -// defined to be the empty string. -func ProjectAttributeValue(attr string) (string, error) { - return Get("project/attributes/" + attr) -} - -// Scopes returns the service account scopes for the given account. -// The account may be empty or the string "default" to use the instance's -// main account. -func Scopes(serviceAccount string) ([]string, error) { - if serviceAccount == "" { - serviceAccount = "default" - } - return lines("instance/service-accounts/" + serviceAccount + "/scopes") -} - -func strsContains(ss []string, s string) bool { - for _, v := range ss { - if v == s { - return true - } - } - return false -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/LICENSE b/vendor/github.com/Azure/azure-sdk-for-go/LICENSE deleted file mode 100644 index af39a91e7..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/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 2016 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/Azure/azure-sdk-for-go/NOTICE b/vendor/github.com/Azure/azure-sdk-for-go/NOTICE deleted file mode 100644 index 2d1d72608..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Microsoft Azure-SDK-for-Go -Copyright 2014-2017 Microsoft - -This product includes software developed at -the Microsoft Corporation (https://www.microsoft.com). diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go deleted file mode 100644 index 482d2f943..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/client.go +++ /dev/null @@ -1,51 +0,0 @@ -// Package dns implements the Azure ARM Dns service API version 2017-09-01. -// -// The DNS Management Client. -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/Azure/go-autorest/autorest" -) - -const ( - // DefaultBaseURI is the default URI used for the service Dns - DefaultBaseURI = "https://management.azure.com" -) - -// BaseClient is the base client for Dns. -type BaseClient struct { - autorest.Client - BaseURI string - SubscriptionID string -} - -// New creates an instance of the BaseClient client. -func New(subscriptionID string) BaseClient { - return NewWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewWithBaseURI creates an instance of the BaseClient client. -func NewWithBaseURI(baseURI string, subscriptionID string) BaseClient { - return BaseClient{ - Client: autorest.NewClientWithUserAgent(UserAgent()), - BaseURI: baseURI, - SubscriptionID: subscriptionID, - } -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go deleted file mode 100644 index 53d57a6ad..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/models.go +++ /dev/null @@ -1,763 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "encoding/json" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/to" - "net/http" -) - -// RecordType enumerates the values for record type. -type RecordType string - -const ( - // A ... - A RecordType = "A" - // AAAA ... - AAAA RecordType = "AAAA" - // CAA ... - CAA RecordType = "CAA" - // CNAME ... - CNAME RecordType = "CNAME" - // MX ... - MX RecordType = "MX" - // NS ... - NS RecordType = "NS" - // PTR ... - PTR RecordType = "PTR" - // SOA ... - SOA RecordType = "SOA" - // SRV ... - SRV RecordType = "SRV" - // TXT ... - TXT RecordType = "TXT" -) - -// PossibleRecordTypeValues returns an array of possible values for the RecordType const type. -func PossibleRecordTypeValues() []RecordType { - return []RecordType{A, AAAA, CAA, CNAME, MX, NS, PTR, SOA, SRV, TXT} -} - -// AaaaRecord an AAAA record. -type AaaaRecord struct { - // Ipv6Address - The IPv6 address of this AAAA record. - Ipv6Address *string `json:"ipv6Address,omitempty"` -} - -// ARecord an A record. -type ARecord struct { - // Ipv4Address - The IPv4 address of this A record. - Ipv4Address *string `json:"ipv4Address,omitempty"` -} - -// CaaRecord a CAA record. -type CaaRecord struct { - // Flags - The flags for this CAA record as an integer between 0 and 255. - Flags *int32 `json:"flags,omitempty"` - // Tag - The tag for this CAA record. - Tag *string `json:"tag,omitempty"` - // Value - The value for this CAA record. - Value *string `json:"value,omitempty"` -} - -// CloudError an error message -type CloudError struct { - // Error - The error message body - Error *CloudErrorBody `json:"error,omitempty"` -} - -// CloudErrorBody the body of an error message -type CloudErrorBody struct { - // Code - The error code - Code *string `json:"code,omitempty"` - // Message - A description of what caused the error - Message *string `json:"message,omitempty"` - // Target - The target resource of the error message - Target *string `json:"target,omitempty"` - // Details - Extra error information - Details *[]CloudErrorBody `json:"details,omitempty"` -} - -// CnameRecord a CNAME record. -type CnameRecord struct { - // Cname - The canonical name for this CNAME record. - Cname *string `json:"cname,omitempty"` -} - -// MxRecord an MX record. -type MxRecord struct { - // Preference - The preference value for this MX record. - Preference *int32 `json:"preference,omitempty"` - // Exchange - The domain name of the mail host for this MX record. - Exchange *string `json:"exchange,omitempty"` -} - -// NsRecord an NS record. -type NsRecord struct { - // Nsdname - The name server name for this NS record. - Nsdname *string `json:"nsdname,omitempty"` -} - -// PtrRecord a PTR record. -type PtrRecord struct { - // Ptrdname - The PTR target domain name for this PTR record. - Ptrdname *string `json:"ptrdname,omitempty"` -} - -// RecordSet describes a DNS record set (a collection of DNS records with the same name and type). -type RecordSet struct { - autorest.Response `json:"-"` - // ID - The ID of the record set. - ID *string `json:"id,omitempty"` - // Name - The name of the record set. - Name *string `json:"name,omitempty"` - // Type - The type of the record set. - Type *string `json:"type,omitempty"` - // Etag - The etag of the record set. - Etag *string `json:"etag,omitempty"` - // RecordSetProperties - The properties of the record set. - *RecordSetProperties `json:"properties,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSet. -func (rs RecordSet) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rs.ID != nil { - objectMap["id"] = rs.ID - } - if rs.Name != nil { - objectMap["name"] = rs.Name - } - if rs.Type != nil { - objectMap["type"] = rs.Type - } - if rs.Etag != nil { - objectMap["etag"] = rs.Etag - } - if rs.RecordSetProperties != nil { - objectMap["properties"] = rs.RecordSetProperties - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for RecordSet struct. -func (rs *RecordSet) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - rs.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - rs.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - rs.Type = &typeVar - } - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - rs.Etag = &etag - } - case "properties": - if v != nil { - var recordSetProperties RecordSetProperties - err = json.Unmarshal(*v, &recordSetProperties) - if err != nil { - return err - } - rs.RecordSetProperties = &recordSetProperties - } - } - } - - return nil -} - -// RecordSetListResult the response to a record set List operation. -type RecordSetListResult struct { - autorest.Response `json:"-"` - // Value - Information about the record sets in the response. - Value *[]RecordSet `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// RecordSetListResultIterator provides access to a complete listing of RecordSet values. -type RecordSetListResultIterator struct { - i int - page RecordSetListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *RecordSetListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter RecordSetListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter RecordSetListResultIterator) Response() RecordSetListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter RecordSetListResultIterator) Value() RecordSet { - if !iter.page.NotDone() { - return RecordSet{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (rslr RecordSetListResult) IsEmpty() bool { - return rslr.Value == nil || len(*rslr.Value) == 0 -} - -// recordSetListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (rslr RecordSetListResult) recordSetListResultPreparer() (*http.Request, error) { - if rslr.NextLink == nil || len(to.String(rslr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(rslr.NextLink))) -} - -// RecordSetListResultPage contains a page of RecordSet values. -type RecordSetListResultPage struct { - fn func(RecordSetListResult) (RecordSetListResult, error) - rslr RecordSetListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *RecordSetListResultPage) Next() error { - next, err := page.fn(page.rslr) - if err != nil { - return err - } - page.rslr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page RecordSetListResultPage) NotDone() bool { - return !page.rslr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page RecordSetListResultPage) Response() RecordSetListResult { - return page.rslr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page RecordSetListResultPage) Values() []RecordSet { - if page.rslr.IsEmpty() { - return nil - } - return *page.rslr.Value -} - -// RecordSetProperties represents the properties of the records in the record set. -type RecordSetProperties struct { - // Metadata - The metadata attached to the record set. - Metadata map[string]*string `json:"metadata"` - // TTL - The TTL (time-to-live) of the records in the record set. - TTL *int64 `json:"TTL,omitempty"` - // Fqdn - Fully qualified domain name of the record set. - Fqdn *string `json:"fqdn,omitempty"` - // ARecords - The list of A records in the record set. - ARecords *[]ARecord `json:"ARecords,omitempty"` - // AaaaRecords - The list of AAAA records in the record set. - AaaaRecords *[]AaaaRecord `json:"AAAARecords,omitempty"` - // MxRecords - The list of MX records in the record set. - MxRecords *[]MxRecord `json:"MXRecords,omitempty"` - // NsRecords - The list of NS records in the record set. - NsRecords *[]NsRecord `json:"NSRecords,omitempty"` - // PtrRecords - The list of PTR records in the record set. - PtrRecords *[]PtrRecord `json:"PTRRecords,omitempty"` - // SrvRecords - The list of SRV records in the record set. - SrvRecords *[]SrvRecord `json:"SRVRecords,omitempty"` - // TxtRecords - The list of TXT records in the record set. - TxtRecords *[]TxtRecord `json:"TXTRecords,omitempty"` - // CnameRecord - The CNAME record in the record set. - CnameRecord *CnameRecord `json:"CNAMERecord,omitempty"` - // SoaRecord - The SOA record in the record set. - SoaRecord *SoaRecord `json:"SOARecord,omitempty"` - // CaaRecords - The list of CAA records in the record set. - CaaRecords *[]CaaRecord `json:"caaRecords,omitempty"` -} - -// MarshalJSON is the custom marshaler for RecordSetProperties. -func (rsp RecordSetProperties) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if rsp.Metadata != nil { - objectMap["metadata"] = rsp.Metadata - } - if rsp.TTL != nil { - objectMap["TTL"] = rsp.TTL - } - if rsp.Fqdn != nil { - objectMap["fqdn"] = rsp.Fqdn - } - if rsp.ARecords != nil { - objectMap["ARecords"] = rsp.ARecords - } - if rsp.AaaaRecords != nil { - objectMap["AAAARecords"] = rsp.AaaaRecords - } - if rsp.MxRecords != nil { - objectMap["MXRecords"] = rsp.MxRecords - } - if rsp.NsRecords != nil { - objectMap["NSRecords"] = rsp.NsRecords - } - if rsp.PtrRecords != nil { - objectMap["PTRRecords"] = rsp.PtrRecords - } - if rsp.SrvRecords != nil { - objectMap["SRVRecords"] = rsp.SrvRecords - } - if rsp.TxtRecords != nil { - objectMap["TXTRecords"] = rsp.TxtRecords - } - if rsp.CnameRecord != nil { - objectMap["CNAMERecord"] = rsp.CnameRecord - } - if rsp.SoaRecord != nil { - objectMap["SOARecord"] = rsp.SoaRecord - } - if rsp.CaaRecords != nil { - objectMap["caaRecords"] = rsp.CaaRecords - } - return json.Marshal(objectMap) -} - -// RecordSetUpdateParameters parameters supplied to update a record set. -type RecordSetUpdateParameters struct { - // RecordSet - Specifies information about the record set being updated. - RecordSet *RecordSet `json:"RecordSet,omitempty"` -} - -// Resource common properties of an Azure Resource Manager resource -type Resource struct { - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Resource. -func (r Resource) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if r.ID != nil { - objectMap["id"] = r.ID - } - if r.Name != nil { - objectMap["name"] = r.Name - } - if r.Type != nil { - objectMap["type"] = r.Type - } - if r.Location != nil { - objectMap["location"] = r.Location - } - if r.Tags != nil { - objectMap["tags"] = r.Tags - } - return json.Marshal(objectMap) -} - -// SoaRecord an SOA record. -type SoaRecord struct { - // Host - The domain name of the authoritative name server for this SOA record. - Host *string `json:"host,omitempty"` - // Email - The email contact for this SOA record. - Email *string `json:"email,omitempty"` - // SerialNumber - The serial number for this SOA record. - SerialNumber *int64 `json:"serialNumber,omitempty"` - // RefreshTime - The refresh value for this SOA record. - RefreshTime *int64 `json:"refreshTime,omitempty"` - // RetryTime - The retry time for this SOA record. - RetryTime *int64 `json:"retryTime,omitempty"` - // ExpireTime - The expire time for this SOA record. - ExpireTime *int64 `json:"expireTime,omitempty"` - // MinimumTTL - The minimum value for this SOA record. By convention this is used to determine the negative caching duration. - MinimumTTL *int64 `json:"minimumTTL,omitempty"` -} - -// SrvRecord an SRV record. -type SrvRecord struct { - // Priority - The priority value for this SRV record. - Priority *int32 `json:"priority,omitempty"` - // Weight - The weight value for this SRV record. - Weight *int32 `json:"weight,omitempty"` - // Port - The port value for this SRV record. - Port *int32 `json:"port,omitempty"` - // Target - The target domain name for this SRV record. - Target *string `json:"target,omitempty"` -} - -// SubResource a reference to a another resource -type SubResource struct { - // ID - Resource Id. - ID *string `json:"id,omitempty"` -} - -// TxtRecord a TXT record. -type TxtRecord struct { - // Value - The text value of this TXT record. - Value *[]string `json:"value,omitempty"` -} - -// Zone describes a DNS zone. -type Zone struct { - autorest.Response `json:"-"` - // Etag - The etag of the zone. - Etag *string `json:"etag,omitempty"` - // ZoneProperties - The properties of the zone. - *ZoneProperties `json:"properties,omitempty"` - // ID - Resource ID. - ID *string `json:"id,omitempty"` - // Name - Resource name. - Name *string `json:"name,omitempty"` - // Type - Resource type. - Type *string `json:"type,omitempty"` - // Location - Resource location. - Location *string `json:"location,omitempty"` - // Tags - Resource tags. - Tags map[string]*string `json:"tags"` -} - -// MarshalJSON is the custom marshaler for Zone. -func (z Zone) MarshalJSON() ([]byte, error) { - objectMap := make(map[string]interface{}) - if z.Etag != nil { - objectMap["etag"] = z.Etag - } - if z.ZoneProperties != nil { - objectMap["properties"] = z.ZoneProperties - } - if z.ID != nil { - objectMap["id"] = z.ID - } - if z.Name != nil { - objectMap["name"] = z.Name - } - if z.Type != nil { - objectMap["type"] = z.Type - } - if z.Location != nil { - objectMap["location"] = z.Location - } - if z.Tags != nil { - objectMap["tags"] = z.Tags - } - return json.Marshal(objectMap) -} - -// UnmarshalJSON is the custom unmarshaler for Zone struct. -func (z *Zone) UnmarshalJSON(body []byte) error { - var m map[string]*json.RawMessage - err := json.Unmarshal(body, &m) - if err != nil { - return err - } - for k, v := range m { - switch k { - case "etag": - if v != nil { - var etag string - err = json.Unmarshal(*v, &etag) - if err != nil { - return err - } - z.Etag = &etag - } - case "properties": - if v != nil { - var zoneProperties ZoneProperties - err = json.Unmarshal(*v, &zoneProperties) - if err != nil { - return err - } - z.ZoneProperties = &zoneProperties - } - case "id": - if v != nil { - var ID string - err = json.Unmarshal(*v, &ID) - if err != nil { - return err - } - z.ID = &ID - } - case "name": - if v != nil { - var name string - err = json.Unmarshal(*v, &name) - if err != nil { - return err - } - z.Name = &name - } - case "type": - if v != nil { - var typeVar string - err = json.Unmarshal(*v, &typeVar) - if err != nil { - return err - } - z.Type = &typeVar - } - case "location": - if v != nil { - var location string - err = json.Unmarshal(*v, &location) - if err != nil { - return err - } - z.Location = &location - } - case "tags": - if v != nil { - var tags map[string]*string - err = json.Unmarshal(*v, &tags) - if err != nil { - return err - } - z.Tags = tags - } - } - } - - return nil -} - -// ZoneListResult the response to a Zone List or ListAll operation. -type ZoneListResult struct { - autorest.Response `json:"-"` - // Value - Information about the DNS zones. - Value *[]Zone `json:"value,omitempty"` - // NextLink - The continuation token for the next page of results. - NextLink *string `json:"nextLink,omitempty"` -} - -// ZoneListResultIterator provides access to a complete listing of Zone values. -type ZoneListResultIterator struct { - i int - page ZoneListResultPage -} - -// Next advances to the next value. If there was an error making -// the request the iterator does not advance and the error is returned. -func (iter *ZoneListResultIterator) Next() error { - iter.i++ - if iter.i < len(iter.page.Values()) { - return nil - } - err := iter.page.Next() - if err != nil { - iter.i-- - return err - } - iter.i = 0 - return nil -} - -// NotDone returns true if the enumeration should be started or is not yet complete. -func (iter ZoneListResultIterator) NotDone() bool { - return iter.page.NotDone() && iter.i < len(iter.page.Values()) -} - -// Response returns the raw server response from the last page request. -func (iter ZoneListResultIterator) Response() ZoneListResult { - return iter.page.Response() -} - -// Value returns the current value or a zero-initialized value if the -// iterator has advanced beyond the end of the collection. -func (iter ZoneListResultIterator) Value() Zone { - if !iter.page.NotDone() { - return Zone{} - } - return iter.page.Values()[iter.i] -} - -// IsEmpty returns true if the ListResult contains no values. -func (zlr ZoneListResult) IsEmpty() bool { - return zlr.Value == nil || len(*zlr.Value) == 0 -} - -// zoneListResultPreparer prepares a request to retrieve the next set of results. -// It returns nil if no more results exist. -func (zlr ZoneListResult) zoneListResultPreparer() (*http.Request, error) { - if zlr.NextLink == nil || len(to.String(zlr.NextLink)) < 1 { - return nil, nil - } - return autorest.Prepare(&http.Request{}, - autorest.AsJSON(), - autorest.AsGet(), - autorest.WithBaseURL(to.String(zlr.NextLink))) -} - -// ZoneListResultPage contains a page of Zone values. -type ZoneListResultPage struct { - fn func(ZoneListResult) (ZoneListResult, error) - zlr ZoneListResult -} - -// Next advances to the next page of values. If there was an error making -// the request the page does not advance and the error is returned. -func (page *ZoneListResultPage) Next() error { - next, err := page.fn(page.zlr) - if err != nil { - return err - } - page.zlr = next - return nil -} - -// NotDone returns true if the page enumeration should be started or is not yet complete. -func (page ZoneListResultPage) NotDone() bool { - return !page.zlr.IsEmpty() -} - -// Response returns the raw server response from the last page request. -func (page ZoneListResultPage) Response() ZoneListResult { - return page.zlr -} - -// Values returns the slice of values for the current page or nil if there are no values. -func (page ZoneListResultPage) Values() []Zone { - if page.zlr.IsEmpty() { - return nil - } - return *page.zlr.Value -} - -// ZoneProperties represents the properties of the zone. -type ZoneProperties struct { - // MaxNumberOfRecordSets - The maximum number of record sets that can be created in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - MaxNumberOfRecordSets *int64 `json:"maxNumberOfRecordSets,omitempty"` - // NumberOfRecordSets - The current number of record sets in this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NumberOfRecordSets *int64 `json:"numberOfRecordSets,omitempty"` - // NameServers - The name servers for this DNS zone. This is a read-only property and any attempt to set this value will be ignored. - NameServers *[]string `json:"nameServers,omitempty"` -} - -// ZonesDeleteFuture an abstraction for monitoring and retrieving the results of a long-running operation. -type ZonesDeleteFuture struct { - azure.Future - req *http.Request -} - -// Result returns the result of the asynchronous operation. -// If the operation has not completed it will return an error. -func (future ZonesDeleteFuture) Result(client ZonesClient) (ar autorest.Response, err error) { - var done bool - done, err = future.Done(client) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", future.Response(), "Polling failure") - return - } - if !done { - return ar, azure.NewAsyncOpIncompleteError("dns.ZonesDeleteFuture") - } - if future.PollingMethod() == azure.PollingLocation { - ar, err = client.DeleteResponder(future.Response()) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", future.Response(), "Failure responding to request") - } - return - } - var req *http.Request - var resp *http.Response - if future.PollingURL() != "" { - req, err = http.NewRequest(http.MethodGet, future.PollingURL(), nil) - if err != nil { - return - } - } else { - req = autorest.ChangeToGet(future.req) - } - resp, err = autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...)) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", resp, "Failure sending request") - return - } - ar, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesDeleteFuture", "Result", resp, "Failure responding to request") - } - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go deleted file mode 100644 index 45ea7a8c8..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/recordsets.go +++ /dev/null @@ -1,556 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// RecordSetsClient is the the DNS Management Client. -type RecordSetsClient struct { - BaseClient -} - -// NewRecordSetsClient creates an instance of the RecordSetsClient client. -func NewRecordSetsClient(subscriptionID string) RecordSetsClient { - return NewRecordSetsClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewRecordSetsClientWithBaseURI creates an instance of the RecordSetsClient client. -func NewRecordSetsClientWithBaseURI(baseURI string, subscriptionID string) RecordSetsClient { - return RecordSetsClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a record set within a DNS zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). relativeRecordSetName is the name of the record set, relative to the name of the zone. recordType is the -// type of DNS record in this record set. Record sets of type SOA can be updated but not created (they are created -// when the DNS zone is created). parameters is parameters supplied to the CreateOrUpdate operation. ifMatch is the -// etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag -// value to prevent accidentally overwritting any concurrent changes. ifNoneMatch is set to '*' to allow a new -// record set to be created, but to prevent updating an existing record set. Other values will be ignored. -func (client RecordSetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (result RecordSet, err error) { - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client RecordSetsClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - if len(ifNoneMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) CreateOrUpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a record set from a DNS zone. This operation cannot be undone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). relativeRecordSetName is the name of the record set, relative to the name of the zone. recordType is the -// type of DNS record in this record set. Record sets of type SOA cannot be deleted (they are deleted when the DNS -// zone is deleted). ifMatch is the etag of the record set. Omit this value to always delete the current record -// set. Specify the last-seen etag value to prevent accidentally deleting any concurrent changes. -func (client RecordSetsClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (result autorest.Response, err error) { - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", nil, "Failure preparing request") - return - } - - resp, err := client.DeleteSender(req) - if err != nil { - result.Response = resp - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure sending request") - return - } - - result, err = client.DeleteResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Delete", resp, "Failure responding to request") - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client RecordSetsClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) DeleteSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a record set. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). relativeRecordSetName is the name of the record set, relative to the name of the zone. recordType is the -// type of DNS record in this record set. -func (client RecordSetsClient) Get(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (result RecordSet, err error) { - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client RecordSetsClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) GetResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// ListByDNSZone lists all record sets in a DNS zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). top is the maximum number of record sets to return. If not specified, returns up to 100 record sets. -// recordsetnamesuffix is the suffix label of the record set name that has to be used to filter the record set -// enumerations. If this parameter is specified, Enumeration will return only records that end with -// . -func (client RecordSetsClient) ListByDNSZone(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - result.fn = client.listByDNSZoneNextResults - req, err := client.ListByDNSZonePreparer(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", nil, "Failure preparing request") - return - } - - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByDNSZone", resp, "Failure responding to request") - } - - return -} - -// ListByDNSZonePreparer prepares the ListByDNSZone request. -func (client RecordSetsClient) ListByDNSZonePreparer(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/recordsets", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByDNSZoneSender sends the ListByDNSZone request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByDNSZoneSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByDNSZoneResponder handles the response to the ListByDNSZone request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByDNSZoneResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByDNSZoneNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByDNSZoneNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByDNSZoneSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByDNSZoneResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByDNSZoneNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByDNSZoneComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByDNSZoneComplete(ctx context.Context, resourceGroupName string, zoneName string, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByDNSZone(ctx, resourceGroupName, zoneName, top, recordsetnamesuffix) - return -} - -// ListByType lists the record sets of a specified type in a DNS zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). recordType is the type of record sets to enumerate. top is the maximum number of record sets to return. If -// not specified, returns up to 100 record sets. recordsetnamesuffix is the suffix label of the record set name -// that has to be used to filter the record set enumerations. If this parameter is specified, Enumeration will -// return only records that end with . -func (client RecordSetsClient) ListByType(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultPage, err error) { - result.fn = client.listByTypeNextResults - req, err := client.ListByTypePreparer(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", nil, "Failure preparing request") - return - } - - resp, err := client.ListByTypeSender(req) - if err != nil { - result.rslr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure sending request") - return - } - - result.rslr, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "ListByType", resp, "Failure responding to request") - } - - return -} - -// ListByTypePreparer prepares the ListByType request. -func (client RecordSetsClient) ListByTypePreparer(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - if len(recordsetnamesuffix) > 0 { - queryParameters["$recordsetnamesuffix"] = autorest.Encode("query", recordsetnamesuffix) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByTypeSender sends the ListByType request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) ListByTypeSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByTypeResponder handles the response to the ListByType request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) ListByTypeResponder(resp *http.Response) (result RecordSetListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByTypeNextResults retrieves the next set of results, if any. -func (client RecordSetsClient) listByTypeNextResults(lastResults RecordSetListResult) (result RecordSetListResult, err error) { - req, err := lastResults.recordSetListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByTypeSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByTypeResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "listByTypeNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByTypeComplete enumerates all values, automatically crossing page boundaries as required. -func (client RecordSetsClient) ListByTypeComplete(ctx context.Context, resourceGroupName string, zoneName string, recordType RecordType, top *int32, recordsetnamesuffix string) (result RecordSetListResultIterator, err error) { - result.page, err = client.ListByType(ctx, resourceGroupName, zoneName, recordType, top, recordsetnamesuffix) - return -} - -// Update updates a record set within a DNS zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). relativeRecordSetName is the name of the record set, relative to the name of the zone. recordType is the -// type of DNS record in this record set. parameters is parameters supplied to the Update operation. ifMatch is the -// etag of the record set. Omit this value to always overwrite the current record set. Specify the last-seen etag -// value to prevent accidentally overwritting concurrent changes. -func (client RecordSetsClient) Update(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (result RecordSet, err error) { - req, err := client.UpdatePreparer(ctx, resourceGroupName, zoneName, relativeRecordSetName, recordType, parameters, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", nil, "Failure preparing request") - return - } - - resp, err := client.UpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure sending request") - return - } - - result, err = client.UpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.RecordSetsClient", "Update", resp, "Failure responding to request") - } - - return -} - -// UpdatePreparer prepares the Update request. -func (client RecordSetsClient) UpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, relativeRecordSetName string, recordType RecordType, parameters RecordSet, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "recordType": autorest.Encode("path", recordType), - "relativeRecordSetName": relativeRecordSetName, - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPatch(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}/{recordType}/{relativeRecordSetName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// UpdateSender sends the Update request. The method will close the -// http.Response Body if it receives an error. -func (client RecordSetsClient) UpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// UpdateResponder handles the response to the Update request. The method always -// closes the http.Response Body. -func (client RecordSetsClient) UpdateResponder(resp *http.Response) (result RecordSet, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go deleted file mode 100644 index 0556b6130..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/version.go +++ /dev/null @@ -1,30 +0,0 @@ -package dns - -import "github.com/Azure/azure-sdk-for-go/version" - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// UserAgent returns the UserAgent string to use when sending http.Requests. -func UserAgent() string { - return "Azure-SDK-For-Go/" + version.Number + " dns/2017-09-01" -} - -// Version returns the semantic version (see http://semver.org) of the client. -func Version() string { - return version.Number -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go b/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go deleted file mode 100644 index 04ac760d0..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns/zones.go +++ /dev/null @@ -1,453 +0,0 @@ -package dns - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "context" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/azure" - "net/http" -) - -// ZonesClient is the the DNS Management Client. -type ZonesClient struct { - BaseClient -} - -// NewZonesClient creates an instance of the ZonesClient client. -func NewZonesClient(subscriptionID string) ZonesClient { - return NewZonesClientWithBaseURI(DefaultBaseURI, subscriptionID) -} - -// NewZonesClientWithBaseURI creates an instance of the ZonesClient client. -func NewZonesClientWithBaseURI(baseURI string, subscriptionID string) ZonesClient { - return ZonesClient{NewWithBaseURI(baseURI, subscriptionID)} -} - -// CreateOrUpdate creates or updates a DNS zone. Does not modify DNS records within the zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). parameters is parameters supplied to the CreateOrUpdate operation. ifMatch is the etag of the DNS zone. -// Omit this value to always overwrite the current zone. Specify the last-seen etag value to prevent accidentally -// overwritting any concurrent changes. ifNoneMatch is set to '*' to allow a new DNS zone to be created, but to -// prevent updating an existing zone. Other values will be ignored. -func (client ZonesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (result Zone, err error) { - req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, zoneName, parameters, ifMatch, ifNoneMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", nil, "Failure preparing request") - return - } - - resp, err := client.CreateOrUpdateSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure sending request") - return - } - - result, err = client.CreateOrUpdateResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "CreateOrUpdate", resp, "Failure responding to request") - } - - return -} - -// CreateOrUpdatePreparer prepares the CreateOrUpdate request. -func (client ZonesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, zoneName string, parameters Zone, ifMatch string, ifNoneMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsContentType("application/json; charset=utf-8"), - autorest.AsPut(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithJSON(parameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - if len(ifNoneMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-None-Match", autorest.String(ifNoneMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always -// closes the http.Response Body. -func (client ZonesClient) CreateOrUpdateResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// Delete deletes a DNS zone. WARNING: All DNS records in the zone will also be deleted. This operation cannot be -// undone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). ifMatch is the etag of the DNS zone. Omit this value to always delete the current zone. Specify the -// last-seen etag value to prevent accidentally deleting any concurrent changes. -func (client ZonesClient) Delete(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (result ZonesDeleteFuture, err error) { - req, err := client.DeletePreparer(ctx, resourceGroupName, zoneName, ifMatch) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", nil, "Failure preparing request") - return - } - - result, err = client.DeleteSender(req) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Delete", result.Response(), "Failure sending request") - return - } - - return -} - -// DeletePreparer prepares the Delete request. -func (client ZonesClient) DeletePreparer(ctx context.Context, resourceGroupName string, zoneName string, ifMatch string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsDelete(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - if len(ifMatch) > 0 { - preparer = autorest.DecoratePreparer(preparer, - autorest.WithHeader("If-Match", autorest.String(ifMatch))) - } - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// DeleteSender sends the Delete request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) DeleteSender(req *http.Request) (future ZonesDeleteFuture, err error) { - sender := autorest.DecorateSender(client, azure.DoRetryWithRegistration(client.Client)) - future.Future = azure.NewFuture(req) - future.req = req - _, err = future.Done(sender) - if err != nil { - return - } - err = autorest.Respond(future.Response(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent)) - return -} - -// DeleteResponder handles the response to the Delete request. The method always -// closes the http.Response Body. -func (client ZonesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusAccepted, http.StatusNoContent), - autorest.ByClosing()) - result.Response = resp - return -} - -// Get gets a DNS zone. Retrieves the zone properties, but not the record sets within the zone. -// -// resourceGroupName is the name of the resource group. zoneName is the name of the DNS zone (without a terminating -// dot). -func (client ZonesClient) Get(ctx context.Context, resourceGroupName string, zoneName string) (result Zone, err error) { - req, err := client.GetPreparer(ctx, resourceGroupName, zoneName) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", nil, "Failure preparing request") - return - } - - resp, err := client.GetSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure sending request") - return - } - - result, err = client.GetResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "Get", resp, "Failure responding to request") - } - - return -} - -// GetPreparer prepares the Get request. -func (client ZonesClient) GetPreparer(ctx context.Context, resourceGroupName string, zoneName string) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - "zoneName": autorest.Encode("path", zoneName), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones/{zoneName}", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// GetSender sends the Get request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) GetSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// GetResponder handles the response to the Get request. The method always -// closes the http.Response Body. -func (client ZonesClient) GetResponder(resp *http.Response) (result Zone, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// List lists the DNS zones in all resource groups in a subscription. -// -// top is the maximum number of DNS zones to return. If not specified, returns up to 100 zones. -func (client ZonesClient) List(ctx context.Context, top *int32) (result ZoneListResultPage, err error) { - result.fn = client.listNextResults - req, err := client.ListPreparer(ctx, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", nil, "Failure preparing request") - return - } - - resp, err := client.ListSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "List", resp, "Failure responding to request") - } - - return -} - -// ListPreparer prepares the List request. -func (client ZonesClient) ListPreparer(ctx context.Context, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Network/dnszones", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListSender sends the List request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) ListSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListResponder handles the response to the List request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listNextResults retrieves the next set of results, if any. -func (client ZonesClient) listNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure sending next results request") - } - result, err = client.ListResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListComplete(ctx context.Context, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.List(ctx, top) - return -} - -// ListByResourceGroup lists the DNS zones within a resource group. -// -// resourceGroupName is the name of the resource group. top is the maximum number of record sets to return. If not -// specified, returns up to 100 record sets. -func (client ZonesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultPage, err error) { - result.fn = client.listByResourceGroupNextResults - req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName, top) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", nil, "Failure preparing request") - return - } - - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.zlr.Response = autorest.Response{Response: resp} - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure sending request") - return - } - - result.zlr, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "ListByResourceGroup", resp, "Failure responding to request") - } - - return -} - -// ListByResourceGroupPreparer prepares the ListByResourceGroup request. -func (client ZonesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string, top *int32) (*http.Request, error) { - pathParameters := map[string]interface{}{ - "resourceGroupName": autorest.Encode("path", resourceGroupName), - "subscriptionId": autorest.Encode("path", client.SubscriptionID), - } - - const APIVersion = "2017-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - if top != nil { - queryParameters["$top"] = autorest.Encode("query", *top) - } - - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(client.BaseURI), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/dnsZones", pathParameters), - autorest.WithQueryParameters(queryParameters)) - return preparer.Prepare((&http.Request{}).WithContext(ctx)) -} - -// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the -// http.Response Body if it receives an error. -func (client ZonesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) { - return autorest.SendWithSender(client, req, - azure.DoRetryWithRegistration(client.Client)) -} - -// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always -// closes the http.Response Body. -func (client ZonesClient) ListByResourceGroupResponder(resp *http.Response) (result ZoneListResult, err error) { - err = autorest.Respond( - resp, - client.ByInspecting(), - azure.WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&result), - autorest.ByClosing()) - result.Response = autorest.Response{Response: resp} - return -} - -// listByResourceGroupNextResults retrieves the next set of results, if any. -func (client ZonesClient) listByResourceGroupNextResults(lastResults ZoneListResult) (result ZoneListResult, err error) { - req, err := lastResults.zoneListResultPreparer() - if err != nil { - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request") - } - if req == nil { - return - } - resp, err := client.ListByResourceGroupSender(req) - if err != nil { - result.Response = autorest.Response{Response: resp} - return result, autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request") - } - result, err = client.ListByResourceGroupResponder(resp) - if err != nil { - err = autorest.NewErrorWithError(err, "dns.ZonesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request") - } - return -} - -// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required. -func (client ZonesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string, top *int32) (result ZoneListResultIterator, err error) { - result.page, err = client.ListByResourceGroup(ctx, resourceGroupName, top) - return -} diff --git a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go b/vendor/github.com/Azure/azure-sdk-for-go/version/version.go deleted file mode 100644 index 2cd4c1b1f..000000000 --- a/vendor/github.com/Azure/azure-sdk-for-go/version/version.go +++ /dev/null @@ -1,21 +0,0 @@ -package version - -// Copyright (c) Microsoft and contributors. All rights reserved. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// -// See the License for the specific language governing permissions and -// limitations under the License. -// -// Code generated by Microsoft (R) AutoRest Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Number contains the semantic version of this SDK. -const Number = "v15.0.1" 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/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 a67327972..000000000 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ /dev/null @@ -1,182 +0,0 @@ -// +build windows - -package winterm - -import ( - "fmt" - "os" - "strconv" - "strings" - "syscall" - - "github.com/Azure/go-ansiterm" -) - -// 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 - 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/Azure/go-autorest/LICENSE b/vendor/github.com/Azure/go-autorest/LICENSE deleted file mode 100644 index b9d6a27ea..000000000 --- a/vendor/github.com/Azure/go-autorest/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2015 Microsoft Corporation - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/Azure/go-autorest/autorest/adal/config.go b/vendor/github.com/Azure/go-autorest/autorest/adal/config.go deleted file mode 100644 index f570d540a..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/config.go +++ /dev/null @@ -1,81 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/url" -) - -const ( - activeDirectoryAPIVersion = "1.0" -) - -// OAuthConfig represents the endpoints needed -// in OAuth operations -type OAuthConfig struct { - AuthorityEndpoint url.URL - AuthorizeEndpoint url.URL - TokenEndpoint url.URL - DeviceCodeEndpoint url.URL -} - -// IsZero returns true if the OAuthConfig object is zero-initialized. -func (oac OAuthConfig) IsZero() bool { - return oac == OAuthConfig{} -} - -func validateStringParam(param, name string) error { - if len(param) == 0 { - return fmt.Errorf("parameter '" + name + "' cannot be empty") - } - return nil -} - -// NewOAuthConfig returns an OAuthConfig with tenant specific urls -func NewOAuthConfig(activeDirectoryEndpoint, tenantID string) (*OAuthConfig, error) { - if err := validateStringParam(activeDirectoryEndpoint, "activeDirectoryEndpoint"); err != nil { - return nil, err - } - // it's legal for tenantID to be empty so don't validate it - const activeDirectoryEndpointTemplate = "%s/oauth2/%s?api-version=%s" - u, err := url.Parse(activeDirectoryEndpoint) - if err != nil { - return nil, err - } - authorityURL, err := u.Parse(tenantID) - if err != nil { - return nil, err - } - authorizeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "authorize", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - tokenURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "token", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - deviceCodeURL, err := u.Parse(fmt.Sprintf(activeDirectoryEndpointTemplate, tenantID, "devicecode", activeDirectoryAPIVersion)) - if err != nil { - return nil, err - } - - return &OAuthConfig{ - AuthorityEndpoint: *authorityURL, - AuthorizeEndpoint: *authorizeURL, - TokenEndpoint: *tokenURL, - DeviceCodeEndpoint: *deviceCodeURL, - }, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go b/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go deleted file mode 100644 index b38f4c245..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/devicetoken.go +++ /dev/null @@ -1,242 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -/* - This file is largely based on rjw57/oauth2device's code, with the follow differences: - * scope -> resource, and only allow a single one - * receive "Message" in the DeviceCode struct and show it to users as the prompt - * azure-xplat-cli has the following behavior that this emulates: - - does not send client_secret during the token exchange - - sends resource again in the token exchange request -*/ - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -const ( - logPrefix = "autorest/adal/devicetoken:" -) - -var ( - // ErrDeviceGeneric represents an unknown error from the token endpoint when using device flow - ErrDeviceGeneric = fmt.Errorf("%s Error while retrieving OAuth token: Unknown Error", logPrefix) - - // ErrDeviceAccessDenied represents an access denied error from the token endpoint when using device flow - ErrDeviceAccessDenied = fmt.Errorf("%s Error while retrieving OAuth token: Access Denied", logPrefix) - - // ErrDeviceAuthorizationPending represents the server waiting on the user to complete the device flow - ErrDeviceAuthorizationPending = fmt.Errorf("%s Error while retrieving OAuth token: Authorization Pending", logPrefix) - - // ErrDeviceCodeExpired represents the server timing out and expiring the code during device flow - ErrDeviceCodeExpired = fmt.Errorf("%s Error while retrieving OAuth token: Code Expired", logPrefix) - - // ErrDeviceSlowDown represents the service telling us we're polling too often during device flow - ErrDeviceSlowDown = fmt.Errorf("%s Error while retrieving OAuth token: Slow Down", logPrefix) - - // ErrDeviceCodeEmpty represents an empty device code from the device endpoint while using device flow - ErrDeviceCodeEmpty = fmt.Errorf("%s Error while retrieving device code: Device Code Empty", logPrefix) - - // ErrOAuthTokenEmpty represents an empty OAuth token from the token endpoint when using device flow - ErrOAuthTokenEmpty = fmt.Errorf("%s Error while retrieving OAuth token: Token Empty", logPrefix) - - errCodeSendingFails = "Error occurred while sending request for Device Authorization Code" - errCodeHandlingFails = "Error occurred while handling response from the Device Endpoint" - errTokenSendingFails = "Error occurred while sending request with device code for a token" - errTokenHandlingFails = "Error occurred while handling response from the Token Endpoint (during device flow)" - errStatusNotOK = "Error HTTP status != 200" -) - -// DeviceCode is the object returned by the device auth endpoint -// It contains information to instruct the user to complete the auth flow -type DeviceCode struct { - DeviceCode *string `json:"device_code,omitempty"` - UserCode *string `json:"user_code,omitempty"` - VerificationURL *string `json:"verification_url,omitempty"` - ExpiresIn *int64 `json:"expires_in,string,omitempty"` - Interval *int64 `json:"interval,string,omitempty"` - - Message *string `json:"message"` // Azure specific - Resource string // store the following, stored when initiating, used when exchanging - OAuthConfig OAuthConfig - ClientID string -} - -// TokenError is the object returned by the token exchange endpoint -// when something is amiss -type TokenError struct { - Error *string `json:"error,omitempty"` - ErrorCodes []int `json:"error_codes,omitempty"` - ErrorDescription *string `json:"error_description,omitempty"` - Timestamp *string `json:"timestamp,omitempty"` - TraceID *string `json:"trace_id,omitempty"` -} - -// DeviceToken is the object return by the token exchange endpoint -// It can either look like a Token or an ErrorToken, so put both here -// and check for presence of "Error" to know if we are in error state -type deviceToken struct { - Token - TokenError -} - -// InitiateDeviceAuth initiates a device auth flow. It returns a DeviceCode -// that can be used with CheckForUserCompletion or WaitForUserCompletion. -func InitiateDeviceAuth(sender Sender, oauthConfig OAuthConfig, clientID, resource string) (*DeviceCode, error) { - v := url.Values{ - "client_id": []string{clientID}, - "resource": []string{resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, oauthConfig.DeviceCodeEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, errStatusNotOK) - } - - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrDeviceCodeEmpty - } - - var code DeviceCode - err = json.Unmarshal(rb, &code) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errCodeHandlingFails, err.Error()) - } - - code.ClientID = clientID - code.Resource = resource - code.OAuthConfig = oauthConfig - - return &code, nil -} - -// CheckForUserCompletion takes a DeviceCode and checks with the Azure AD OAuth endpoint -// to see if the device flow has: been completed, timed out, or otherwise failed -func CheckForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - v := url.Values{ - "client_id": []string{code.ClientID}, - "code": []string{*code.DeviceCode}, - "grant_type": []string{OAuthGrantTypeDeviceCode}, - "resource": []string{code.Resource}, - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - - req, err := http.NewRequest(http.MethodPost, code.OAuthConfig.TokenEndpoint.String(), body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - resp, err := sender.Do(req) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenSendingFails, err.Error()) - } - defer resp.Body.Close() - - rb, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if resp.StatusCode != http.StatusOK && len(strings.Trim(string(rb), " ")) == 0 { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, errStatusNotOK) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return nil, ErrOAuthTokenEmpty - } - - var token deviceToken - err = json.Unmarshal(rb, &token) - if err != nil { - return nil, fmt.Errorf("%s %s: %s", logPrefix, errTokenHandlingFails, err.Error()) - } - - if token.Error == nil { - return &token.Token, nil - } - - switch *token.Error { - case "authorization_pending": - return nil, ErrDeviceAuthorizationPending - case "slow_down": - return nil, ErrDeviceSlowDown - case "access_denied": - return nil, ErrDeviceAccessDenied - case "code_expired": - return nil, ErrDeviceCodeExpired - default: - return nil, ErrDeviceGeneric - } -} - -// WaitForUserCompletion calls CheckForUserCompletion repeatedly until a token is granted or an error state occurs. -// This prevents the user from looping and checking against 'ErrDeviceAuthorizationPending'. -func WaitForUserCompletion(sender Sender, code *DeviceCode) (*Token, error) { - intervalDuration := time.Duration(*code.Interval) * time.Second - waitDuration := intervalDuration - - for { - token, err := CheckForUserCompletion(sender, code) - - if err == nil { - return token, nil - } - - switch err { - case ErrDeviceSlowDown: - waitDuration += waitDuration - case ErrDeviceAuthorizationPending: - // noop - default: // everything else is "fatal" to us - return nil, err - } - - if waitDuration > (intervalDuration * 3) { - return nil, fmt.Errorf("%s Error waiting for user to complete device flow. Server told us to slow_down too much", logPrefix) - } - - time.Sleep(waitDuration) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go b/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go deleted file mode 100644 index 9e15f2751..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/persist.go +++ /dev/null @@ -1,73 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "path/filepath" -) - -// LoadToken restores a Token object from a file located at 'path'. -func LoadToken(path string) (*Token, error) { - file, err := os.Open(path) - if err != nil { - return nil, fmt.Errorf("failed to open file (%s) while loading token: %v", path, err) - } - defer file.Close() - - var token Token - - dec := json.NewDecoder(file) - if err = dec.Decode(&token); err != nil { - return nil, fmt.Errorf("failed to decode contents of file (%s) into Token representation: %v", path, err) - } - return &token, nil -} - -// SaveToken persists an oauth token at the given location on disk. -// It moves the new file into place so it can safely be used to replace an existing file -// that maybe accessed by multiple processes. -func SaveToken(path string, mode os.FileMode, token Token) error { - dir := filepath.Dir(path) - err := os.MkdirAll(dir, os.ModePerm) - if err != nil { - return fmt.Errorf("failed to create directory (%s) to store token in: %v", dir, err) - } - - newFile, err := ioutil.TempFile(dir, "token") - if err != nil { - return fmt.Errorf("failed to create the temp file to write the token: %v", err) - } - tempPath := newFile.Name() - - if err := json.NewEncoder(newFile).Encode(token); err != nil { - return fmt.Errorf("failed to encode token to file (%s) while saving token: %v", tempPath, err) - } - if err := newFile.Close(); err != nil { - return fmt.Errorf("failed to close temp file %s: %v", tempPath, err) - } - - // Atomic replace to avoid multi-writer file corruptions - if err := os.Rename(tempPath, path); err != nil { - return fmt.Errorf("failed to move temporary token to desired output location. src=%s dst=%s: %v", tempPath, path, err) - } - if err := os.Chmod(path, mode); err != nil { - return fmt.Errorf("failed to chmod the token file %s: %v", path, err) - } - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go b/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go deleted file mode 100644 index 0e5ad14d3..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/sender.go +++ /dev/null @@ -1,60 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "net/http" -) - -const ( - contentType = "Content-Type" - mimeTypeFormPost = "application/x-www-form-urlencoded" -) - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go b/vendor/github.com/Azure/go-autorest/autorest/adal/token.go deleted file mode 100644 index b61b3eb8e..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/adal/token.go +++ /dev/null @@ -1,684 +0,0 @@ -package adal - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/Azure/go-autorest/autorest/date" - "github.com/dgrijalva/jwt-go" -) - -const ( - defaultRefresh = 5 * time.Minute - - // OAuthGrantTypeDeviceCode is the "grant_type" identifier used in device flow - OAuthGrantTypeDeviceCode = "device_code" - - // OAuthGrantTypeClientCredentials is the "grant_type" identifier used in credential flows - OAuthGrantTypeClientCredentials = "client_credentials" - - // OAuthGrantTypeUserPass is the "grant_type" identifier used in username and password auth flows - OAuthGrantTypeUserPass = "password" - - // OAuthGrantTypeRefreshToken is the "grant_type" identifier used in refresh token flows - OAuthGrantTypeRefreshToken = "refresh_token" - - // OAuthGrantTypeAuthorizationCode is the "grant_type" identifier used in authorization code flows - OAuthGrantTypeAuthorizationCode = "authorization_code" - - // metadataHeader is the header required by MSI extension - metadataHeader = "Metadata" - - // msiEndpoint is the well known endpoint for getting MSI authentications tokens - msiEndpoint = "http://169.254.169.254/metadata/identity/oauth2/token" -) - -// OAuthTokenProvider is an interface which should be implemented by an access token retriever -type OAuthTokenProvider interface { - OAuthToken() string -} - -// TokenRefreshError is an interface used by errors returned during token refresh. -type TokenRefreshError interface { - error - Response() *http.Response -} - -// Refresher is an interface for token refresh functionality -type Refresher interface { - Refresh() error - RefreshExchange(resource string) error - EnsureFresh() error -} - -// TokenRefreshCallback is the type representing callbacks that will be called after -// a successful token refresh -type TokenRefreshCallback func(Token) error - -// Token encapsulates the access token used to authorize Azure requests. -type Token struct { - AccessToken string `json:"access_token"` - RefreshToken string `json:"refresh_token"` - - ExpiresIn string `json:"expires_in"` - ExpiresOn string `json:"expires_on"` - NotBefore string `json:"not_before"` - - Resource string `json:"resource"` - Type string `json:"token_type"` -} - -// IsZero returns true if the token object is zero-initialized. -func (t Token) IsZero() bool { - return t == Token{} -} - -// Expires returns the time.Time when the Token expires. -func (t Token) Expires() time.Time { - s, err := strconv.Atoi(t.ExpiresOn) - if err != nil { - s = -3600 - } - - expiration := date.NewUnixTimeFromSeconds(float64(s)) - - return time.Time(expiration).UTC() -} - -// IsExpired returns true if the Token is expired, false otherwise. -func (t Token) IsExpired() bool { - return t.WillExpireIn(0) -} - -// WillExpireIn returns true if the Token will expire after the passed time.Duration interval -// from now, false otherwise. -func (t Token) WillExpireIn(d time.Duration) bool { - return !t.Expires().After(time.Now().Add(d)) -} - -//OAuthToken return the current access token -func (t *Token) OAuthToken() string { - return t.AccessToken -} - -// ServicePrincipalNoSecret represents a secret type that contains no secret -// meaning it is not valid for fetching a fresh token. This is used by Manual -type ServicePrincipalNoSecret struct { -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret -// It only returns an error for the ServicePrincipalNoSecret type -func (noSecret *ServicePrincipalNoSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return fmt.Errorf("Manually created ServicePrincipalToken does not contain secret material to retrieve a new access token") -} - -// ServicePrincipalSecret is an interface that allows various secret mechanism to fill the form -// that is submitted when acquiring an oAuth token. -type ServicePrincipalSecret interface { - SetAuthenticationValues(spt *ServicePrincipalToken, values *url.Values) error -} - -// ServicePrincipalTokenSecret implements ServicePrincipalSecret for client_secret type authorization. -type ServicePrincipalTokenSecret struct { - ClientSecret string -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using the client_secret. -func (tokenSecret *ServicePrincipalTokenSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("client_secret", tokenSecret.ClientSecret) - return nil -} - -// ServicePrincipalCertificateSecret implements ServicePrincipalSecret for generic RSA cert auth with signed JWTs. -type ServicePrincipalCertificateSecret struct { - Certificate *x509.Certificate - PrivateKey *rsa.PrivateKey -} - -// ServicePrincipalMSISecret implements ServicePrincipalSecret for machines running the MSI Extension. -type ServicePrincipalMSISecret struct { -} - -// ServicePrincipalUsernamePasswordSecret implements ServicePrincipalSecret for username and password auth. -type ServicePrincipalUsernamePasswordSecret struct { - Username string - Password string -} - -// ServicePrincipalAuthorizationCodeSecret implements ServicePrincipalSecret for authorization code auth. -type ServicePrincipalAuthorizationCodeSecret struct { - ClientSecret string - AuthorizationCode string - RedirectURI string -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalAuthorizationCodeSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("code", secret.AuthorizationCode) - v.Set("client_secret", secret.ClientSecret) - v.Set("redirect_uri", secret.RedirectURI) - return nil -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (secret *ServicePrincipalUsernamePasswordSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - v.Set("username", secret.Username) - v.Set("password", secret.Password) - return nil -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -func (msiSecret *ServicePrincipalMSISecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - return nil -} - -// SignJwt returns the JWT signed with the certificate's private key. -func (secret *ServicePrincipalCertificateSecret) SignJwt(spt *ServicePrincipalToken) (string, error) { - hasher := sha1.New() - _, err := hasher.Write(secret.Certificate.Raw) - if err != nil { - return "", err - } - - thumbprint := base64.URLEncoding.EncodeToString(hasher.Sum(nil)) - - // The jti (JWT ID) claim provides a unique identifier for the JWT. - jti := make([]byte, 20) - _, err = rand.Read(jti) - if err != nil { - return "", err - } - - token := jwt.New(jwt.SigningMethodRS256) - token.Header["x5t"] = thumbprint - token.Claims = jwt.MapClaims{ - "aud": spt.oauthConfig.TokenEndpoint.String(), - "iss": spt.clientID, - "sub": spt.clientID, - "jti": base64.URLEncoding.EncodeToString(jti), - "nbf": time.Now().Unix(), - "exp": time.Now().Add(time.Hour * 24).Unix(), - } - - signedString, err := token.SignedString(secret.PrivateKey) - return signedString, err -} - -// SetAuthenticationValues is a method of the interface ServicePrincipalSecret. -// It will populate the form submitted during oAuth Token Acquisition using a JWT signed with a certificate. -func (secret *ServicePrincipalCertificateSecret) SetAuthenticationValues(spt *ServicePrincipalToken, v *url.Values) error { - jwt, err := secret.SignJwt(spt) - if err != nil { - return err - } - - v.Set("client_assertion", jwt) - v.Set("client_assertion_type", "urn:ietf:params:oauth:client-assertion-type:jwt-bearer") - return nil -} - -// ServicePrincipalToken encapsulates a Token created for a Service Principal. -type ServicePrincipalToken struct { - token Token - secret ServicePrincipalSecret - oauthConfig OAuthConfig - clientID string - resource string - autoRefresh bool - refreshLock *sync.RWMutex - refreshWithin time.Duration - sender Sender - - refreshCallbacks []TokenRefreshCallback -} - -func validateOAuthConfig(oac OAuthConfig) error { - if oac.IsZero() { - return fmt.Errorf("parameter 'oauthConfig' cannot be zero-initialized") - } - return nil -} - -// NewServicePrincipalTokenWithSecret create a ServicePrincipalToken using the supplied ServicePrincipalSecret implementation. -func NewServicePrincipalTokenWithSecret(oauthConfig OAuthConfig, id string, resource string, secret ServicePrincipalSecret, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(id, "id"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if secret == nil { - return nil, fmt.Errorf("parameter 'secret' cannot be nil") - } - spt := &ServicePrincipalToken{ - oauthConfig: oauthConfig, - secret: secret, - clientID: id, - resource: resource, - autoRefresh: true, - refreshLock: &sync.RWMutex{}, - refreshWithin: defaultRefresh, - sender: &http.Client{}, - refreshCallbacks: callbacks, - } - return spt, nil -} - -// NewServicePrincipalTokenFromManualToken creates a ServicePrincipalToken using the supplied token -func NewServicePrincipalTokenFromManualToken(oauthConfig OAuthConfig, clientID string, resource string, token Token, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if token.IsZero() { - return nil, fmt.Errorf("parameter 'token' cannot be zero-initialized") - } - spt, err := NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalNoSecret{}, - callbacks...) - if err != nil { - return nil, err - } - - spt.token = token - - return spt, nil -} - -// NewServicePrincipalToken creates a ServicePrincipalToken from the supplied Service Principal -// credentials scoped to the named resource. -func NewServicePrincipalToken(oauthConfig OAuthConfig, clientID string, secret string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(secret, "secret"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalTokenSecret{ - ClientSecret: secret, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromCertificate creates a ServicePrincipalToken from the supplied pkcs12 bytes. -func NewServicePrincipalTokenFromCertificate(oauthConfig OAuthConfig, clientID string, certificate *x509.Certificate, privateKey *rsa.PrivateKey, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if certificate == nil { - return nil, fmt.Errorf("parameter 'certificate' cannot be nil") - } - if privateKey == nil { - return nil, fmt.Errorf("parameter 'privateKey' cannot be nil") - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalCertificateSecret{ - PrivateKey: privateKey, - Certificate: certificate, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromUsernamePassword creates a ServicePrincipalToken from the username and password. -func NewServicePrincipalTokenFromUsernamePassword(oauthConfig OAuthConfig, clientID string, username string, password string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(username, "username"); err != nil { - return nil, err - } - if err := validateStringParam(password, "password"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalUsernamePasswordSecret{ - Username: username, - Password: password, - }, - callbacks..., - ) -} - -// NewServicePrincipalTokenFromAuthorizationCode creates a ServicePrincipalToken from the -func NewServicePrincipalTokenFromAuthorizationCode(oauthConfig OAuthConfig, clientID string, clientSecret string, authorizationCode string, redirectURI string, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - - if err := validateOAuthConfig(oauthConfig); err != nil { - return nil, err - } - if err := validateStringParam(clientID, "clientID"); err != nil { - return nil, err - } - if err := validateStringParam(clientSecret, "clientSecret"); err != nil { - return nil, err - } - if err := validateStringParam(authorizationCode, "authorizationCode"); err != nil { - return nil, err - } - if err := validateStringParam(redirectURI, "redirectURI"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - - return NewServicePrincipalTokenWithSecret( - oauthConfig, - clientID, - resource, - &ServicePrincipalAuthorizationCodeSecret{ - ClientSecret: clientSecret, - AuthorizationCode: authorizationCode, - RedirectURI: redirectURI, - }, - callbacks..., - ) -} - -// GetMSIVMEndpoint gets the MSI endpoint on Virtual Machines. -func GetMSIVMEndpoint() (string, error) { - return msiEndpoint, nil -} - -// NewServicePrincipalTokenFromMSI creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the system assigned identity when creating the token. -func NewServicePrincipalTokenFromMSI(msiEndpoint, resource string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, nil, callbacks...) -} - -// NewServicePrincipalTokenFromMSIWithUserAssignedID creates a ServicePrincipalToken via the MSI VM Extension. -// It will use the specified user assigned identity when creating the token. -func NewServicePrincipalTokenFromMSIWithUserAssignedID(msiEndpoint, resource string, userAssignedID string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - return newServicePrincipalTokenFromMSI(msiEndpoint, resource, &userAssignedID, callbacks...) -} - -func newServicePrincipalTokenFromMSI(msiEndpoint, resource string, userAssignedID *string, callbacks ...TokenRefreshCallback) (*ServicePrincipalToken, error) { - if err := validateStringParam(msiEndpoint, "msiEndpoint"); err != nil { - return nil, err - } - if err := validateStringParam(resource, "resource"); err != nil { - return nil, err - } - if userAssignedID != nil { - if err := validateStringParam(*userAssignedID, "userAssignedID"); err != nil { - return nil, err - } - } - // We set the oauth config token endpoint to be MSI's endpoint - msiEndpointURL, err := url.Parse(msiEndpoint) - if err != nil { - return nil, err - } - - v := url.Values{} - v.Set("resource", resource) - v.Set("api-version", "2018-02-01") - if userAssignedID != nil { - v.Set("client_id", *userAssignedID) - } - msiEndpointURL.RawQuery = v.Encode() - - spt := &ServicePrincipalToken{ - oauthConfig: OAuthConfig{ - TokenEndpoint: *msiEndpointURL, - }, - secret: &ServicePrincipalMSISecret{}, - resource: resource, - autoRefresh: true, - refreshLock: &sync.RWMutex{}, - refreshWithin: defaultRefresh, - sender: &http.Client{}, - refreshCallbacks: callbacks, - } - - if userAssignedID != nil { - spt.clientID = *userAssignedID - } - - return spt, nil -} - -// internal type that implements TokenRefreshError -type tokenRefreshError struct { - message string - resp *http.Response -} - -// Error implements the error interface which is part of the TokenRefreshError interface. -func (tre tokenRefreshError) Error() string { - return tre.message -} - -// Response implements the TokenRefreshError interface, it returns the raw HTTP response from the refresh operation. -func (tre tokenRefreshError) Response() *http.Response { - return tre.resp -} - -func newTokenRefreshError(message string, resp *http.Response) TokenRefreshError { - return tokenRefreshError{message: message, resp: resp} -} - -// EnsureFresh will refresh the token if it will expire within the refresh window (as set by -// RefreshWithin) and autoRefresh flag is on. This method is safe for concurrent use. -func (spt *ServicePrincipalToken) EnsureFresh() error { - if spt.autoRefresh && spt.token.WillExpireIn(spt.refreshWithin) { - // take the write lock then check to see if the token was already refreshed - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - if spt.token.WillExpireIn(spt.refreshWithin) { - return spt.refreshInternal(spt.resource) - } - } - return nil -} - -// InvokeRefreshCallbacks calls any TokenRefreshCallbacks that were added to the SPT during initialization -func (spt *ServicePrincipalToken) InvokeRefreshCallbacks(token Token) error { - if spt.refreshCallbacks != nil { - for _, callback := range spt.refreshCallbacks { - err := callback(spt.token) - if err != nil { - return fmt.Errorf("adal: TokenRefreshCallback handler failed. Error = '%v'", err) - } - } - } - return nil -} - -// Refresh obtains a fresh token for the Service Principal. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) Refresh() error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(spt.resource) -} - -// RefreshExchange refreshes the token, but for a different resource. -// This method is not safe for concurrent use and should be syncrhonized. -func (spt *ServicePrincipalToken) RefreshExchange(resource string) error { - spt.refreshLock.Lock() - defer spt.refreshLock.Unlock() - return spt.refreshInternal(resource) -} - -func (spt *ServicePrincipalToken) getGrantType() string { - switch spt.secret.(type) { - case *ServicePrincipalUsernamePasswordSecret: - return OAuthGrantTypeUserPass - case *ServicePrincipalAuthorizationCodeSecret: - return OAuthGrantTypeAuthorizationCode - default: - return OAuthGrantTypeClientCredentials - } -} - -func isIMDS(u url.URL) bool { - imds, err := url.Parse(msiEndpoint) - if err != nil { - return false - } - return u.Host == imds.Host && u.Path == imds.Path -} - -func (spt *ServicePrincipalToken) refreshInternal(resource string) error { - req, err := http.NewRequest(http.MethodPost, spt.oauthConfig.TokenEndpoint.String(), nil) - if err != nil { - return fmt.Errorf("adal: Failed to build the refresh request. Error = '%v'", err) - } - - if !isIMDS(spt.oauthConfig.TokenEndpoint) { - v := url.Values{} - v.Set("client_id", spt.clientID) - v.Set("resource", resource) - - if spt.token.RefreshToken != "" { - v.Set("grant_type", OAuthGrantTypeRefreshToken) - v.Set("refresh_token", spt.token.RefreshToken) - } else { - v.Set("grant_type", spt.getGrantType()) - err := spt.secret.SetAuthenticationValues(spt, &v) - if err != nil { - return err - } - } - - s := v.Encode() - body := ioutil.NopCloser(strings.NewReader(s)) - req.ContentLength = int64(len(s)) - req.Header.Set(contentType, mimeTypeFormPost) - req.Body = body - } - - if _, ok := spt.secret.(*ServicePrincipalMSISecret); ok { - req.Method = http.MethodGet - req.Header.Set(metadataHeader, "true") - } - - resp, err := spt.sender.Do(req) - if err != nil { - return fmt.Errorf("adal: Failed to execute the refresh request. Error = '%v'", err) - } - - defer resp.Body.Close() - rb, err := ioutil.ReadAll(resp.Body) - - if resp.StatusCode != http.StatusOK { - if err != nil { - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Failed reading response body", resp.StatusCode), resp) - } - return newTokenRefreshError(fmt.Sprintf("adal: Refresh request failed. Status Code = '%d'. Response body: %s", resp.StatusCode, string(rb)), resp) - } - - if err != nil { - return fmt.Errorf("adal: Failed to read a new service principal token during refresh. Error = '%v'", err) - } - if len(strings.Trim(string(rb), " ")) == 0 { - return fmt.Errorf("adal: Empty service principal token received during refresh") - } - var token Token - err = json.Unmarshal(rb, &token) - if err != nil { - return fmt.Errorf("adal: Failed to unmarshal the service principal token during refresh. Error = '%v' JSON = '%s'", err, string(rb)) - } - - spt.token = token - - return spt.InvokeRefreshCallbacks(token) -} - -// SetAutoRefresh enables or disables automatic refreshing of stale tokens. -func (spt *ServicePrincipalToken) SetAutoRefresh(autoRefresh bool) { - spt.autoRefresh = autoRefresh -} - -// SetRefreshWithin sets the interval within which if the token will expire, EnsureFresh will -// refresh the token. -func (spt *ServicePrincipalToken) SetRefreshWithin(d time.Duration) { - spt.refreshWithin = d - return -} - -// SetSender sets the http.Client used when obtaining the Service Principal token. An -// undecorated http.Client is used by default. -func (spt *ServicePrincipalToken) SetSender(s Sender) { spt.sender = s } - -// OAuthToken implements the OAuthTokenProvider interface. It returns the current access token. -func (spt *ServicePrincipalToken) OAuthToken() string { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.token.OAuthToken() -} - -// Token returns a copy of the current token. -func (spt *ServicePrincipalToken) Token() Token { - spt.refreshLock.RLock() - defer spt.refreshLock.RUnlock() - return spt.token -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/authorization.go b/vendor/github.com/Azure/go-autorest/autorest/authorization.go deleted file mode 100644 index c51eac0a7..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/authorization.go +++ /dev/null @@ -1,257 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -const ( - bearerChallengeHeader = "Www-Authenticate" - bearer = "Bearer" - tenantID = "tenantID" - apiKeyAuthorizerHeader = "Ocp-Apim-Subscription-Key" - bingAPISdkHeader = "X-BingApis-SDK-Client" - golangBingAPISdkHeaderValue = "Go-SDK" -) - -// Authorizer is the interface that provides a PrepareDecorator used to supply request -// authorization. Most often, the Authorizer decorator runs last so it has access to the full -// state of the formed HTTP request. -type Authorizer interface { - WithAuthorization() PrepareDecorator -} - -// NullAuthorizer implements a default, "do nothing" Authorizer. -type NullAuthorizer struct{} - -// WithAuthorization returns a PrepareDecorator that does nothing. -func (na NullAuthorizer) WithAuthorization() PrepareDecorator { - return WithNothing() -} - -// APIKeyAuthorizer implements API Key authorization. -type APIKeyAuthorizer struct { - headers map[string]interface{} - queryParameters map[string]interface{} -} - -// NewAPIKeyAuthorizerWithHeaders creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizerWithHeaders(headers map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(headers, nil) -} - -// NewAPIKeyAuthorizerWithQueryParameters creates an ApiKeyAuthorizer with query parameters. -func NewAPIKeyAuthorizerWithQueryParameters(queryParameters map[string]interface{}) *APIKeyAuthorizer { - return NewAPIKeyAuthorizer(nil, queryParameters) -} - -// NewAPIKeyAuthorizer creates an ApiKeyAuthorizer with headers. -func NewAPIKeyAuthorizer(headers map[string]interface{}, queryParameters map[string]interface{}) *APIKeyAuthorizer { - return &APIKeyAuthorizer{headers: headers, queryParameters: queryParameters} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP headers and Query Paramaters -func (aka *APIKeyAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return DecoratePreparer(p, WithHeaders(aka.headers), WithQueryParameters(aka.queryParameters)) - } -} - -// CognitiveServicesAuthorizer implements authorization for Cognitive Services. -type CognitiveServicesAuthorizer struct { - subscriptionKey string -} - -// NewCognitiveServicesAuthorizer is -func NewCognitiveServicesAuthorizer(subscriptionKey string) *CognitiveServicesAuthorizer { - return &CognitiveServicesAuthorizer{subscriptionKey: subscriptionKey} -} - -// WithAuthorization is -func (csa *CognitiveServicesAuthorizer) WithAuthorization() PrepareDecorator { - headers := make(map[string]interface{}) - headers[apiKeyAuthorizerHeader] = csa.subscriptionKey - headers[bingAPISdkHeader] = golangBingAPISdkHeaderValue - - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} - -// BearerAuthorizer implements the bearer authorization -type BearerAuthorizer struct { - tokenProvider adal.OAuthTokenProvider -} - -// NewBearerAuthorizer crates a BearerAuthorizer using the given token provider -func NewBearerAuthorizer(tp adal.OAuthTokenProvider) *BearerAuthorizer { - return &BearerAuthorizer{tokenProvider: tp} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the token. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (ba *BearerAuthorizer) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - refresher, ok := ba.tokenProvider.(adal.Refresher) - if ok { - err := refresher.EnsureFresh() - if err != nil { - var resp *http.Response - if tokError, ok := err.(adal.TokenRefreshError); ok { - resp = tokError.Response() - } - return r, NewErrorWithError(err, "azure.BearerAuthorizer", "WithAuthorization", resp, - "Failed to refresh the Token for request to %s", r.URL) - } - } - return Prepare(r, WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", ba.tokenProvider.OAuthToken()))) - } - return r, err - }) - } -} - -// BearerAuthorizerCallbackFunc is the authentication callback signature. -type BearerAuthorizerCallbackFunc func(tenantID, resource string) (*BearerAuthorizer, error) - -// BearerAuthorizerCallback implements bearer authorization via a callback. -type BearerAuthorizerCallback struct { - sender Sender - callback BearerAuthorizerCallbackFunc -} - -// NewBearerAuthorizerCallback creates a bearer authorization callback. The callback -// is invoked when the HTTP request is submitted. -func NewBearerAuthorizerCallback(sender Sender, callback BearerAuthorizerCallbackFunc) *BearerAuthorizerCallback { - if sender == nil { - sender = &http.Client{} - } - return &BearerAuthorizerCallback{sender: sender, callback: callback} -} - -// WithAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose value -// is "Bearer " followed by the token. The BearerAuthorizer is obtained via a user-supplied callback. -// -// By default, the token will be automatically refreshed through the Refresher interface. -func (bacb *BearerAuthorizerCallback) WithAuthorization() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - // make a copy of the request and remove the body as it's not - // required and avoids us having to create a copy of it. - rCopy := *r - removeRequestBody(&rCopy) - - resp, err := bacb.sender.Do(&rCopy) - if err == nil && resp.StatusCode == 401 { - defer resp.Body.Close() - if hasBearerChallenge(resp) { - bc, err := newBearerChallenge(resp) - if err != nil { - return r, err - } - if bacb.callback != nil { - ba, err := bacb.callback(bc.values[tenantID], bc.values["resource"]) - if err != nil { - return r, err - } - return Prepare(r, ba.WithAuthorization()) - } - } - } - } - return r, err - }) - } -} - -// returns true if the HTTP response contains a bearer challenge -func hasBearerChallenge(resp *http.Response) bool { - authHeader := resp.Header.Get(bearerChallengeHeader) - if len(authHeader) == 0 || strings.Index(authHeader, bearer) < 0 { - return false - } - return true -} - -type bearerChallenge struct { - values map[string]string -} - -func newBearerChallenge(resp *http.Response) (bc bearerChallenge, err error) { - challenge := strings.TrimSpace(resp.Header.Get(bearerChallengeHeader)) - trimmedChallenge := challenge[len(bearer)+1:] - - // challenge is a set of key=value pairs that are comma delimited - pairs := strings.Split(trimmedChallenge, ",") - if len(pairs) < 1 { - err = fmt.Errorf("challenge '%s' contains no pairs", challenge) - return bc, err - } - - bc.values = make(map[string]string) - for i := range pairs { - trimmedPair := strings.TrimSpace(pairs[i]) - pair := strings.Split(trimmedPair, "=") - if len(pair) == 2 { - // remove the enclosing quotes - key := strings.Trim(pair[0], "\"") - value := strings.Trim(pair[1], "\"") - - switch key { - case "authorization", "authorization_uri": - // strip the tenant ID from the authorization URL - asURL, err := url.Parse(value) - if err != nil { - return bc, err - } - bc.values[tenantID] = asURL.Path[1:] - default: - bc.values[key] = value - } - } - } - - return bc, err -} - -// EventGridKeyAuthorizer implements authorization for event grid using key authentication. -type EventGridKeyAuthorizer struct { - topicKey string -} - -// NewEventGridKeyAuthorizer creates a new EventGridKeyAuthorizer -// with the specified topic key. -func NewEventGridKeyAuthorizer(topicKey string) EventGridKeyAuthorizer { - return EventGridKeyAuthorizer{topicKey: topicKey} -} - -// WithAuthorization returns a PrepareDecorator that adds the aeg-sas-key authentication header. -func (egta EventGridKeyAuthorizer) WithAuthorization() PrepareDecorator { - headers := map[string]interface{}{ - "aeg-sas-key": egta.topicKey, - } - return NewAPIKeyAuthorizerWithHeaders(headers).WithAuthorization() -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/autorest.go b/vendor/github.com/Azure/go-autorest/autorest/autorest.go deleted file mode 100644 index aafdf021f..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/autorest.go +++ /dev/null @@ -1,150 +0,0 @@ -/* -Package autorest implements an HTTP request pipeline suitable for use across multiple go-routines -and provides the shared routines relied on by AutoRest (see https://github.com/Azure/autorest/) -generated Go code. - -The package breaks sending and responding to HTTP requests into three phases: Preparing, Sending, -and Responding. A typical pattern is: - - req, err := Prepare(&http.Request{}, - token.WithAuthorization()) - - resp, err := Send(req, - WithLogging(logger), - DoErrorIfStatusCode(http.StatusInternalServerError), - DoCloseIfError(), - DoRetryForAttempts(5, time.Second)) - - err = Respond(resp, - ByDiscardingBody(), - ByClosing()) - -Each phase relies on decorators to modify and / or manage processing. Decorators may first modify -and then pass the data along, pass the data first and then modify the result, or wrap themselves -around passing the data (such as a logger might do). Decorators run in the order provided. For -example, the following: - - req, err := Prepare(&http.Request{}, - WithBaseURL("https://microsoft.com/"), - WithPath("a"), - WithPath("b"), - WithPath("c")) - -will set the URL to: - - https://microsoft.com/a/b/c - -Preparers and Responders may be shared and re-used (assuming the underlying decorators support -sharing and re-use). Performant use is obtained by creating one or more Preparers and Responders -shared among multiple go-routines, and a single Sender shared among multiple sending go-routines, -all bound together by means of input / output channels. - -Decorators hold their passed state within a closure (such as the path components in the example -above). Be careful to share Preparers and Responders only in a context where such held state -applies. For example, it may not make sense to share a Preparer that applies a query string from a -fixed set of values. Similarly, sharing a Responder that reads the response body into a passed -struct (e.g., ByUnmarshallingJson) is likely incorrect. - -Lastly, the Swagger specification (https://swagger.io) that drives AutoRest -(https://github.com/Azure/autorest/) precisely defines two date forms: date and date-time. The -github.com/Azure/go-autorest/autorest/date package provides time.Time derivations to ensure -correct parsing and formatting. - -Errors raised by autorest objects and methods will conform to the autorest.Error interface. - -See the included examples for more detail. For details on the suggested use of this package by -generated clients, see the Client described below. -*/ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "context" - "net/http" - "time" -) - -const ( - // HeaderLocation specifies the HTTP Location header. - HeaderLocation = "Location" - - // HeaderRetryAfter specifies the HTTP Retry-After header. - HeaderRetryAfter = "Retry-After" -) - -// ResponseHasStatusCode returns true if the status code in the HTTP Response is in the passed set -// and false otherwise. -func ResponseHasStatusCode(resp *http.Response, codes ...int) bool { - if resp == nil { - return false - } - return containsInt(codes, resp.StatusCode) -} - -// GetLocation retrieves the URL from the Location header of the passed response. -func GetLocation(resp *http.Response) string { - return resp.Header.Get(HeaderLocation) -} - -// GetRetryAfter extracts the retry delay from the Retry-After header of the passed response. If -// the header is absent or is malformed, it will return the supplied default delay time.Duration. -func GetRetryAfter(resp *http.Response, defaultDelay time.Duration) time.Duration { - retry := resp.Header.Get(HeaderRetryAfter) - if retry == "" { - return defaultDelay - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - return defaultDelay - } - - return d -} - -// NewPollingRequest allocates and returns a new http.Request to poll for the passed response. -func NewPollingRequest(resp *http.Response, cancel <-chan struct{}) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequest", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare(&http.Request{Cancel: cancel}, - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequest", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} - -// NewPollingRequestWithContext allocates and returns a new http.Request with the specified context to poll for the passed response. -func NewPollingRequestWithContext(ctx context.Context, resp *http.Response) (*http.Request, error) { - location := GetLocation(resp) - if location == "" { - return nil, NewErrorWithResponse("autorest", "NewPollingRequestWithContext", resp, "Location header missing from response that requires polling") - } - - req, err := Prepare((&http.Request{}).WithContext(ctx), - AsGet(), - WithBaseURL(location)) - if err != nil { - return nil, NewErrorWithError(err, "autorest", "NewPollingRequestWithContext", nil, "Failure creating poll request to %s", location) - } - - return req, nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go b/vendor/github.com/Azure/go-autorest/autorest/azure/async.go deleted file mode 100644 index a58e5ef3f..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/async.go +++ /dev/null @@ -1,511 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/date" -) - -const ( - headerAsyncOperation = "Azure-AsyncOperation" -) - -const ( - operationInProgress string = "InProgress" - operationCanceled string = "Canceled" - operationFailed string = "Failed" - operationSucceeded string = "Succeeded" -) - -var pollingCodes = [...]int{http.StatusNoContent, http.StatusAccepted, http.StatusCreated, http.StatusOK} - -// Future provides a mechanism to access the status and results of an asynchronous request. -// Since futures are stateful they should be passed by value to avoid race conditions. -type Future struct { - req *http.Request - resp *http.Response - ps pollingState -} - -// NewFuture returns a new Future object initialized with the specified request. -func NewFuture(req *http.Request) Future { - return Future{req: req} -} - -// Response returns the last HTTP response or nil if there isn't one. -func (f Future) Response() *http.Response { - return f.resp -} - -// Status returns the last status message of the operation. -func (f Future) Status() string { - if f.ps.State == "" { - return "Unknown" - } - return f.ps.State -} - -// PollingMethod returns the method used to monitor the status of the asynchronous operation. -func (f Future) PollingMethod() PollingMethodType { - return f.ps.PollingMethod -} - -// Done queries the service to see if the operation has completed. -func (f *Future) Done(sender autorest.Sender) (bool, error) { - // exit early if this future has terminated - if f.ps.hasTerminated() { - return true, f.errorInfo() - } - resp, err := sender.Do(f.req) - f.resp = resp - if err != nil { - return false, err - } - - if !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { - // check response body for error content - if resp.Body != nil { - type respErr struct { - ServiceError ServiceError `json:"error"` - } - re := respErr{} - - defer resp.Body.Close() - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return false, err - } - err = json.Unmarshal(b, &re) - if err != nil { - return false, err - } - return false, re.ServiceError - } - - // try to return something meaningful - return false, ServiceError{ - Code: fmt.Sprintf("%v", resp.StatusCode), - Message: resp.Status, - } - } - - err = updatePollingState(resp, &f.ps) - if err != nil { - return false, err - } - - if f.ps.hasTerminated() { - return true, f.errorInfo() - } - - f.req, err = newPollingRequest(f.ps) - return false, err -} - -// GetPollingDelay returns a duration the application should wait before checking -// the status of the asynchronous request and true; this value is returned from -// the service via the Retry-After response header. If the header wasn't returned -// then the function returns the zero-value time.Duration and false. -func (f Future) GetPollingDelay() (time.Duration, bool) { - if f.resp == nil { - return 0, false - } - - retry := f.resp.Header.Get(autorest.HeaderRetryAfter) - if retry == "" { - return 0, false - } - - d, err := time.ParseDuration(retry + "s") - if err != nil { - panic(err) - } - - return d, true -} - -// WaitForCompletion will return when one of the following conditions is met: the long -// running operation has completed, the provided context is cancelled, or the client's -// polling duration has been exceeded. It will retry failed polling attempts based on -// the retry value defined in the client up to the maximum retry attempts. -func (f Future) WaitForCompletion(ctx context.Context, client autorest.Client) error { - ctx, cancel := context.WithTimeout(ctx, client.PollingDuration) - defer cancel() - - done, err := f.Done(client) - for attempts := 0; !done; done, err = f.Done(client) { - if attempts >= client.RetryAttempts { - return autorest.NewErrorWithError(err, "azure", "WaitForCompletion", f.resp, "the number of retries has been exceeded") - } - // we want delayAttempt to be zero in the non-error case so - // that DelayForBackoff doesn't perform exponential back-off - var delayAttempt int - var delay time.Duration - if err == nil { - // check for Retry-After delay, if not present use the client's polling delay - var ok bool - delay, ok = f.GetPollingDelay() - if !ok { - delay = client.PollingDelay - } - } else { - // there was an error polling for status so perform exponential - // back-off based on the number of attempts using the client's retry - // duration. update attempts after delayAttempt to avoid off-by-one. - delayAttempt = attempts - delay = client.RetryDuration - attempts++ - } - // wait until the delay elapses or the context is cancelled - delayElapsed := autorest.DelayForBackoff(delay, delayAttempt, ctx.Done()) - if !delayElapsed { - return autorest.NewErrorWithError(ctx.Err(), "azure", "WaitForCompletion", f.resp, "context has been cancelled") - } - } - return err -} - -// if the operation failed the polling state will contain -// error information and implements the error interface -func (f *Future) errorInfo() error { - if !f.ps.hasSucceeded() { - return f.ps - } - return nil -} - -// MarshalJSON implements the json.Marshaler interface. -func (f Future) MarshalJSON() ([]byte, error) { - return json.Marshal(&f.ps) -} - -// UnmarshalJSON implements the json.Unmarshaler interface. -func (f *Future) UnmarshalJSON(data []byte) error { - err := json.Unmarshal(data, &f.ps) - if err != nil { - return err - } - f.req, err = newPollingRequest(f.ps) - return err -} - -// PollingURL returns the URL used for retrieving the status of the long-running operation. -// For LROs that use the Location header the final URL value is used to retrieve the result. -func (f Future) PollingURL() string { - return f.ps.URI -} - -// DoPollForAsynchronous returns a SendDecorator that polls if the http.Response is for an Azure -// long-running operation. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by -// closing the optional channel on the http.Request. -func DoPollForAsynchronous(delay time.Duration) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - resp, err = s.Do(r) - if err != nil { - return resp, err - } - if !autorest.ResponseHasStatusCode(resp, pollingCodes[:]...) { - return resp, nil - } - - ps := pollingState{} - for err == nil { - err = updatePollingState(resp, &ps) - if err != nil { - break - } - if ps.hasTerminated() { - if !ps.hasSucceeded() { - err = ps - } - break - } - - r, err = newPollingRequest(ps) - if err != nil { - return resp, err - } - r = r.WithContext(resp.Request.Context()) - - delay = autorest.GetRetryAfter(resp, delay) - resp, err = autorest.SendWithSender(s, r, - autorest.AfterDelay(delay)) - } - - return resp, err - }) - } -} - -func getAsyncOperation(resp *http.Response) string { - return resp.Header.Get(http.CanonicalHeaderKey(headerAsyncOperation)) -} - -func hasSucceeded(state string) bool { - return strings.EqualFold(state, operationSucceeded) -} - -func hasTerminated(state string) bool { - return strings.EqualFold(state, operationCanceled) || strings.EqualFold(state, operationFailed) || strings.EqualFold(state, operationSucceeded) -} - -func hasFailed(state string) bool { - return strings.EqualFold(state, operationFailed) -} - -type provisioningTracker interface { - state() string - hasSucceeded() bool - hasTerminated() bool -} - -type operationResource struct { - // Note: - // The specification states services should return the "id" field. However some return it as - // "operationId". - ID string `json:"id"` - OperationID string `json:"operationId"` - Name string `json:"name"` - Status string `json:"status"` - Properties map[string]interface{} `json:"properties"` - OperationError ServiceError `json:"error"` - StartTime date.Time `json:"startTime"` - EndTime date.Time `json:"endTime"` - PercentComplete float64 `json:"percentComplete"` -} - -func (or operationResource) state() string { - return or.Status -} - -func (or operationResource) hasSucceeded() bool { - return hasSucceeded(or.state()) -} - -func (or operationResource) hasTerminated() bool { - return hasTerminated(or.state()) -} - -type provisioningProperties struct { - ProvisioningState string `json:"provisioningState"` -} - -type provisioningStatus struct { - Properties provisioningProperties `json:"properties,omitempty"` - ProvisioningError ServiceError `json:"error,omitempty"` -} - -func (ps provisioningStatus) state() string { - return ps.Properties.ProvisioningState -} - -func (ps provisioningStatus) hasSucceeded() bool { - return hasSucceeded(ps.state()) -} - -func (ps provisioningStatus) hasTerminated() bool { - return hasTerminated(ps.state()) -} - -func (ps provisioningStatus) hasProvisioningError() bool { - // code and message are required fields so only check them - return len(ps.ProvisioningError.Code) > 0 || - len(ps.ProvisioningError.Message) > 0 -} - -// PollingMethodType defines a type used for enumerating polling mechanisms. -type PollingMethodType string - -const ( - // PollingAsyncOperation indicates the polling method uses the Azure-AsyncOperation header. - PollingAsyncOperation PollingMethodType = "AsyncOperation" - - // PollingLocation indicates the polling method uses the Location header. - PollingLocation PollingMethodType = "Location" - - // PollingUnknown indicates an unknown polling method and is the default value. - PollingUnknown PollingMethodType = "" -) - -type pollingState struct { - PollingMethod PollingMethodType `json:"pollingMethod"` - URI string `json:"uri"` - State string `json:"state"` - ServiceError *ServiceError `json:"error,omitempty"` -} - -func (ps pollingState) hasSucceeded() bool { - return hasSucceeded(ps.State) -} - -func (ps pollingState) hasTerminated() bool { - return hasTerminated(ps.State) -} - -func (ps pollingState) hasFailed() bool { - return hasFailed(ps.State) -} - -func (ps pollingState) Error() string { - s := fmt.Sprintf("Long running operation terminated with status '%s'", ps.State) - if ps.ServiceError != nil { - s = fmt.Sprintf("%s: %+v", s, *ps.ServiceError) - } - return s -} - -// updatePollingState maps the operation status -- retrieved from either a provisioningState -// field, the status field of an OperationResource, or inferred from the HTTP status code -- -// into a well-known states. Since the process begins from the initial request, the state -// always comes from either a the provisioningState returned or is inferred from the HTTP -// status code. Subsequent requests will read an Azure OperationResource object if the -// service initially returned the Azure-AsyncOperation header. The responseFormat field notes -// the expected response format. -func updatePollingState(resp *http.Response, ps *pollingState) error { - // Determine the response shape - // -- The first response will always be a provisioningStatus response; only the polling requests, - // depending on the header returned, may be something otherwise. - var pt provisioningTracker - if ps.PollingMethod == PollingAsyncOperation { - pt = &operationResource{} - } else { - pt = &provisioningStatus{} - } - - // If this is the first request (that is, the polling response shape is unknown), determine how - // to poll and what to expect - if ps.PollingMethod == PollingUnknown { - req := resp.Request - if req == nil { - return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Original HTTP request is missing") - } - - // Prefer the Azure-AsyncOperation header - ps.URI = getAsyncOperation(resp) - if ps.URI != "" { - ps.PollingMethod = PollingAsyncOperation - } else { - ps.PollingMethod = PollingLocation - } - - // Else, use the Location header - if ps.URI == "" { - ps.URI = autorest.GetLocation(resp) - } - - // Lastly, requests against an existing resource, use the last request URI - if ps.URI == "" { - m := strings.ToUpper(req.Method) - if m == http.MethodPatch || m == http.MethodPut || m == http.MethodGet { - ps.URI = req.URL.String() - } - } - } - - // Read and interpret the response (saving the Body in case no polling is necessary) - b := &bytes.Buffer{} - err := autorest.Respond(resp, - autorest.ByCopying(b), - autorest.ByUnmarshallingJSON(pt), - autorest.ByClosing()) - resp.Body = ioutil.NopCloser(b) - if err != nil { - return err - } - - // Interpret the results - // -- Terminal states apply regardless - // -- Unknown states are per-service inprogress states - // -- Otherwise, infer state from HTTP status code - if pt.hasTerminated() { - ps.State = pt.state() - } else if pt.state() != "" { - ps.State = operationInProgress - } else { - switch resp.StatusCode { - case http.StatusAccepted: - ps.State = operationInProgress - - case http.StatusNoContent, http.StatusCreated, http.StatusOK: - ps.State = operationSucceeded - - default: - ps.State = operationFailed - } - } - - if strings.EqualFold(ps.State, operationInProgress) && ps.URI == "" { - return autorest.NewError("azure", "updatePollingState", "Azure Polling Error - Unable to obtain polling URI for %s %s", resp.Request.Method, resp.Request.URL) - } - - // For failed operation, check for error code and message in - // -- Operation resource - // -- Response - // -- Otherwise, Unknown - if ps.hasFailed() { - if or, ok := pt.(*operationResource); ok { - ps.ServiceError = &or.OperationError - } else if p, ok := pt.(*provisioningStatus); ok && p.hasProvisioningError() { - ps.ServiceError = &p.ProvisioningError - } else { - ps.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "None", - } - } - } - return nil -} - -func newPollingRequest(ps pollingState) (*http.Request, error) { - reqPoll, err := autorest.Prepare(&http.Request{}, - autorest.AsGet(), - autorest.WithBaseURL(ps.URI)) - if err != nil { - return nil, autorest.NewErrorWithError(err, "azure", "newPollingRequest", nil, "Failure creating poll request to %s", ps.URI) - } - - return reqPoll, nil -} - -// AsyncOpIncompleteError is the type that's returned from a future that has not completed. -type AsyncOpIncompleteError struct { - // FutureType is the name of the type composed of a azure.Future. - FutureType string -} - -// Error returns an error message including the originating type name of the error. -func (e AsyncOpIncompleteError) Error() string { - return fmt.Sprintf("%s: asynchronous operation has not completed", e.FutureType) -} - -// NewAsyncOpIncompleteError creates a new AsyncOpIncompleteError with the specified parameters. -func NewAsyncOpIncompleteError(futureType string) AsyncOpIncompleteError { - return AsyncOpIncompleteError{ - FutureType: futureType, - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go b/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go deleted file mode 100644 index dd89d9c9d..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/auth/auth.go +++ /dev/null @@ -1,408 +0,0 @@ -package auth - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "crypto/rsa" - "crypto/x509" - "encoding/binary" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "os" - "strings" - "unicode/utf16" - - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/dimchansky/utfbom" - "golang.org/x/crypto/pkcs12" -) - -// NewAuthorizerFromEnvironment creates an Authorizer configured from environment variables in the order: -// 1. Client credentials -// 2. Client certificate -// 3. Username password -// 4. MSI -func NewAuthorizerFromEnvironment() (autorest.Authorizer, error) { - tenantID := os.Getenv("AZURE_TENANT_ID") - clientID := os.Getenv("AZURE_CLIENT_ID") - clientSecret := os.Getenv("AZURE_CLIENT_SECRET") - certificatePath := os.Getenv("AZURE_CERTIFICATE_PATH") - certificatePassword := os.Getenv("AZURE_CERTIFICATE_PASSWORD") - username := os.Getenv("AZURE_USERNAME") - password := os.Getenv("AZURE_PASSWORD") - envName := os.Getenv("AZURE_ENVIRONMENT") - resource := os.Getenv("AZURE_AD_RESOURCE") - - var env azure.Environment - if envName == "" { - env = azure.PublicCloud - } else { - var err error - env, err = azure.EnvironmentFromName(envName) - if err != nil { - return nil, err - } - } - - if resource == "" { - resource = env.ResourceManagerEndpoint - } - - //1.Client Credentials - if clientSecret != "" { - config := NewClientCredentialsConfig(clientID, clientSecret, tenantID) - config.AADEndpoint = env.ActiveDirectoryEndpoint - config.Resource = resource - return config.Authorizer() - } - - //2. Client Certificate - if certificatePath != "" { - config := NewClientCertificateConfig(certificatePath, certificatePassword, clientID, tenantID) - config.AADEndpoint = env.ActiveDirectoryEndpoint - config.Resource = resource - return config.Authorizer() - } - - //3. Username Password - if username != "" && password != "" { - config := NewUsernamePasswordConfig(username, password, clientID, tenantID) - config.AADEndpoint = env.ActiveDirectoryEndpoint - config.Resource = resource - return config.Authorizer() - } - - // 4. MSI - config := NewMSIConfig() - config.Resource = resource - config.ClientID = clientID - return config.Authorizer() -} - -// NewAuthorizerFromFile creates an Authorizer configured from a configuration file. -func NewAuthorizerFromFile(baseURI string) (autorest.Authorizer, error) { - fileLocation := os.Getenv("AZURE_AUTH_LOCATION") - if fileLocation == "" { - return nil, errors.New("auth file not found. Environment variable AZURE_AUTH_LOCATION is not set") - } - - contents, err := ioutil.ReadFile(fileLocation) - if err != nil { - return nil, err - } - - // Auth file might be encoded - decoded, err := decode(contents) - if err != nil { - return nil, err - } - - file := file{} - err = json.Unmarshal(decoded, &file) - if err != nil { - return nil, err - } - - resource, err := getResourceForToken(file, baseURI) - if err != nil { - return nil, err - } - - config, err := adal.NewOAuthConfig(file.ActiveDirectoryEndpoint, file.TenantID) - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalToken(*config, file.ClientID, file.ClientSecret, resource) - if err != nil { - return nil, err - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// File represents the authentication file -type file struct { - ClientID string `json:"clientId,omitempty"` - ClientSecret string `json:"clientSecret,omitempty"` - SubscriptionID string `json:"subscriptionId,omitempty"` - TenantID string `json:"tenantId,omitempty"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpointUrl,omitempty"` - ResourceManagerEndpoint string `json:"resourceManagerEndpointUrl,omitempty"` - GraphResourceID string `json:"activeDirectoryGraphResourceId,omitempty"` - SQLManagementEndpoint string `json:"sqlManagementEndpointUrl,omitempty"` - GalleryEndpoint string `json:"galleryEndpointUrl,omitempty"` - ManagementEndpoint string `json:"managementEndpointUrl,omitempty"` -} - -func decode(b []byte) ([]byte, error) { - reader, enc := utfbom.Skip(bytes.NewReader(b)) - - switch enc { - case utfbom.UTF16LittleEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.LittleEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - case utfbom.UTF16BigEndian: - u16 := make([]uint16, (len(b)/2)-1) - err := binary.Read(reader, binary.BigEndian, &u16) - if err != nil { - return nil, err - } - return []byte(string(utf16.Decode(u16))), nil - } - return ioutil.ReadAll(reader) -} - -func getResourceForToken(f file, baseURI string) (string, error) { - // Compare dafault base URI from the SDK to the endpoints from the public cloud - // Base URI and token resource are the same string. This func finds the authentication - // file field that matches the SDK base URI. The SDK defines the public cloud - // endpoint as its default base URI - if !strings.HasSuffix(baseURI, "/") { - baseURI += "/" - } - switch baseURI { - case azure.PublicCloud.ServiceManagementEndpoint: - return f.ManagementEndpoint, nil - case azure.PublicCloud.ResourceManagerEndpoint: - return f.ResourceManagerEndpoint, nil - case azure.PublicCloud.ActiveDirectoryEndpoint: - return f.ActiveDirectoryEndpoint, nil - case azure.PublicCloud.GalleryEndpoint: - return f.GalleryEndpoint, nil - case azure.PublicCloud.GraphEndpoint: - return f.GraphResourceID, nil - } - return "", fmt.Errorf("auth: base URI not found in endpoints") -} - -// NewClientCredentialsConfig creates an AuthorizerConfig object configured to obtain an Authorizer through Client Credentials. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCredentialsConfig(clientID string, clientSecret string, tenantID string) ClientCredentialsConfig { - return ClientCredentialsConfig{ - ClientID: clientID, - ClientSecret: clientSecret, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewClientCertificateConfig creates a ClientCertificateConfig object configured to obtain an Authorizer through client certificate. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewClientCertificateConfig(certificatePath string, certificatePassword string, clientID string, tenantID string) ClientCertificateConfig { - return ClientCertificateConfig{ - CertificatePath: certificatePath, - CertificatePassword: certificatePassword, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewUsernamePasswordConfig creates an UsernamePasswordConfig object configured to obtain an Authorizer through username and password. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewUsernamePasswordConfig(username string, password string, clientID string, tenantID string) UsernamePasswordConfig { - return UsernamePasswordConfig{ - Username: username, - Password: password, - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -// NewMSIConfig creates an MSIConfig object configured to obtain an Authorizer through MSI. -func NewMSIConfig() MSIConfig { - return MSIConfig{ - Resource: azure.PublicCloud.ResourceManagerEndpoint, - } -} - -// NewDeviceFlowConfig creates a DeviceFlowConfig object configured to obtain an Authorizer through device flow. -// Defaults to Public Cloud and Resource Manager Endpoint. -func NewDeviceFlowConfig(clientID string, tenantID string) DeviceFlowConfig { - return DeviceFlowConfig{ - ClientID: clientID, - TenantID: tenantID, - Resource: azure.PublicCloud.ResourceManagerEndpoint, - AADEndpoint: azure.PublicCloud.ActiveDirectoryEndpoint, - } -} - -//AuthorizerConfig provides an authorizer from the configuration provided. -type AuthorizerConfig interface { - Authorizer() (autorest.Authorizer, error) -} - -// ClientCredentialsConfig provides the options to get a bearer authorizer from client credentials. -type ClientCredentialsConfig struct { - ClientID string - ClientSecret string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from client credentials. -func (ccc ClientCredentialsConfig) Authorizer() (autorest.Authorizer, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalToken(*oauthConfig, ccc.ClientID, ccc.ClientSecret, ccc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from client credentials: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// ClientCertificateConfig provides the options to get a bearer authorizer from a client certificate. -type ClientCertificateConfig struct { - ClientID string - CertificatePath string - CertificatePassword string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets an authorizer object from client certificate. -func (ccc ClientCertificateConfig) Authorizer() (autorest.Authorizer, error) { - oauthConfig, err := adal.NewOAuthConfig(ccc.AADEndpoint, ccc.TenantID) - - certData, err := ioutil.ReadFile(ccc.CertificatePath) - if err != nil { - return nil, fmt.Errorf("failed to read the certificate file (%s): %v", ccc.CertificatePath, err) - } - - certificate, rsaPrivateKey, err := decodePkcs12(certData, ccc.CertificatePassword) - if err != nil { - return nil, fmt.Errorf("failed to decode pkcs12 certificate while creating spt: %v", err) - } - - spToken, err := adal.NewServicePrincipalTokenFromCertificate(*oauthConfig, ccc.ClientID, certificate, rsaPrivateKey, ccc.Resource) - - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from certificate auth: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// DeviceFlowConfig provides the options to get a bearer authorizer using device flow authentication. -type DeviceFlowConfig struct { - ClientID string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from device flow. -func (dfc DeviceFlowConfig) Authorizer() (autorest.Authorizer, error) { - oauthClient := &autorest.Client{} - oauthConfig, err := adal.NewOAuthConfig(dfc.AADEndpoint, dfc.TenantID) - deviceCode, err := adal.InitiateDeviceAuth(oauthClient, *oauthConfig, dfc.ClientID, dfc.AADEndpoint) - if err != nil { - return nil, fmt.Errorf("failed to start device auth flow: %s", err) - } - - log.Println(*deviceCode.Message) - - token, err := adal.WaitForUserCompletion(oauthClient, deviceCode) - if err != nil { - return nil, fmt.Errorf("failed to finish device auth flow: %s", err) - } - - spToken, err := adal.NewServicePrincipalTokenFromManualToken(*oauthConfig, dfc.ClientID, dfc.Resource, *token) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from device flow: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -func decodePkcs12(pkcs []byte, password string) (*x509.Certificate, *rsa.PrivateKey, error) { - privateKey, certificate, err := pkcs12.Decode(pkcs, password) - if err != nil { - return nil, nil, err - } - - rsaPrivateKey, isRsaKey := privateKey.(*rsa.PrivateKey) - if !isRsaKey { - return nil, nil, fmt.Errorf("PKCS#12 certificate must contain an RSA private key") - } - - return certificate, rsaPrivateKey, nil -} - -// UsernamePasswordConfig provides the options to get a bearer authorizer from a username and a password. -type UsernamePasswordConfig struct { - ClientID string - Username string - Password string - TenantID string - AADEndpoint string - Resource string -} - -// Authorizer gets the authorizer from a username and a password. -func (ups UsernamePasswordConfig) Authorizer() (autorest.Authorizer, error) { - - oauthConfig, err := adal.NewOAuthConfig(ups.AADEndpoint, ups.TenantID) - - spToken, err := adal.NewServicePrincipalTokenFromUsernamePassword(*oauthConfig, ups.ClientID, ups.Username, ups.Password, ups.Resource) - - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from username and password auth: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} - -// MSIConfig provides the options to get a bearer authorizer through MSI. -type MSIConfig struct { - Resource string - ClientID string -} - -// Authorizer gets the authorizer from MSI. -func (mc MSIConfig) Authorizer() (autorest.Authorizer, error) { - msiEndpoint, err := adal.GetMSIVMEndpoint() - if err != nil { - return nil, err - } - - spToken, err := adal.NewServicePrincipalTokenFromMSI(msiEndpoint, mc.Resource) - if err != nil { - return nil, fmt.Errorf("failed to get oauth token from MSI: %v", err) - } - - return autorest.NewBearerAuthorizer(spToken), nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go b/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go deleted file mode 100644 index 18d029526..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/azure.go +++ /dev/null @@ -1,301 +0,0 @@ -// Package azure provides Azure-specific implementations used with AutoRest. -// See the included examples for more detail. -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -const ( - // HeaderClientID is the Azure extension header to set a user-specified request ID. - HeaderClientID = "x-ms-client-request-id" - - // HeaderReturnClientID is the Azure extension header to set if the user-specified request ID - // should be included in the response. - HeaderReturnClientID = "x-ms-return-client-request-id" - - // HeaderRequestID is the Azure extension header of the service generated request ID returned - // in the response. - HeaderRequestID = "x-ms-request-id" -) - -// ServiceError encapsulates the error response from an Azure service. -// It adhears to the OData v4 specification for error responses. -type ServiceError struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` -} - -func (se ServiceError) Error() string { - result := fmt.Sprintf("Code=%q Message=%q", se.Code, se.Message) - - if se.Target != nil { - result += fmt.Sprintf(" Target=%q", *se.Target) - } - - if se.Details != nil { - d, err := json.Marshal(se.Details) - if err != nil { - result += fmt.Sprintf(" Details=%v", se.Details) - } - result += fmt.Sprintf(" Details=%v", string(d)) - } - - if se.InnerError != nil { - d, err := json.Marshal(se.InnerError) - if err != nil { - result += fmt.Sprintf(" InnerError=%v", se.InnerError) - } - result += fmt.Sprintf(" InnerError=%v", string(d)) - } - - return result -} - -// UnmarshalJSON implements the json.Unmarshaler interface for the ServiceError type. -func (se *ServiceError) UnmarshalJSON(b []byte) error { - // per the OData v4 spec the details field must be an array of JSON objects. - // unfortunately not all services adhear to the spec and just return a single - // object instead of an array with one object. so we have to perform some - // shenanigans to accommodate both cases. - // http://docs.oasis-open.org/odata/odata-json-format/v4.0/os/odata-json-format-v4.0-os.html#_Toc372793091 - - type serviceError1 struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details []map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - } - - type serviceError2 struct { - Code string `json:"code"` - Message string `json:"message"` - Target *string `json:"target"` - Details map[string]interface{} `json:"details"` - InnerError map[string]interface{} `json:"innererror"` - } - - se1 := serviceError1{} - err := json.Unmarshal(b, &se1) - if err == nil { - se.populate(se1.Code, se1.Message, se1.Target, se1.Details, se1.InnerError) - return nil - } - - se2 := serviceError2{} - err = json.Unmarshal(b, &se2) - if err == nil { - se.populate(se2.Code, se2.Message, se2.Target, nil, se2.InnerError) - se.Details = append(se.Details, se2.Details) - return nil - } - return err -} - -func (se *ServiceError) populate(code, message string, target *string, details []map[string]interface{}, inner map[string]interface{}) { - se.Code = code - se.Message = message - se.Target = target - se.Details = details - se.InnerError = inner -} - -// RequestError describes an error response returned by Azure service. -type RequestError struct { - autorest.DetailedError - - // The error returned by the Azure service. - ServiceError *ServiceError `json:"error"` - - // The request id (from the x-ms-request-id-header) of the request. - RequestID string -} - -// Error returns a human-friendly error message from service error. -func (e RequestError) Error() string { - return fmt.Sprintf("autorest/azure: Service returned an error. Status=%v %v", - e.StatusCode, e.ServiceError) -} - -// IsAzureError returns true if the passed error is an Azure Service error; false otherwise. -func IsAzureError(e error) bool { - _, ok := e.(*RequestError) - return ok -} - -// Resource contains details about an Azure resource. -type Resource struct { - SubscriptionID string - ResourceGroup string - Provider string - ResourceType string - ResourceName string -} - -// ParseResourceID parses a resource ID into a ResourceDetails struct. -// See https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-functions-resource#return-value-4. -func ParseResourceID(resourceID string) (Resource, error) { - - const resourceIDPatternText = `(?i)subscriptions/(.+)/resourceGroups/(.+)/providers/(.+?)/(.+?)/(.+)` - resourceIDPattern := regexp.MustCompile(resourceIDPatternText) - match := resourceIDPattern.FindStringSubmatch(resourceID) - - if len(match) == 0 { - return Resource{}, fmt.Errorf("parsing failed for %s. Invalid resource Id format", resourceID) - } - - v := strings.Split(match[5], "/") - resourceName := v[len(v)-1] - - result := Resource{ - SubscriptionID: match[1], - ResourceGroup: match[2], - Provider: match[3], - ResourceType: match[4], - ResourceName: resourceName, - } - - return result, nil -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) RequestError { - if v, ok := original.(*RequestError); ok { - return *v - } - - statusCode := autorest.UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - return RequestError{ - DetailedError: autorest.DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - }, - } -} - -// WithReturningClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is the passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). It also sets the x-ms-return-client-request-id -// header to true such that UUID accompanies the http.Response. -func WithReturningClientID(uuid string) autorest.PrepareDecorator { - preparer := autorest.CreatePreparer( - WithClientID(uuid), - WithReturnClientID(true)) - - return func(p autorest.Preparer) autorest.Preparer { - return autorest.PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err != nil { - return r, err - } - return preparer.Prepare(r) - }) - } -} - -// WithClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-client-request-id whose value is passed, undecorated UUID (e.g., -// "0F39878C-5F76-4DB8-A25D-61D2C193C3CA"). -func WithClientID(uuid string) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderClientID, uuid) -} - -// WithReturnClientID returns a PrepareDecorator that adds an HTTP extension header of -// x-ms-return-client-request-id whose boolean value indicates if the value of the -// x-ms-client-request-id header should be included in the http.Response. -func WithReturnClientID(b bool) autorest.PrepareDecorator { - return autorest.WithHeader(HeaderReturnClientID, strconv.FormatBool(b)) -} - -// ExtractClientID extracts the client identifier from the x-ms-client-request-id header set on the -// http.Request sent to the service (and returned in the http.Response) -func ExtractClientID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderClientID, resp) -} - -// ExtractRequestID extracts the Azure server generated request identifier from the -// x-ms-request-id header. -func ExtractRequestID(resp *http.Response) string { - return autorest.ExtractHeaderValue(HeaderRequestID, resp) -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an -// azure.RequestError by reading the response body unless the response HTTP status code -// is among the set passed. -// -// If there is a chance service may return responses other than the Azure error -// format and the response cannot be parsed into an error, a decoding error will -// be returned containing the response body. In any case, the Responder will -// return an error if the status code is not satisfied. -// -// If this Responder returns an error, the response body will be replaced with -// an in-memory reader, which needs no further closing. -func WithErrorUnlessStatusCode(codes ...int) autorest.RespondDecorator { - return func(r autorest.Responder) autorest.Responder { - return autorest.ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !autorest.ResponseHasStatusCode(resp, codes...) { - var e RequestError - defer resp.Body.Close() - - // Copy and replace the Body in case it does not contain an error object. - // This will leave the Body available to the caller. - b, decodeErr := autorest.CopyAndDecode(autorest.EncodedAsJSON, resp.Body, &e) - resp.Body = ioutil.NopCloser(&b) - if decodeErr != nil { - return fmt.Errorf("autorest/azure: error response cannot be parsed: %q error: %v", b.String(), decodeErr) - } else if e.ServiceError == nil { - // Check if error is unwrapped ServiceError - if err := json.Unmarshal(b.Bytes(), &e.ServiceError); err != nil || e.ServiceError.Message == "" { - e.ServiceError = &ServiceError{ - Code: "Unknown", - Message: "Unknown service error", - } - } - } - - e.RequestID = ExtractRequestID(resp) - if e.StatusCode == nil { - e.StatusCode = resp.StatusCode - } - err = &e - } - return err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go b/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go deleted file mode 100644 index 7e41f7fd9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go +++ /dev/null @@ -1,191 +0,0 @@ -package azure - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "os" - "strings" -) - -// EnvironmentFilepathName captures the name of the environment variable containing the path to the file -// to be used while populating the Azure Environment. -const EnvironmentFilepathName = "AZURE_ENVIRONMENT_FILEPATH" - -var environments = map[string]Environment{ - "AZURECHINACLOUD": ChinaCloud, - "AZUREGERMANCLOUD": GermanCloud, - "AZUREPUBLICCLOUD": PublicCloud, - "AZUREUSGOVERNMENTCLOUD": USGovernmentCloud, -} - -// Environment represents a set of endpoints for each of Azure's Clouds. -type Environment struct { - Name string `json:"name"` - ManagementPortalURL string `json:"managementPortalURL"` - PublishSettingsURL string `json:"publishSettingsURL"` - ServiceManagementEndpoint string `json:"serviceManagementEndpoint"` - ResourceManagerEndpoint string `json:"resourceManagerEndpoint"` - ActiveDirectoryEndpoint string `json:"activeDirectoryEndpoint"` - GalleryEndpoint string `json:"galleryEndpoint"` - KeyVaultEndpoint string `json:"keyVaultEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - ServiceBusEndpoint string `json:"serviceBusEndpoint"` - BatchManagementEndpoint string `json:"batchManagementEndpoint"` - StorageEndpointSuffix string `json:"storageEndpointSuffix"` - SQLDatabaseDNSSuffix string `json:"sqlDatabaseDNSSuffix"` - TrafficManagerDNSSuffix string `json:"trafficManagerDNSSuffix"` - KeyVaultDNSSuffix string `json:"keyVaultDNSSuffix"` - ServiceBusEndpointSuffix string `json:"serviceBusEndpointSuffix"` - ServiceManagementVMDNSSuffix string `json:"serviceManagementVMDNSSuffix"` - ResourceManagerVMDNSSuffix string `json:"resourceManagerVMDNSSuffix"` - ContainerRegistryDNSSuffix string `json:"containerRegistryDNSSuffix"` - TokenAudience string `json:"tokenAudience"` -} - -var ( - // PublicCloud is the default public Azure cloud environment - PublicCloud = Environment{ - Name: "AzurePublicCloud", - ManagementPortalURL: "https://manage.windowsazure.com/", - PublishSettingsURL: "https://manage.windowsazure.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.windows.net/", - ResourceManagerEndpoint: "https://management.azure.com/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.com/", - GalleryEndpoint: "https://gallery.azure.com/", - KeyVaultEndpoint: "https://vault.azure.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.windows.net/", - BatchManagementEndpoint: "https://batch.core.windows.net/", - StorageEndpointSuffix: "core.windows.net", - SQLDatabaseDNSSuffix: "database.windows.net", - TrafficManagerDNSSuffix: "trafficmanager.net", - KeyVaultDNSSuffix: "vault.azure.net", - ServiceBusEndpointSuffix: "servicebus.windows.net", - ServiceManagementVMDNSSuffix: "cloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.azure.com", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.azure.com/", - } - - // USGovernmentCloud is the cloud environment for the US Government - USGovernmentCloud = Environment{ - Name: "AzureUSGovernmentCloud", - ManagementPortalURL: "https://manage.windowsazure.us/", - PublishSettingsURL: "https://manage.windowsazure.us/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.usgovcloudapi.net/", - ResourceManagerEndpoint: "https://management.usgovcloudapi.net/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.us/", - GalleryEndpoint: "https://gallery.usgovcloudapi.net/", - KeyVaultEndpoint: "https://vault.usgovcloudapi.net/", - GraphEndpoint: "https://graph.windows.net/", - ServiceBusEndpoint: "https://servicebus.usgovcloudapi.net/", - BatchManagementEndpoint: "https://batch.core.usgovcloudapi.net/", - StorageEndpointSuffix: "core.usgovcloudapi.net", - SQLDatabaseDNSSuffix: "database.usgovcloudapi.net", - TrafficManagerDNSSuffix: "usgovtrafficmanager.net", - KeyVaultDNSSuffix: "vault.usgovcloudapi.net", - ServiceBusEndpointSuffix: "servicebus.usgovcloudapi.net", - ServiceManagementVMDNSSuffix: "usgovcloudapp.net", - ResourceManagerVMDNSSuffix: "cloudapp.windowsazure.us", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.usgovcloudapi.net/", - } - - // ChinaCloud is the cloud environment operated in China - ChinaCloud = Environment{ - Name: "AzureChinaCloud", - ManagementPortalURL: "https://manage.chinacloudapi.com/", - PublishSettingsURL: "https://manage.chinacloudapi.com/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.chinacloudapi.cn/", - ResourceManagerEndpoint: "https://management.chinacloudapi.cn/", - ActiveDirectoryEndpoint: "https://login.chinacloudapi.cn/", - GalleryEndpoint: "https://gallery.chinacloudapi.cn/", - KeyVaultEndpoint: "https://vault.azure.cn/", - GraphEndpoint: "https://graph.chinacloudapi.cn/", - ServiceBusEndpoint: "https://servicebus.chinacloudapi.cn/", - BatchManagementEndpoint: "https://batch.chinacloudapi.cn/", - StorageEndpointSuffix: "core.chinacloudapi.cn", - SQLDatabaseDNSSuffix: "database.chinacloudapi.cn", - TrafficManagerDNSSuffix: "trafficmanager.cn", - KeyVaultDNSSuffix: "vault.azure.cn", - ServiceBusEndpointSuffix: "servicebus.chinacloudapi.cn", - ServiceManagementVMDNSSuffix: "chinacloudapp.cn", - ResourceManagerVMDNSSuffix: "cloudapp.azure.cn", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.chinacloudapi.cn/", - } - - // GermanCloud is the cloud environment operated in Germany - GermanCloud = Environment{ - Name: "AzureGermanCloud", - ManagementPortalURL: "http://portal.microsoftazure.de/", - PublishSettingsURL: "https://manage.microsoftazure.de/publishsettings/index", - ServiceManagementEndpoint: "https://management.core.cloudapi.de/", - ResourceManagerEndpoint: "https://management.microsoftazure.de/", - ActiveDirectoryEndpoint: "https://login.microsoftonline.de/", - GalleryEndpoint: "https://gallery.cloudapi.de/", - KeyVaultEndpoint: "https://vault.microsoftazure.de/", - GraphEndpoint: "https://graph.cloudapi.de/", - ServiceBusEndpoint: "https://servicebus.cloudapi.de/", - BatchManagementEndpoint: "https://batch.cloudapi.de/", - StorageEndpointSuffix: "core.cloudapi.de", - SQLDatabaseDNSSuffix: "database.cloudapi.de", - TrafficManagerDNSSuffix: "azuretrafficmanager.de", - KeyVaultDNSSuffix: "vault.microsoftazure.de", - ServiceBusEndpointSuffix: "servicebus.cloudapi.de", - ServiceManagementVMDNSSuffix: "azurecloudapp.de", - ResourceManagerVMDNSSuffix: "cloudapp.microsoftazure.de", - ContainerRegistryDNSSuffix: "azurecr.io", - TokenAudience: "https://management.microsoftazure.de/", - } -) - -// EnvironmentFromName returns an Environment based on the common name specified. -func EnvironmentFromName(name string) (Environment, error) { - // IMPORTANT - // As per @radhikagupta5: - // This is technical debt, fundamentally here because Kubernetes is not currently accepting - // contributions to the providers. Once that is an option, the provider should be updated to - // directly call `EnvironmentFromFile`. Until then, we rely on dispatching Azure Stack environment creation - // from this method based on the name that is provided to us. - if strings.EqualFold(name, "AZURESTACKCLOUD") { - return EnvironmentFromFile(os.Getenv(EnvironmentFilepathName)) - } - - name = strings.ToUpper(name) - env, ok := environments[name] - if !ok { - return env, fmt.Errorf("autorest/azure: There is no cloud environment matching the name %q", name) - } - - return env, nil -} - -// EnvironmentFromFile loads an Environment from a configuration file available on disk. -// This function is particularly useful in the Hybrid Cloud model, where one must define their own -// endpoints. -func EnvironmentFromFile(location string) (unmarshaled Environment, err error) { - fileContents, err := ioutil.ReadFile(location) - if err != nil { - return - } - - err = json.Unmarshal(fileContents, &unmarshaled) - - return -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go b/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go deleted file mode 100644 index 507f9e95c..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/metadata_environment.go +++ /dev/null @@ -1,245 +0,0 @@ -package azure - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/Azure/go-autorest/autorest" -) - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -type audience []string - -type authentication struct { - LoginEndpoint string `json:"loginEndpoint"` - Audiences audience `json:"audiences"` -} - -type environmentMetadataInfo struct { - GalleryEndpoint string `json:"galleryEndpoint"` - GraphEndpoint string `json:"graphEndpoint"` - PortalEndpoint string `json:"portalEndpoint"` - Authentication authentication `json:"authentication"` -} - -// EnvironmentProperty represent property names that clients can override -type EnvironmentProperty string - -const ( - // EnvironmentName ... - EnvironmentName EnvironmentProperty = "name" - // EnvironmentManagementPortalURL .. - EnvironmentManagementPortalURL EnvironmentProperty = "managementPortalURL" - // EnvironmentPublishSettingsURL ... - EnvironmentPublishSettingsURL EnvironmentProperty = "publishSettingsURL" - // EnvironmentServiceManagementEndpoint ... - EnvironmentServiceManagementEndpoint EnvironmentProperty = "serviceManagementEndpoint" - // EnvironmentResourceManagerEndpoint ... - EnvironmentResourceManagerEndpoint EnvironmentProperty = "resourceManagerEndpoint" - // EnvironmentActiveDirectoryEndpoint ... - EnvironmentActiveDirectoryEndpoint EnvironmentProperty = "activeDirectoryEndpoint" - // EnvironmentGalleryEndpoint ... - EnvironmentGalleryEndpoint EnvironmentProperty = "galleryEndpoint" - // EnvironmentKeyVaultEndpoint ... - EnvironmentKeyVaultEndpoint EnvironmentProperty = "keyVaultEndpoint" - // EnvironmentGraphEndpoint ... - EnvironmentGraphEndpoint EnvironmentProperty = "graphEndpoint" - // EnvironmentServiceBusEndpoint ... - EnvironmentServiceBusEndpoint EnvironmentProperty = "serviceBusEndpoint" - // EnvironmentBatchManagementEndpoint ... - EnvironmentBatchManagementEndpoint EnvironmentProperty = "batchManagementEndpoint" - // EnvironmentStorageEndpointSuffix ... - EnvironmentStorageEndpointSuffix EnvironmentProperty = "storageEndpointSuffix" - // EnvironmentSQLDatabaseDNSSuffix ... - EnvironmentSQLDatabaseDNSSuffix EnvironmentProperty = "sqlDatabaseDNSSuffix" - // EnvironmentTrafficManagerDNSSuffix ... - EnvironmentTrafficManagerDNSSuffix EnvironmentProperty = "trafficManagerDNSSuffix" - // EnvironmentKeyVaultDNSSuffix ... - EnvironmentKeyVaultDNSSuffix EnvironmentProperty = "keyVaultDNSSuffix" - // EnvironmentServiceBusEndpointSuffix ... - EnvironmentServiceBusEndpointSuffix EnvironmentProperty = "serviceBusEndpointSuffix" - // EnvironmentServiceManagementVMDNSSuffix ... - EnvironmentServiceManagementVMDNSSuffix EnvironmentProperty = "serviceManagementVMDNSSuffix" - // EnvironmentResourceManagerVMDNSSuffix ... - EnvironmentResourceManagerVMDNSSuffix EnvironmentProperty = "resourceManagerVMDNSSuffix" - // EnvironmentContainerRegistryDNSSuffix ... - EnvironmentContainerRegistryDNSSuffix EnvironmentProperty = "containerRegistryDNSSuffix" - // EnvironmentTokenAudience ... - EnvironmentTokenAudience EnvironmentProperty = "tokenAudience" -) - -// OverrideProperty represents property name and value that clients can override -type OverrideProperty struct { - Key EnvironmentProperty - Value string -} - -// EnvironmentFromURL loads an Environment from a URL -// This function is particularly useful in the Hybrid Cloud model, where one may define their own -// endpoints. -func EnvironmentFromURL(resourceManagerEndpoint string, properties ...OverrideProperty) (environment Environment, err error) { - var metadataEnvProperties environmentMetadataInfo - - if resourceManagerEndpoint == "" { - return environment, fmt.Errorf("Metadata resource manager endpoint is empty") - } - - if metadataEnvProperties, err = retrieveMetadataEnvironment(resourceManagerEndpoint); err != nil { - return environment, err - } - - // Give priority to user's override values - overrideProperties(&environment, properties) - - if environment.Name == "" { - environment.Name = "HybridEnvironment" - } - stampDNSSuffix := environment.StorageEndpointSuffix - if stampDNSSuffix == "" { - stampDNSSuffix = strings.TrimSuffix(strings.TrimPrefix(strings.Replace(resourceManagerEndpoint, strings.Split(resourceManagerEndpoint, ".")[0], "", 1), "."), "/") - environment.StorageEndpointSuffix = stampDNSSuffix - } - if environment.KeyVaultDNSSuffix == "" { - environment.KeyVaultDNSSuffix = fmt.Sprintf("%s.%s", "vault", stampDNSSuffix) - } - if environment.KeyVaultEndpoint == "" { - environment.KeyVaultEndpoint = fmt.Sprintf("%s%s", "https://", environment.KeyVaultDNSSuffix) - } - if environment.TokenAudience == "" { - environment.TokenAudience = metadataEnvProperties.Authentication.Audiences[0] - } - if environment.ActiveDirectoryEndpoint == "" { - environment.ActiveDirectoryEndpoint = metadataEnvProperties.Authentication.LoginEndpoint - } - if environment.ResourceManagerEndpoint == "" { - environment.ResourceManagerEndpoint = resourceManagerEndpoint - } - if environment.GalleryEndpoint == "" { - environment.GalleryEndpoint = metadataEnvProperties.GalleryEndpoint - } - if environment.GraphEndpoint == "" { - environment.GraphEndpoint = metadataEnvProperties.GraphEndpoint - } - - return environment, nil -} - -func overrideProperties(environment *Environment, properties []OverrideProperty) { - for _, property := range properties { - switch property.Key { - case EnvironmentName: - { - environment.Name = property.Value - } - case EnvironmentManagementPortalURL: - { - environment.ManagementPortalURL = property.Value - } - case EnvironmentPublishSettingsURL: - { - environment.PublishSettingsURL = property.Value - } - case EnvironmentServiceManagementEndpoint: - { - environment.ServiceManagementEndpoint = property.Value - } - case EnvironmentResourceManagerEndpoint: - { - environment.ResourceManagerEndpoint = property.Value - } - case EnvironmentActiveDirectoryEndpoint: - { - environment.ActiveDirectoryEndpoint = property.Value - } - case EnvironmentGalleryEndpoint: - { - environment.GalleryEndpoint = property.Value - } - case EnvironmentKeyVaultEndpoint: - { - environment.KeyVaultEndpoint = property.Value - } - case EnvironmentGraphEndpoint: - { - environment.GraphEndpoint = property.Value - } - case EnvironmentServiceBusEndpoint: - { - environment.ServiceBusEndpoint = property.Value - } - case EnvironmentBatchManagementEndpoint: - { - environment.BatchManagementEndpoint = property.Value - } - case EnvironmentStorageEndpointSuffix: - { - environment.StorageEndpointSuffix = property.Value - } - case EnvironmentSQLDatabaseDNSSuffix: - { - environment.SQLDatabaseDNSSuffix = property.Value - } - case EnvironmentTrafficManagerDNSSuffix: - { - environment.TrafficManagerDNSSuffix = property.Value - } - case EnvironmentKeyVaultDNSSuffix: - { - environment.KeyVaultDNSSuffix = property.Value - } - case EnvironmentServiceBusEndpointSuffix: - { - environment.ServiceBusEndpointSuffix = property.Value - } - case EnvironmentServiceManagementVMDNSSuffix: - { - environment.ServiceManagementVMDNSSuffix = property.Value - } - case EnvironmentResourceManagerVMDNSSuffix: - { - environment.ResourceManagerVMDNSSuffix = property.Value - } - case EnvironmentContainerRegistryDNSSuffix: - { - environment.ContainerRegistryDNSSuffix = property.Value - } - case EnvironmentTokenAudience: - { - environment.TokenAudience = property.Value - } - } - } -} - -func retrieveMetadataEnvironment(endpoint string) (environment environmentMetadataInfo, err error) { - client := autorest.NewClientWithUserAgent("") - managementEndpoint := fmt.Sprintf("%s%s", strings.TrimSuffix(endpoint, "/"), "/metadata/endpoints?api-version=1.0") - req, _ := http.NewRequest("GET", managementEndpoint, nil) - response, err := client.Do(req) - if err != nil { - return environment, err - } - defer response.Body.Close() - jsonResponse, err := ioutil.ReadAll(response.Body) - if err != nil { - return environment, err - } - err = json.Unmarshal(jsonResponse, &environment) - return environment, err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go b/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go deleted file mode 100644 index 65ad0afc8..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/azure/rp.go +++ /dev/null @@ -1,200 +0,0 @@ -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package azure - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/Azure/go-autorest/autorest" -) - -// DoRetryWithRegistration tries to register the resource provider in case it is unregistered. -// It also handles request retries -func DoRetryWithRegistration(client autorest.Client) autorest.SendDecorator { - return func(s autorest.Sender) autorest.Sender { - return autorest.SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := autorest.NewRetriableRequest(r) - for currentAttempt := 0; currentAttempt < client.RetryAttempts; currentAttempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - - resp, err = autorest.SendWithSender(s, rr.Request(), - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return resp, err - } - - if resp.StatusCode != http.StatusConflict || client.SkipResourceProviderRegistration { - return resp, err - } - var re RequestError - err = autorest.Respond( - resp, - autorest.ByUnmarshallingJSON(&re), - ) - if err != nil { - return resp, err - } - err = re - - if re.ServiceError != nil && re.ServiceError.Code == "MissingSubscriptionRegistration" { - regErr := register(client, r, re) - if regErr != nil { - return resp, fmt.Errorf("failed auto registering Resource Provider: %s. Original error: %s", regErr, err) - } - } - } - return resp, fmt.Errorf("failed request: %s", err) - }) - } -} - -func getProvider(re RequestError) (string, error) { - if re.ServiceError != nil && len(re.ServiceError.Details) > 0 { - return re.ServiceError.Details[0]["target"].(string), nil - } - return "", errors.New("provider was not found in the response") -} - -func register(client autorest.Client, originalReq *http.Request, re RequestError) error { - subID := getSubscription(originalReq.URL.Path) - if subID == "" { - return errors.New("missing parameter subscriptionID to register resource provider") - } - providerName, err := getProvider(re) - if err != nil { - return fmt.Errorf("missing parameter provider to register resource provider: %s", err) - } - newURL := url.URL{ - Scheme: originalReq.URL.Scheme, - Host: originalReq.URL.Host, - } - - // taken from the resources SDK - // with almost identical code, this sections are easier to mantain - // It is also not a good idea to import the SDK here - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L252 - pathParameters := map[string]interface{}{ - "resourceProviderNamespace": autorest.Encode("path", providerName), - "subscriptionId": autorest.Encode("path", subID), - } - - const APIVersion = "2016-09-01" - queryParameters := map[string]interface{}{ - "api-version": APIVersion, - } - - preparer := autorest.CreatePreparer( - autorest.AsPost(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}/register", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - - req, err := preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - type Provider struct { - RegistrationState *string `json:"registrationState,omitempty"` - } - var provider Provider - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - // poll for registered provisioning state - now := time.Now() - for err == nil && time.Since(now) < client.PollingDuration { - // taken from the resources SDK - // https://github.com/Azure/azure-sdk-for-go/blob/9f366792afa3e0ddaecdc860e793ba9d75e76c27/arm/resources/resources/providers.go#L45 - preparer := autorest.CreatePreparer( - autorest.AsGet(), - autorest.WithBaseURL(newURL.String()), - autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/{resourceProviderNamespace}", pathParameters), - autorest.WithQueryParameters(queryParameters), - ) - req, err = preparer.Prepare(&http.Request{}) - if err != nil { - return err - } - req = req.WithContext(originalReq.Context()) - - resp, err := autorest.SendWithSender(client, req, - autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...), - ) - if err != nil { - return err - } - - err = autorest.Respond( - resp, - WithErrorUnlessStatusCode(http.StatusOK), - autorest.ByUnmarshallingJSON(&provider), - autorest.ByClosing(), - ) - if err != nil { - return err - } - - if provider.RegistrationState != nil && - *provider.RegistrationState == "Registered" { - break - } - - delayed := autorest.DelayWithRetryAfter(resp, originalReq.Context().Done()) - if !delayed && !autorest.DelayForBackoff(client.PollingDelay, 0, originalReq.Context().Done()) { - return originalReq.Context().Err() - } - } - if !(time.Since(now) < client.PollingDuration) { - return errors.New("polling for resource provider registration has exceeded the polling duration") - } - return err -} - -func getSubscription(path string) string { - parts := strings.Split(path, "/") - for i, v := range parts { - if v == "subscriptions" && (i+1) < len(parts) { - return parts[i+1] - } - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/client.go b/vendor/github.com/Azure/go-autorest/autorest/client.go deleted file mode 100644 index 4e92dcad0..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/client.go +++ /dev/null @@ -1,264 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "net/http/cookiejar" - "runtime" - "time" -) - -const ( - // DefaultPollingDelay is a reasonable delay between polling requests. - DefaultPollingDelay = 60 * time.Second - - // DefaultPollingDuration is a reasonable total polling duration. - DefaultPollingDuration = 15 * time.Minute - - // DefaultRetryAttempts is number of attempts for retry status codes (5xx). - DefaultRetryAttempts = 3 - - // DefaultRetryDuration is the duration to wait between retries. - DefaultRetryDuration = 30 * time.Second -) - -var ( - // defaultUserAgent builds a string containing the Go version, system archityecture and OS, - // and the go-autorest version. - defaultUserAgent = fmt.Sprintf("Go/%s (%s-%s) go-autorest/%s", - runtime.Version(), - runtime.GOARCH, - runtime.GOOS, - Version(), - ) - - // StatusCodesForRetry are a defined group of status code for which the client will retry - StatusCodesForRetry = []int{ - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusServiceUnavailable, // 503 - http.StatusGatewayTimeout, // 504 - } -) - -const ( - requestFormat = `HTTP Request Begin =================================================== -%s -===================================================== HTTP Request End -` - responseFormat = `HTTP Response Begin =================================================== -%s -===================================================== HTTP Response End -` -) - -// Response serves as the base for all responses from generated clients. It provides access to the -// last http.Response. -type Response struct { - *http.Response `json:"-"` -} - -// LoggingInspector implements request and response inspectors that log the full request and -// response to a supplied log. -type LoggingInspector struct { - Logger *log.Logger -} - -// WithInspection returns a PrepareDecorator that emits the http.Request to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) WithInspection() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - var body, b bytes.Buffer - - defer r.Body.Close() - - r.Body = ioutil.NopCloser(io.TeeReader(r.Body, &body)) - if err := r.Write(&b); err != nil { - return nil, fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(requestFormat, b.String()) - - r.Body = ioutil.NopCloser(&body) - return p.Prepare(r) - }) - } -} - -// ByInspecting returns a RespondDecorator that emits the http.Response to the supplied logger. The -// body is restored after being emitted. -// -// Note: Since it reads the entire Body, this decorator should not be used where body streaming is -// important. It is best used to trace JSON or similar body values. -func (li LoggingInspector) ByInspecting() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - var body, b bytes.Buffer - defer resp.Body.Close() - resp.Body = ioutil.NopCloser(io.TeeReader(resp.Body, &body)) - if err := resp.Write(&b); err != nil { - return fmt.Errorf("Failed to write response: %v", err) - } - - li.Logger.Printf(responseFormat, b.String()) - - resp.Body = ioutil.NopCloser(&body) - return r.Respond(resp) - }) - } -} - -// Client is the base for autorest generated clients. It provides default, "do nothing" -// implementations of an Authorizer, RequestInspector, and ResponseInspector. It also returns the -// standard, undecorated http.Client as a default Sender. -// -// Generated clients should also use Error (see NewError and NewErrorWithError) for errors and -// return responses that compose with Response. -// -// Most customization of generated clients is best achieved by supplying a custom Authorizer, custom -// RequestInspector, and / or custom ResponseInspector. Users may log requests, implement circuit -// breakers (see https://msdn.microsoft.com/en-us/library/dn589784.aspx) or otherwise influence -// sending the request by providing a decorated Sender. -type Client struct { - Authorizer Authorizer - Sender Sender - RequestInspector PrepareDecorator - ResponseInspector RespondDecorator - - // PollingDelay sets the polling frequency used in absence of a Retry-After HTTP header - PollingDelay time.Duration - - // PollingDuration sets the maximum polling time after which an error is returned. - PollingDuration time.Duration - - // RetryAttempts sets the default number of retry attempts for client. - RetryAttempts int - - // RetryDuration sets the delay duration for retries. - RetryDuration time.Duration - - // UserAgent, if not empty, will be set as the HTTP User-Agent header on all requests sent - // through the Do method. - UserAgent string - - Jar http.CookieJar - - // Set to true to skip attempted registration of resource providers (false by default). - SkipResourceProviderRegistration bool -} - -// NewClientWithUserAgent returns an instance of a Client with the UserAgent set to the passed -// string. -func NewClientWithUserAgent(ua string) Client { - c := Client{ - PollingDelay: DefaultPollingDelay, - PollingDuration: DefaultPollingDuration, - RetryAttempts: DefaultRetryAttempts, - RetryDuration: DefaultRetryDuration, - UserAgent: defaultUserAgent, - } - c.Sender = c.sender() - c.AddToUserAgent(ua) - return c -} - -// AddToUserAgent adds an extension to the current user agent -func (c *Client) AddToUserAgent(extension string) error { - if extension != "" { - c.UserAgent = fmt.Sprintf("%s %s", c.UserAgent, extension) - return nil - } - return fmt.Errorf("Extension was empty, User Agent stayed as %s", c.UserAgent) -} - -// Do implements the Sender interface by invoking the active Sender after applying authorization. -// If Sender is not set, it uses a new instance of http.Client. In both cases it will, if UserAgent -// is set, apply set the User-Agent header. -func (c Client) Do(r *http.Request) (*http.Response, error) { - if r.UserAgent() == "" { - r, _ = Prepare(r, - WithUserAgent(c.UserAgent)) - } - // NOTE: c.WithInspection() must be last in the list so that it can inspect all preceding operations - r, err := Prepare(r, - c.WithAuthorization(), - c.WithInspection()) - if err != nil { - var resp *http.Response - if detErr, ok := err.(DetailedError); ok { - // if the authorization failed (e.g. invalid credentials) there will - // be a response associated with the error, be sure to return it. - resp = detErr.Response - } - return resp, NewErrorWithError(err, "autorest/Client", "Do", nil, "Preparing request failed") - } - - resp, err := SendWithSender(c.sender(), r) - Respond(resp, c.ByInspecting()) - return resp, err -} - -// sender returns the Sender to which to send requests. -func (c Client) sender() Sender { - if c.Sender == nil { - j, _ := cookiejar.New(nil) - return &http.Client{Jar: j} - } - return c.Sender -} - -// WithAuthorization is a convenience method that returns the WithAuthorization PrepareDecorator -// from the current Authorizer. If not Authorizer is set, it uses the NullAuthorizer. -func (c Client) WithAuthorization() PrepareDecorator { - return c.authorizer().WithAuthorization() -} - -// authorizer returns the Authorizer to use. -func (c Client) authorizer() Authorizer { - if c.Authorizer == nil { - return NullAuthorizer{} - } - return c.Authorizer -} - -// WithInspection is a convenience method that passes the request to the supplied RequestInspector, -// if present, or returns the WithNothing PrepareDecorator otherwise. -func (c Client) WithInspection() PrepareDecorator { - if c.RequestInspector == nil { - return WithNothing() - } - return c.RequestInspector -} - -// ByInspecting is a convenience method that passes the response to the supplied ResponseInspector, -// if present, or returns the ByIgnoring RespondDecorator otherwise. -func (c Client) ByInspecting() RespondDecorator { - if c.ResponseInspector == nil { - return ByIgnoring() - } - return c.ResponseInspector -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/date.go b/vendor/github.com/Azure/go-autorest/autorest/date/date.go deleted file mode 100644 index c45710656..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/date.go +++ /dev/null @@ -1,96 +0,0 @@ -/* -Package date provides time.Time derivatives that conform to the Swagger.io (https://swagger.io/) -defined date formats: Date and DateTime. Both types may, in most cases, be used in lieu of -time.Time types. And both convert to time.Time through a ToTime method. -*/ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "time" -) - -const ( - fullDate = "2006-01-02" - fullDateJSON = `"2006-01-02"` - dateFormat = "%04d-%02d-%02d" - jsonFormat = `"%04d-%02d-%02d"` -) - -// Date defines a type similar to time.Time but assumes a layout of RFC3339 full-date (i.e., -// 2006-01-02). -type Date struct { - time.Time -} - -// ParseDate create a new Date from the passed string. -func ParseDate(date string) (d Date, err error) { - return parseDate(date, fullDate) -} - -func parseDate(date string, format string) (Date, error) { - d, err := time.Parse(format, date) - return Date{Time: d}, err -} - -// MarshalBinary preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalBinary() ([]byte, error) { - return d.MarshalText() -} - -// UnmarshalBinary reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalBinary(data []byte) error { - return d.UnmarshalText(data) -} - -// MarshalJSON preserves the Date as a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalJSON() (json []byte, err error) { - return []byte(fmt.Sprintf(jsonFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalJSON reconstitutes the Date from a JSON string conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalJSON(data []byte) (err error) { - d.Time, err = time.Parse(fullDateJSON, string(data)) - return err -} - -// MarshalText preserves the Date as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d Date) MarshalText() (text []byte, err error) { - return []byte(fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day())), nil -} - -// UnmarshalText reconstitutes a Date saved as a byte array conforming to RFC3339 full-date (i.e., -// 2006-01-02). -func (d *Date) UnmarshalText(data []byte) (err error) { - d.Time, err = time.Parse(fullDate, string(data)) - return err -} - -// String returns the Date formatted as an RFC3339 full-date string (i.e., 2006-01-02). -func (d Date) String() string { - return fmt.Sprintf(dateFormat, d.Year(), d.Month(), d.Day()) -} - -// ToTime returns a Date as a time.Time -func (d Date) ToTime() time.Time { - return d.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/time.go b/vendor/github.com/Azure/go-autorest/autorest/date/time.go deleted file mode 100644 index b453fad04..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/time.go +++ /dev/null @@ -1,103 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "regexp" - "time" -) - -// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. -const ( - azureUtcFormatJSON = `"2006-01-02T15:04:05.999999999"` - azureUtcFormat = "2006-01-02T15:04:05.999999999" - rfc3339JSON = `"` + time.RFC3339Nano + `"` - rfc3339 = time.RFC3339Nano - tzOffsetRegex = `(Z|z|\+|-)(\d+:\d+)*"*$` -) - -// Time defines a type similar to time.Time but assumes a layout of RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -type Time struct { - time.Time -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalBinary() ([]byte, error) { - return t.Time.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalJSON() (json []byte, err error) { - return t.Time.MarshalJSON() -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalJSON(data []byte) (err error) { - timeFormat := azureUtcFormatJSON - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339JSON - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// MarshalText preserves the Time as a byte array conforming to RFC3339 date-time (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) MarshalText() (text []byte, err error) { - return t.Time.MarshalText() -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC3339 date-time -// (i.e., 2006-01-02T15:04:05Z). -func (t *Time) UnmarshalText(data []byte) (err error) { - timeFormat := azureUtcFormat - match, err := regexp.Match(tzOffsetRegex, data) - if err != nil { - return err - } else if match { - timeFormat = rfc3339 - } - t.Time, err = ParseTime(timeFormat, string(data)) - return err -} - -// String returns the Time formatted as an RFC3339 date-time string (i.e., -// 2006-01-02T15:04:05Z). -func (t Time) String() string { - // Note: time.Time.String does not return an RFC3339 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} - -// ToTime returns a Time as a time.Time -func (t Time) ToTime() time.Time { - return t.Time -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go b/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go deleted file mode 100644 index 48fb39ba9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/timerfc1123.go +++ /dev/null @@ -1,100 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "errors" - "time" -) - -const ( - rfc1123JSON = `"` + time.RFC1123 + `"` - rfc1123 = time.RFC1123 -) - -// TimeRFC1123 defines a type similar to time.Time but assumes a layout of RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -type TimeRFC1123 struct { - time.Time -} - -// UnmarshalJSON reconstitutes the Time from a JSON string conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalJSON(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123JSON, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalJSON preserves the Time as a JSON string conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalJSON() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalJSON: year outside of range [0,9999]") - } - b := []byte(t.Format(rfc1123JSON)) - return b, nil -} - -// MarshalText preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalText() ([]byte, error) { - if y := t.Year(); y < 0 || y >= 10000 { - return nil, errors.New("Time.MarshalText: year outside of range [0,9999]") - } - - b := []byte(t.Format(rfc1123)) - return b, nil -} - -// UnmarshalText reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalText(data []byte) (err error) { - t.Time, err = ParseTime(rfc1123, string(data)) - if err != nil { - return err - } - return nil -} - -// MarshalBinary preserves the Time as a byte array conforming to RFC1123 date-time (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) MarshalBinary() ([]byte, error) { - return t.MarshalText() -} - -// UnmarshalBinary reconstitutes a Time saved as a byte array conforming to RFC1123 date-time -// (i.e., Mon, 02 Jan 2006 15:04:05 MST). -func (t *TimeRFC1123) UnmarshalBinary(data []byte) error { - return t.UnmarshalText(data) -} - -// ToTime returns a Time as a time.Time -func (t TimeRFC1123) ToTime() time.Time { - return t.Time -} - -// String returns the Time formatted as an RFC1123 date-time string (i.e., -// Mon, 02 Jan 2006 15:04:05 MST). -func (t TimeRFC1123) String() string { - // Note: time.Time.String does not return an RFC1123 compliant string, time.Time.MarshalText does. - b, err := t.MarshalText() - if err != nil { - return "" - } - return string(b) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go b/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go deleted file mode 100644 index 7073959b2..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/unixtime.go +++ /dev/null @@ -1,123 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/binary" - "encoding/json" - "time" -) - -// unixEpoch is the moment in time that should be treated as timestamp 0. -var unixEpoch = time.Date(1970, time.January, 1, 0, 0, 0, 0, time.UTC) - -// UnixTime marshals and unmarshals a time that is represented as the number -// of seconds (ignoring skip-seconds) since the Unix Epoch. -type UnixTime time.Time - -// Duration returns the time as a Duration since the UnixEpoch. -func (t UnixTime) Duration() time.Duration { - return time.Time(t).Sub(unixEpoch) -} - -// NewUnixTimeFromSeconds creates a UnixTime as a number of seconds from the UnixEpoch. -func NewUnixTimeFromSeconds(seconds float64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(seconds * float64(time.Second))) -} - -// NewUnixTimeFromNanoseconds creates a UnixTime as a number of nanoseconds from the UnixEpoch. -func NewUnixTimeFromNanoseconds(nanoseconds int64) UnixTime { - return NewUnixTimeFromDuration(time.Duration(nanoseconds)) -} - -// NewUnixTimeFromDuration creates a UnixTime as a duration of time since the UnixEpoch. -func NewUnixTimeFromDuration(dur time.Duration) UnixTime { - return UnixTime(unixEpoch.Add(dur)) -} - -// UnixEpoch retreives the moment considered the Unix Epoch. I.e. The time represented by '0' -func UnixEpoch() time.Time { - return unixEpoch -} - -// MarshalJSON preserves the UnixTime as a JSON number conforming to Unix Timestamp requirements. -// (i.e. the number of seconds since midnight January 1st, 1970 not considering leap seconds.) -func (t UnixTime) MarshalJSON() ([]byte, error) { - buffer := &bytes.Buffer{} - enc := json.NewEncoder(buffer) - err := enc.Encode(float64(time.Time(t).UnixNano()) / 1e9) - if err != nil { - return nil, err - } - return buffer.Bytes(), nil -} - -// UnmarshalJSON reconstitures a UnixTime saved as a JSON number of the number of seconds since -// midnight January 1st, 1970. -func (t *UnixTime) UnmarshalJSON(text []byte) error { - dec := json.NewDecoder(bytes.NewReader(text)) - - var secondsSinceEpoch float64 - if err := dec.Decode(&secondsSinceEpoch); err != nil { - return err - } - - *t = NewUnixTimeFromSeconds(secondsSinceEpoch) - - return nil -} - -// MarshalText stores the number of seconds since the Unix Epoch as a textual floating point number. -func (t UnixTime) MarshalText() ([]byte, error) { - cast := time.Time(t) - return cast.MarshalText() -} - -// UnmarshalText populates a UnixTime with a value stored textually as a floating point number of seconds since the Unix Epoch. -func (t *UnixTime) UnmarshalText(raw []byte) error { - var unmarshaled time.Time - - if err := unmarshaled.UnmarshalText(raw); err != nil { - return err - } - - *t = UnixTime(unmarshaled) - return nil -} - -// MarshalBinary converts a UnixTime into a binary.LittleEndian float64 of nanoseconds since the epoch. -func (t UnixTime) MarshalBinary() ([]byte, error) { - buf := &bytes.Buffer{} - - payload := int64(t.Duration()) - - if err := binary.Write(buf, binary.LittleEndian, &payload); err != nil { - return nil, err - } - - return buf.Bytes(), nil -} - -// UnmarshalBinary converts a from a binary.LittleEndian float64 of nanoseconds since the epoch into a UnixTime. -func (t *UnixTime) UnmarshalBinary(raw []byte) error { - var nanosecondsSinceEpoch int64 - - if err := binary.Read(bytes.NewReader(raw), binary.LittleEndian, &nanosecondsSinceEpoch); err != nil { - return err - } - *t = NewUnixTimeFromNanoseconds(nanosecondsSinceEpoch) - return nil -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go b/vendor/github.com/Azure/go-autorest/autorest/date/utility.go deleted file mode 100644 index 12addf0eb..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/date/utility.go +++ /dev/null @@ -1,25 +0,0 @@ -package date - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "strings" - "time" -) - -// ParseTime to parse Time string to specified format. -func ParseTime(format string, t string) (d time.Time, err error) { - return time.Parse(format, strings.ToUpper(t)) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/error.go b/vendor/github.com/Azure/go-autorest/autorest/error.go deleted file mode 100644 index f724f3332..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/error.go +++ /dev/null @@ -1,98 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "net/http" -) - -const ( - // UndefinedStatusCode is used when HTTP status code is not available for an error. - UndefinedStatusCode = 0 -) - -// DetailedError encloses a error with details of the package, method, and associated HTTP -// status code (if any). -type DetailedError struct { - Original error - - // PackageType is the package type of the object emitting the error. For types, the value - // matches that produced the the '%T' format specifier of the fmt package. For other elements, - // such as functions, it is just the package name (e.g., "autorest"). - PackageType string - - // Method is the name of the method raising the error. - Method string - - // StatusCode is the HTTP Response StatusCode (if non-zero) that led to the error. - StatusCode interface{} - - // Message is the error message. - Message string - - // Service Error is the response body of failed API in bytes - ServiceError []byte - - // Response is the response object that was returned during failure if applicable. - Response *http.Response -} - -// NewError creates a new Error conforming object from the passed packageType, method, and -// message. message is treated as a format string to which the optional args apply. -func NewError(packageType string, method string, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, nil, message, args...) -} - -// NewErrorWithResponse creates a new Error conforming object from the passed -// packageType, method, statusCode of the given resp (UndefinedStatusCode if -// resp is nil), and message. message is treated as a format string to which the -// optional args apply. -func NewErrorWithResponse(packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - return NewErrorWithError(nil, packageType, method, resp, message, args...) -} - -// NewErrorWithError creates a new Error conforming object from the -// passed packageType, method, statusCode of the given resp (UndefinedStatusCode -// if resp is nil), message, and original error. message is treated as a format -// string to which the optional args apply. -func NewErrorWithError(original error, packageType string, method string, resp *http.Response, message string, args ...interface{}) DetailedError { - if v, ok := original.(DetailedError); ok { - return v - } - - statusCode := UndefinedStatusCode - if resp != nil { - statusCode = resp.StatusCode - } - - return DetailedError{ - Original: original, - PackageType: packageType, - Method: method, - StatusCode: statusCode, - Message: fmt.Sprintf(message, args...), - Response: resp, - } -} - -// Error returns a formatted containing all available details (i.e., PackageType, Method, -// StatusCode, Message, and original error (if any)). -func (e DetailedError) Error() string { - if e.Original == nil { - return fmt.Sprintf("%s#%s: %s: StatusCode=%d", e.PackageType, e.Method, e.Message, e.StatusCode) - } - return fmt.Sprintf("%s#%s: %s: StatusCode=%d -- Original Error: %v", e.PackageType, e.Method, e.Message, e.StatusCode, e.Original) -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/preparer.go b/vendor/github.com/Azure/go-autorest/autorest/preparer.go deleted file mode 100644 index 6d67bd733..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/preparer.go +++ /dev/null @@ -1,480 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "strings" -) - -const ( - mimeTypeJSON = "application/json" - mimeTypeOctetStream = "application/octet-stream" - mimeTypeFormPost = "application/x-www-form-urlencoded" - - headerAuthorization = "Authorization" - headerContentType = "Content-Type" - headerUserAgent = "User-Agent" -) - -// Preparer is the interface that wraps the Prepare method. -// -// Prepare accepts and possibly modifies an http.Request (e.g., adding Headers). Implementations -// must ensure to not share or hold per-invocation state since Preparers may be shared and re-used. -type Preparer interface { - Prepare(*http.Request) (*http.Request, error) -} - -// PreparerFunc is a method that implements the Preparer interface. -type PreparerFunc func(*http.Request) (*http.Request, error) - -// Prepare implements the Preparer interface on PreparerFunc. -func (pf PreparerFunc) Prepare(r *http.Request) (*http.Request, error) { - return pf(r) -} - -// PrepareDecorator takes and possibly decorates, by wrapping, a Preparer. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then affect the result. -type PrepareDecorator func(Preparer) Preparer - -// CreatePreparer creates, decorates, and returns a Preparer. -// Without decorators, the returned Preparer returns the passed http.Request unmodified. -// Preparers are safe to share and re-use. -func CreatePreparer(decorators ...PrepareDecorator) Preparer { - return DecoratePreparer( - Preparer(PreparerFunc(func(r *http.Request) (*http.Request, error) { return r, nil })), - decorators...) -} - -// DecoratePreparer accepts a Preparer and a, possibly empty, set of PrepareDecorators, which it -// applies to the Preparer. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (change the http.Request and then pass it -// along) or a post-decorator (pass the http.Request along and alter it on return). -func DecoratePreparer(p Preparer, decorators ...PrepareDecorator) Preparer { - for _, decorate := range decorators { - p = decorate(p) - } - return p -} - -// Prepare accepts an http.Request and a, possibly empty, set of PrepareDecorators. -// It creates a Preparer from the decorators which it then applies to the passed http.Request. -func Prepare(r *http.Request, decorators ...PrepareDecorator) (*http.Request, error) { - if r == nil { - return nil, NewError("autorest", "Prepare", "Invoked without an http.Request") - } - return CreatePreparer(decorators...).Prepare(r) -} - -// WithNothing returns a "do nothing" PrepareDecorator that makes no changes to the passed -// http.Request. -func WithNothing() PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - return p.Prepare(r) - }) - } -} - -// WithHeader returns a PrepareDecorator that sets the specified HTTP header of the http.Request to -// the passed value. It canonicalizes the passed header name (via http.CanonicalHeaderKey) before -// adding the header. -func WithHeader(header string, value string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(header), value) - } - return r, err - }) - } -} - -// WithHeaders returns a PrepareDecorator that sets the specified HTTP headers of the http.Request to -// the passed value. It canonicalizes the passed headers name (via http.CanonicalHeaderKey) before -// adding them. -func WithHeaders(headers map[string]interface{}) PrepareDecorator { - h := ensureValueStrings(headers) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.Header == nil { - r.Header = make(http.Header) - } - - for name, value := range h { - r.Header.Set(http.CanonicalHeaderKey(name), value) - } - } - return r, err - }) - } -} - -// WithBearerAuthorization returns a PrepareDecorator that adds an HTTP Authorization header whose -// value is "Bearer " followed by the supplied token. -func WithBearerAuthorization(token string) PrepareDecorator { - return WithHeader(headerAuthorization, fmt.Sprintf("Bearer %s", token)) -} - -// AsContentType returns a PrepareDecorator that adds an HTTP Content-Type header whose value -// is the passed contentType. -func AsContentType(contentType string) PrepareDecorator { - return WithHeader(headerContentType, contentType) -} - -// WithUserAgent returns a PrepareDecorator that adds an HTTP User-Agent header whose value is the -// passed string. -func WithUserAgent(ua string) PrepareDecorator { - return WithHeader(headerUserAgent, ua) -} - -// AsFormURLEncoded returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/x-www-form-urlencoded". -func AsFormURLEncoded() PrepareDecorator { - return AsContentType(mimeTypeFormPost) -} - -// AsJSON returns a PrepareDecorator that adds an HTTP Content-Type header whose value is -// "application/json". -func AsJSON() PrepareDecorator { - return AsContentType(mimeTypeJSON) -} - -// AsOctetStream returns a PrepareDecorator that adds the "application/octet-stream" Content-Type header. -func AsOctetStream() PrepareDecorator { - return AsContentType(mimeTypeOctetStream) -} - -// WithMethod returns a PrepareDecorator that sets the HTTP method of the passed request. The -// decorator does not validate that the passed method string is a known HTTP method. -func WithMethod(method string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r.Method = method - return p.Prepare(r) - }) - } -} - -// AsDelete returns a PrepareDecorator that sets the HTTP method to DELETE. -func AsDelete() PrepareDecorator { return WithMethod("DELETE") } - -// AsGet returns a PrepareDecorator that sets the HTTP method to GET. -func AsGet() PrepareDecorator { return WithMethod("GET") } - -// AsHead returns a PrepareDecorator that sets the HTTP method to HEAD. -func AsHead() PrepareDecorator { return WithMethod("HEAD") } - -// AsOptions returns a PrepareDecorator that sets the HTTP method to OPTIONS. -func AsOptions() PrepareDecorator { return WithMethod("OPTIONS") } - -// AsPatch returns a PrepareDecorator that sets the HTTP method to PATCH. -func AsPatch() PrepareDecorator { return WithMethod("PATCH") } - -// AsPost returns a PrepareDecorator that sets the HTTP method to POST. -func AsPost() PrepareDecorator { return WithMethod("POST") } - -// AsPut returns a PrepareDecorator that sets the HTTP method to PUT. -func AsPut() PrepareDecorator { return WithMethod("PUT") } - -// WithBaseURL returns a PrepareDecorator that populates the http.Request with a url.URL constructed -// from the supplied baseUrl. -func WithBaseURL(baseURL string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var u *url.URL - if u, err = url.Parse(baseURL); err != nil { - return r, err - } - if u.Scheme == "" { - err = fmt.Errorf("autorest: No scheme detected in URL %s", baseURL) - } - if err == nil { - r.URL = u - } - } - return r, err - }) - } -} - -// WithCustomBaseURL returns a PrepareDecorator that replaces brace-enclosed keys within the -// request base URL (i.e., http.Request.URL) with the corresponding values from the passed map. -func WithCustomBaseURL(baseURL string, urlParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(urlParameters) - for key, value := range parameters { - baseURL = strings.Replace(baseURL, "{"+key+"}", value, -1) - } - return WithBaseURL(baseURL) -} - -// WithFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) into the -// http.Request body. -func WithFormData(v url.Values) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - s := v.Encode() - - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(headerContentType), mimeTypeFormPost) - r.ContentLength = int64(len(s)) - r.Body = ioutil.NopCloser(strings.NewReader(s)) - } - return r, err - }) - } -} - -// WithMultiPartFormData returns a PrepareDecoratore that "URL encodes" (e.g., bar=baz&foo=quux) form parameters -// into the http.Request body. -func WithMultiPartFormData(formDataParameters map[string]interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - var body bytes.Buffer - writer := multipart.NewWriter(&body) - for key, value := range formDataParameters { - if rc, ok := value.(io.ReadCloser); ok { - var fd io.Writer - if fd, err = writer.CreateFormFile(key, key); err != nil { - return r, err - } - if _, err = io.Copy(fd, rc); err != nil { - return r, err - } - } else { - if err = writer.WriteField(key, ensureValueString(value)); err != nil { - return r, err - } - } - } - if err = writer.Close(); err != nil { - return r, err - } - if r.Header == nil { - r.Header = make(http.Header) - } - r.Header.Set(http.CanonicalHeaderKey(headerContentType), writer.FormDataContentType()) - r.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes())) - r.ContentLength = int64(body.Len()) - return r, err - } - return r, err - }) - } -} - -// WithFile returns a PrepareDecorator that sends file in request body. -func WithFile(f io.ReadCloser) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := ioutil.ReadAll(f) - if err != nil { - return r, err - } - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - r.ContentLength = int64(len(b)) - } - return r, err - }) - } -} - -// WithBool returns a PrepareDecorator that encodes the passed bool into the body of the request -// and sets the Content-Length header. -func WithBool(v bool) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat32 returns a PrepareDecorator that encodes the passed float32 into the body of the -// request and sets the Content-Length header. -func WithFloat32(v float32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithFloat64 returns a PrepareDecorator that encodes the passed float64 into the body of the -// request and sets the Content-Length header. -func WithFloat64(v float64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt32 returns a PrepareDecorator that encodes the passed int32 into the body of the request -// and sets the Content-Length header. -func WithInt32(v int32) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithInt64 returns a PrepareDecorator that encodes the passed int64 into the body of the request -// and sets the Content-Length header. -func WithInt64(v int64) PrepareDecorator { - return WithString(fmt.Sprintf("%v", v)) -} - -// WithString returns a PrepareDecorator that encodes the passed string into the body of the request -// and sets the Content-Length header. -func WithString(v string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - r.ContentLength = int64(len(v)) - r.Body = ioutil.NopCloser(strings.NewReader(v)) - } - return r, err - }) - } -} - -// WithJSON returns a PrepareDecorator that encodes the data passed as JSON into the body of the -// request and sets the Content-Length header. -func WithJSON(v interface{}) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - b, err := json.Marshal(v) - if err == nil { - r.ContentLength = int64(len(b)) - r.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - } - return r, err - }) - } -} - -// WithPath returns a PrepareDecorator that adds the supplied path to the request URL. If the path -// is absolute (that is, it begins with a "/"), it replaces the existing path. -func WithPath(path string) PrepareDecorator { - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPath", "Invoked with a nil URL") - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithEscapedPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. The -// values will be escaped (aka URL encoded) before insertion into the path. -func WithEscapedPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := escapeValueStrings(ensureValueStrings(pathParameters)) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithEscapedPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -// WithPathParameters returns a PrepareDecorator that replaces brace-enclosed keys within the -// request path (i.e., http.Request.URL.Path) with the corresponding values from the passed map. -func WithPathParameters(path string, pathParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(pathParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithPathParameters", "Invoked with a nil URL") - } - for key, value := range parameters { - path = strings.Replace(path, "{"+key+"}", value, -1) - } - - if r.URL, err = parseURL(r.URL, path); err != nil { - return r, err - } - } - return r, err - }) - } -} - -func parseURL(u *url.URL, path string) (*url.URL, error) { - p := strings.TrimRight(u.String(), "/") - if !strings.HasPrefix(path, "/") { - path = "/" + path - } - return url.Parse(p + path) -} - -// WithQueryParameters returns a PrepareDecorators that encodes and applies the query parameters -// given in the supplied map (i.e., key=value). -func WithQueryParameters(queryParameters map[string]interface{}) PrepareDecorator { - parameters := ensureValueStrings(queryParameters) - return func(p Preparer) Preparer { - return PreparerFunc(func(r *http.Request) (*http.Request, error) { - r, err := p.Prepare(r) - if err == nil { - if r.URL == nil { - return r, NewError("autorest", "WithQueryParameters", "Invoked with a nil URL") - } - - v := r.URL.Query() - for key, value := range parameters { - d, err := url.QueryUnescape(value) - if err != nil { - return r, err - } - v.Add(key, d) - } - r.URL.RawQuery = v.Encode() - } - return r, err - }) - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/responder.go b/vendor/github.com/Azure/go-autorest/autorest/responder.go deleted file mode 100644 index a908a0adb..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/responder.go +++ /dev/null @@ -1,250 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "io/ioutil" - "net/http" - "strings" -) - -// Responder is the interface that wraps the Respond method. -// -// Respond accepts and reacts to an http.Response. Implementations must ensure to not share or hold -// state since Responders may be shared and re-used. -type Responder interface { - Respond(*http.Response) error -} - -// ResponderFunc is a method that implements the Responder interface. -type ResponderFunc func(*http.Response) error - -// Respond implements the Responder interface on ResponderFunc. -func (rf ResponderFunc) Respond(r *http.Response) error { - return rf(r) -} - -// RespondDecorator takes and possibly decorates, by wrapping, a Responder. Decorators may react to -// the http.Response and pass it along or, first, pass the http.Response along then react. -type RespondDecorator func(Responder) Responder - -// CreateResponder creates, decorates, and returns a Responder. Without decorators, the returned -// Responder returns the passed http.Response unmodified. Responders may or may not be safe to share -// and re-used: It depends on the applied decorators. For example, a standard decorator that closes -// the response body is fine to share whereas a decorator that reads the body into a passed struct -// is not. -// -// To prevent memory leaks, ensure that at least one Responder closes the response body. -func CreateResponder(decorators ...RespondDecorator) Responder { - return DecorateResponder( - Responder(ResponderFunc(func(r *http.Response) error { return nil })), - decorators...) -} - -// DecorateResponder accepts a Responder and a, possibly empty, set of RespondDecorators, which it -// applies to the Responder. Decorators are applied in the order received, but their affect upon the -// request depends on whether they are a pre-decorator (react to the http.Response and then pass it -// along) or a post-decorator (pass the http.Response along and then react). -func DecorateResponder(r Responder, decorators ...RespondDecorator) Responder { - for _, decorate := range decorators { - r = decorate(r) - } - return r -} - -// Respond accepts an http.Response and a, possibly empty, set of RespondDecorators. -// It creates a Responder from the decorators it then applies to the passed http.Response. -func Respond(r *http.Response, decorators ...RespondDecorator) error { - if r == nil { - return nil - } - return CreateResponder(decorators...).Respond(r) -} - -// ByIgnoring returns a RespondDecorator that ignores the passed http.Response passing it unexamined -// to the next RespondDecorator. -func ByIgnoring() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - return r.Respond(resp) - }) - } -} - -// ByCopying copies the contents of the http.Response Body into the passed bytes.Buffer as -// the Body is read. -func ByCopying(b *bytes.Buffer) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - resp.Body = TeeReadCloser(resp.Body, b) - } - return err - }) - } -} - -// ByDiscardingBody returns a RespondDecorator that first invokes the passed Responder after which -// it copies the remaining bytes (if any) in the response body to ioutil.Discard. Since the passed -// Responder is invoked prior to discarding the response body, the decorator may occur anywhere -// within the set. -func ByDiscardingBody() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && resp != nil && resp.Body != nil { - if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil { - return fmt.Errorf("Error discarding the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosing returns a RespondDecorator that first invokes the passed Responder after which it -// closes the response body. Since the passed Responder is invoked prior to closing the response -// body, the decorator may occur anywhere within the set. -func ByClosing() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByClosingIfError returns a RespondDecorator that first invokes the passed Responder after which -// it closes the response if the passed Responder returns an error and the response body exists. -func ByClosingIfError() RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err != nil && resp != nil && resp.Body != nil { - if err := resp.Body.Close(); err != nil { - return fmt.Errorf("Error closing the response body: %v", err) - } - } - return err - }) - } -} - -// ByUnmarshallingJSON returns a RespondDecorator that decodes a JSON document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingJSON(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - // Some responses might include a BOM, remove for successful unmarshalling - b = bytes.TrimPrefix(b, []byte("\xef\xbb\xbf")) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else if len(strings.Trim(string(b), " ")) > 0 { - errInner = json.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling JSON - Error = '%v' JSON = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// ByUnmarshallingXML returns a RespondDecorator that decodes a XML document returned in the -// response Body into the value pointed to by v. -func ByUnmarshallingXML(v interface{}) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil { - b, errInner := ioutil.ReadAll(resp.Body) - if errInner != nil { - err = fmt.Errorf("Error occurred reading http.Response#Body - Error = '%v'", errInner) - } else { - errInner = xml.Unmarshal(b, v) - if errInner != nil { - err = fmt.Errorf("Error occurred unmarshalling Xml - Error = '%v' Xml = '%s'", errInner, string(b)) - } - } - } - return err - }) - } -} - -// WithErrorUnlessStatusCode returns a RespondDecorator that emits an error unless the response -// StatusCode is among the set passed. On error, response body is fully read into a buffer and -// presented in the returned error, as well as in the response body. -func WithErrorUnlessStatusCode(codes ...int) RespondDecorator { - return func(r Responder) Responder { - return ResponderFunc(func(resp *http.Response) error { - err := r.Respond(resp) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - derr := NewErrorWithResponse("autorest", "WithErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - if resp.Body != nil { - defer resp.Body.Close() - b, _ := ioutil.ReadAll(resp.Body) - derr.ServiceError = b - resp.Body = ioutil.NopCloser(bytes.NewReader(b)) - } - err = derr - } - return err - }) - } -} - -// WithErrorUnlessOK returns a RespondDecorator that emits an error if the response StatusCode is -// anything other than HTTP 200. -func WithErrorUnlessOK() RespondDecorator { - return WithErrorUnlessStatusCode(http.StatusOK) -} - -// ExtractHeader extracts all values of the specified header from the http.Response. It returns an -// empty string slice if the passed http.Response is nil or the header does not exist. -func ExtractHeader(header string, resp *http.Response) []string { - if resp != nil && resp.Header != nil { - return resp.Header[http.CanonicalHeaderKey(header)] - } - return nil -} - -// ExtractHeaderValue extracts the first value of the specified header from the http.Response. It -// returns an empty string if the passed http.Response is nil or the header does not exist. -func ExtractHeaderValue(header string, resp *http.Response) string { - h := ExtractHeader(header, resp) - if len(h) > 0 { - return h[0] - } - return "" -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go deleted file mode 100644 index fa11dbed7..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest.go +++ /dev/null @@ -1,52 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// NewRetriableRequest returns a wrapper around an HTTP request that support retry logic. -func NewRetriableRequest(req *http.Request) *RetriableRequest { - return &RetriableRequest{req: req} -} - -// Request returns the wrapped HTTP request. -func (rr *RetriableRequest) Request() *http.Request { - return rr.req -} - -func (rr *RetriableRequest) prepareFromByteReader() (err error) { - // fall back to making a copy (only do this once) - b := []byte{} - if rr.req.ContentLength > 0 { - b = make([]byte, rr.req.ContentLength) - _, err = io.ReadFull(rr.req.Body, b) - if err != nil { - return err - } - } else { - b, err = ioutil.ReadAll(rr.req.Body) - if err != nil { - return err - } - } - rr.br = bytes.NewReader(b) - rr.req.Body = ioutil.NopCloser(rr.br) - return err -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go deleted file mode 100644 index 7143cc61b..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.7.go +++ /dev/null @@ -1,54 +0,0 @@ -// +build !go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import ( - "bytes" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.br != nil { - _, err = rr.br.Seek(0, 0 /*io.SeekStart*/) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go b/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go deleted file mode 100644 index ae15c6bf9..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/retriablerequest_1.8.go +++ /dev/null @@ -1,66 +0,0 @@ -// +build go1.8 - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package autorest - -import ( - "bytes" - "io" - "io/ioutil" - "net/http" -) - -// RetriableRequest provides facilities for retrying an HTTP request. -type RetriableRequest struct { - req *http.Request - rc io.ReadCloser - br *bytes.Reader -} - -// Prepare signals that the request is about to be sent. -func (rr *RetriableRequest) Prepare() (err error) { - // preserve the request body; this is to support retry logic as - // the underlying transport will always close the reqeust body - if rr.req.Body != nil { - if rr.rc != nil { - rr.req.Body = rr.rc - } else if rr.br != nil { - _, err = rr.br.Seek(0, io.SeekStart) - rr.req.Body = ioutil.NopCloser(rr.br) - } - if err != nil { - return err - } - if rr.req.GetBody != nil { - // this will allow us to preserve the body without having to - // make a copy. note we need to do this on each iteration - rr.rc, err = rr.req.GetBody() - if err != nil { - return err - } - } else if rr.br == nil { - // fall back to making a copy (only do this once) - err = rr.prepareFromByteReader() - } - } - return err -} - -func removeRequestBody(req *http.Request) { - req.Body = nil - req.GetBody = nil - req.ContentLength = 0 -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/sender.go b/vendor/github.com/Azure/go-autorest/autorest/sender.go deleted file mode 100644 index b4f762325..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/sender.go +++ /dev/null @@ -1,321 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "fmt" - "log" - "math" - "net/http" - "strconv" - "time" -) - -// Sender is the interface that wraps the Do method to send HTTP requests. -// -// The standard http.Client conforms to this interface. -type Sender interface { - Do(*http.Request) (*http.Response, error) -} - -// SenderFunc is a method that implements the Sender interface. -type SenderFunc func(*http.Request) (*http.Response, error) - -// Do implements the Sender interface on SenderFunc. -func (sf SenderFunc) Do(r *http.Request) (*http.Response, error) { - return sf(r) -} - -// SendDecorator takes and possibily decorates, by wrapping, a Sender. Decorators may affect the -// http.Request and pass it along or, first, pass the http.Request along then react to the -// http.Response result. -type SendDecorator func(Sender) Sender - -// CreateSender creates, decorates, and returns, as a Sender, the default http.Client. -func CreateSender(decorators ...SendDecorator) Sender { - return DecorateSender(&http.Client{}, decorators...) -} - -// DecorateSender accepts a Sender and a, possibly empty, set of SendDecorators, which is applies to -// the Sender. Decorators are applied in the order received, but their affect upon the request -// depends on whether they are a pre-decorator (change the http.Request and then pass it along) or a -// post-decorator (pass the http.Request along and react to the results in http.Response). -func DecorateSender(s Sender, decorators ...SendDecorator) Sender { - for _, decorate := range decorators { - s = decorate(s) - } - return s -} - -// Send sends, by means of the default http.Client, the passed http.Request, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// Send is a convenience method and not recommended for production. Advanced users should use -// SendWithSender, passing and sharing their own Sender (e.g., instance of http.Client). -// -// Send will not poll or retry requests. -func Send(r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return SendWithSender(&http.Client{}, r, decorators...) -} - -// SendWithSender sends the passed http.Request, through the provided Sender, returning the -// http.Response and possible error. It also accepts a, possibly empty, set of SendDecorators which -// it will apply the http.Client before invoking the Do method. -// -// SendWithSender will not poll or retry requests. -func SendWithSender(s Sender, r *http.Request, decorators ...SendDecorator) (*http.Response, error) { - return DecorateSender(s, decorators...).Do(r) -} - -// AfterDelay returns a SendDecorator that delays for the passed time.Duration before -// invoking the Sender. The delay may be terminated by closing the optional channel on the -// http.Request. If canceled, no further Senders are invoked. -func AfterDelay(d time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - if !DelayForBackoff(d, 0, r.Context().Done()) { - return nil, fmt.Errorf("autorest: AfterDelay canceled before full delay") - } - return s.Do(r) - }) - } -} - -// AsIs returns a SendDecorator that invokes the passed Sender without modifying the http.Request. -func AsIs() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - return s.Do(r) - }) - } -} - -// DoCloseIfError returns a SendDecorator that first invokes the passed Sender after which -// it closes the response if the passed Sender returns an error and the response body exists. -func DoCloseIfError() SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err != nil { - Respond(resp, ByDiscardingBody(), ByClosing()) - } - return resp, err - }) - } -} - -// DoErrorIfStatusCode returns a SendDecorator that emits an error if the response StatusCode is -// among the set passed. Since these are artificial errors, the response body may still require -// closing. -func DoErrorIfStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorIfStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoErrorUnlessStatusCode returns a SendDecorator that emits an error unless the response -// StatusCode is among the set passed. Since these are artificial errors, the response body -// may still require closing. -func DoErrorUnlessStatusCode(codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - resp, err := s.Do(r) - if err == nil && !ResponseHasStatusCode(resp, codes...) { - err = NewErrorWithResponse("autorest", "DoErrorUnlessStatusCode", resp, "%v %v failed with %s", - resp.Request.Method, - resp.Request.URL, - resp.Status) - } - return resp, err - }) - } -} - -// DoPollForStatusCodes returns a SendDecorator that polls if the http.Response contains one of the -// passed status codes. It expects the http.Response to contain a Location header providing the -// URL at which to poll (using GET) and will poll until the time passed is equal to or greater than -// the supplied duration. It will delay between requests for the duration specified in the -// RetryAfter header or, if the header is absent, the passed delay. Polling may be canceled by -// closing the optional channel on the http.Request. -func DoPollForStatusCodes(duration time.Duration, delay time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - resp, err = s.Do(r) - - if err == nil && ResponseHasStatusCode(resp, codes...) { - r, err = NewPollingRequestWithContext(r.Context(), resp) - - for err == nil && ResponseHasStatusCode(resp, codes...) { - Respond(resp, - ByDiscardingBody(), - ByClosing()) - resp, err = SendWithSender(s, r, - AfterDelay(GetRetryAfter(resp, delay))) - } - } - - return resp, err - }) - } -} - -// DoRetryForAttempts returns a SendDecorator that retries a failed request for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForAttempts(attempts int, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - for attempt := 0; attempt < attempts; attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// DoRetryForStatusCodes returns a SendDecorator that retries for specified statusCodes for up to the specified -// number of attempts, exponentially backing off between requests using the supplied backoff -// time.Duration (which may be zero). Retrying may be canceled by closing the optional channel on -// the http.Request. -func DoRetryForStatusCodes(attempts int, backoff time.Duration, codes ...int) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - // Increment to add the first call (attempts denotes number of retries) - attempts++ - for attempt := 0; attempt < attempts; { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - // we want to retry if err is not nil (e.g. transient network failure). note that for failed authentication - // resp and err will both have a value, so in this case we don't want to retry as it will never succeed. - if err == nil && !ResponseHasStatusCode(resp, codes...) || IsTokenRefreshError(err) { - return resp, err - } - delayed := DelayWithRetryAfter(resp, r.Context().Done()) - if !delayed && !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - // don't count a 429 against the number of attempts - // so that we continue to retry until it succeeds - if resp == nil || resp.StatusCode != http.StatusTooManyRequests { - attempt++ - } - } - return resp, err - }) - } -} - -// DelayWithRetryAfter invokes time.After for the duration specified in the "Retry-After" header in -// responses with status code 429 -func DelayWithRetryAfter(resp *http.Response, cancel <-chan struct{}) bool { - if resp == nil { - return false - } - retryAfter, _ := strconv.Atoi(resp.Header.Get("Retry-After")) - if resp.StatusCode == http.StatusTooManyRequests && retryAfter > 0 { - select { - case <-time.After(time.Duration(retryAfter) * time.Second): - return true - case <-cancel: - return false - } - } - return false -} - -// DoRetryForDuration returns a SendDecorator that retries the request until the total time is equal -// to or greater than the specified duration, exponentially backing off between requests using the -// supplied backoff time.Duration (which may be zero). Retrying may be canceled by closing the -// optional channel on the http.Request. -func DoRetryForDuration(d time.Duration, backoff time.Duration) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (resp *http.Response, err error) { - rr := NewRetriableRequest(r) - end := time.Now().Add(d) - for attempt := 0; time.Now().Before(end); attempt++ { - err = rr.Prepare() - if err != nil { - return resp, err - } - resp, err = s.Do(rr.Request()) - if err == nil { - return resp, err - } - if !DelayForBackoff(backoff, attempt, r.Context().Done()) { - return nil, r.Context().Err() - } - } - return resp, err - }) - } -} - -// WithLogging returns a SendDecorator that implements simple before and after logging of the -// request. -func WithLogging(logger *log.Logger) SendDecorator { - return func(s Sender) Sender { - return SenderFunc(func(r *http.Request) (*http.Response, error) { - logger.Printf("Sending %s %s", r.Method, r.URL) - resp, err := s.Do(r) - if err != nil { - logger.Printf("%s %s received error '%v'", r.Method, r.URL, err) - } else { - logger.Printf("%s %s received %s", r.Method, r.URL, resp.Status) - } - return resp, err - }) - } -} - -// DelayForBackoff invokes time.After for the supplied backoff duration raised to the power of -// passed attempt (i.e., an exponential backoff delay). Backoff duration is in seconds and can set -// to zero for no delay. The delay may be canceled by closing the passed channel. If terminated early, -// returns false. -// Note: Passing attempt 1 will result in doubling "backoff" duration. Treat this as a zero-based attempt -// count. -func DelayForBackoff(backoff time.Duration, attempt int, cancel <-chan struct{}) bool { - select { - case <-time.After(time.Duration(backoff.Seconds()*math.Pow(2, float64(attempt))) * time.Second): - return true - case <-cancel: - return false - } -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go b/vendor/github.com/Azure/go-autorest/autorest/to/convert.go deleted file mode 100644 index fdda2ce1a..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/to/convert.go +++ /dev/null @@ -1,147 +0,0 @@ -/* -Package to provides helpers to ease working with pointer values of marshalled structures. -*/ -package to - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// String returns a string value for the passed string pointer. It returns the empty string if the -// pointer is nil. -func String(s *string) string { - if s != nil { - return *s - } - return "" -} - -// StringPtr returns a pointer to the passed string. -func StringPtr(s string) *string { - return &s -} - -// StringSlice returns a string slice value for the passed string slice pointer. It returns a nil -// slice if the pointer is nil. -func StringSlice(s *[]string) []string { - if s != nil { - return *s - } - return nil -} - -// StringSlicePtr returns a pointer to the passed string slice. -func StringSlicePtr(s []string) *[]string { - return &s -} - -// StringMap returns a map of strings built from the map of string pointers. The empty string is -// used for nil pointers. -func StringMap(msp map[string]*string) map[string]string { - ms := make(map[string]string, len(msp)) - for k, sp := range msp { - if sp != nil { - ms[k] = *sp - } else { - ms[k] = "" - } - } - return ms -} - -// StringMapPtr returns a pointer to a map of string pointers built from the passed map of strings. -func StringMapPtr(ms map[string]string) *map[string]*string { - msp := make(map[string]*string, len(ms)) - for k, s := range ms { - msp[k] = StringPtr(s) - } - return &msp -} - -// Bool returns a bool value for the passed bool pointer. It returns false if the pointer is nil. -func Bool(b *bool) bool { - if b != nil { - return *b - } - return false -} - -// BoolPtr returns a pointer to the passed bool. -func BoolPtr(b bool) *bool { - return &b -} - -// Int returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int(i *int) int { - if i != nil { - return *i - } - return 0 -} - -// IntPtr returns a pointer to the passed int. -func IntPtr(i int) *int { - return &i -} - -// Int32 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int32(i *int32) int32 { - if i != nil { - return *i - } - return 0 -} - -// Int32Ptr returns a pointer to the passed int32. -func Int32Ptr(i int32) *int32 { - return &i -} - -// Int64 returns an int value for the passed int pointer. It returns 0 if the pointer is nil. -func Int64(i *int64) int64 { - if i != nil { - return *i - } - return 0 -} - -// Int64Ptr returns a pointer to the passed int64. -func Int64Ptr(i int64) *int64 { - return &i -} - -// Float32 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float32(i *float32) float32 { - if i != nil { - return *i - } - return 0.0 -} - -// Float32Ptr returns a pointer to the passed float32. -func Float32Ptr(i float32) *float32 { - return &i -} - -// Float64 returns an int value for the passed int pointer. It returns 0.0 if the pointer is nil. -func Float64(i *float64) float64 { - if i != nil { - return *i - } - return 0.0 -} - -// Float64Ptr returns a pointer to the passed float64. -func Float64Ptr(i float64) *float64 { - return &i -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/utility.go b/vendor/github.com/Azure/go-autorest/autorest/utility.go deleted file mode 100644 index afb3e4e16..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/utility.go +++ /dev/null @@ -1,218 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -import ( - "bytes" - "encoding/json" - "encoding/xml" - "fmt" - "io" - "net/http" - "net/url" - "reflect" - "strings" - - "github.com/Azure/go-autorest/autorest/adal" -) - -// EncodedAs is a series of constants specifying various data encodings -type EncodedAs string - -const ( - // EncodedAsJSON states that data is encoded as JSON - EncodedAsJSON EncodedAs = "JSON" - - // EncodedAsXML states that data is encoded as Xml - EncodedAsXML EncodedAs = "XML" -) - -// Decoder defines the decoding method json.Decoder and xml.Decoder share -type Decoder interface { - Decode(v interface{}) error -} - -// NewDecoder creates a new decoder appropriate to the passed encoding. -// encodedAs specifies the type of encoding and r supplies the io.Reader containing the -// encoded data. -func NewDecoder(encodedAs EncodedAs, r io.Reader) Decoder { - if encodedAs == EncodedAsJSON { - return json.NewDecoder(r) - } else if encodedAs == EncodedAsXML { - return xml.NewDecoder(r) - } - return nil -} - -// CopyAndDecode decodes the data from the passed io.Reader while making a copy. Having a copy -// is especially useful if there is a chance the data will fail to decode. -// encodedAs specifies the expected encoding, r provides the io.Reader to the data, and v -// is the decoding destination. -func CopyAndDecode(encodedAs EncodedAs, r io.Reader, v interface{}) (bytes.Buffer, error) { - b := bytes.Buffer{} - return b, NewDecoder(encodedAs, io.TeeReader(r, &b)).Decode(v) -} - -// TeeReadCloser returns a ReadCloser that writes to w what it reads from rc. -// It utilizes io.TeeReader to copy the data read and has the same behavior when reading. -// Further, when it is closed, it ensures that rc is closed as well. -func TeeReadCloser(rc io.ReadCloser, w io.Writer) io.ReadCloser { - return &teeReadCloser{rc, io.TeeReader(rc, w)} -} - -type teeReadCloser struct { - rc io.ReadCloser - r io.Reader -} - -func (t *teeReadCloser) Read(p []byte) (int, error) { - return t.r.Read(p) -} - -func (t *teeReadCloser) Close() error { - return t.rc.Close() -} - -func containsInt(ints []int, n int) bool { - for _, i := range ints { - if i == n { - return true - } - } - return false -} - -func escapeValueStrings(m map[string]string) map[string]string { - for key, value := range m { - m[key] = url.QueryEscape(value) - } - return m -} - -func ensureValueStrings(mapOfInterface map[string]interface{}) map[string]string { - mapOfStrings := make(map[string]string) - for key, value := range mapOfInterface { - mapOfStrings[key] = ensureValueString(value) - } - return mapOfStrings -} - -func ensureValueString(value interface{}) string { - if value == nil { - return "" - } - switch v := value.(type) { - case string: - return v - case []byte: - return string(v) - default: - return fmt.Sprintf("%v", v) - } -} - -// MapToValues method converts map[string]interface{} to url.Values. -func MapToValues(m map[string]interface{}) url.Values { - v := url.Values{} - for key, value := range m { - x := reflect.ValueOf(value) - if x.Kind() == reflect.Array || x.Kind() == reflect.Slice { - for i := 0; i < x.Len(); i++ { - v.Add(key, ensureValueString(x.Index(i))) - } - } else { - v.Add(key, ensureValueString(value)) - } - } - return v -} - -// AsStringSlice method converts interface{} to []string. This expects a -//that the parameter passed to be a slice or array of a type that has the underlying -//type a string. -func AsStringSlice(s interface{}) ([]string, error) { - v := reflect.ValueOf(s) - if v.Kind() != reflect.Slice && v.Kind() != reflect.Array { - return nil, NewError("autorest", "AsStringSlice", "the value's type is not an array.") - } - stringSlice := make([]string, 0, v.Len()) - - for i := 0; i < v.Len(); i++ { - stringSlice = append(stringSlice, v.Index(i).String()) - } - return stringSlice, nil -} - -// String method converts interface v to string. If interface is a list, it -// joins list elements using the seperator. Note that only sep[0] will be used for -// joining if any separator is specified. -func String(v interface{}, sep ...string) string { - if len(sep) == 0 { - return ensureValueString(v) - } - stringSlice, ok := v.([]string) - if ok == false { - var err error - stringSlice, err = AsStringSlice(v) - if err != nil { - panic(fmt.Sprintf("autorest: Couldn't convert value to a string %s.", err)) - } - } - return ensureValueString(strings.Join(stringSlice, sep[0])) -} - -// Encode method encodes url path and query parameters. -func Encode(location string, v interface{}, sep ...string) string { - s := String(v, sep...) - switch strings.ToLower(location) { - case "path": - return pathEscape(s) - case "query": - return queryEscape(s) - default: - return s - } -} - -func pathEscape(s string) string { - return strings.Replace(url.QueryEscape(s), "+", "%20", -1) -} - -func queryEscape(s string) string { - return url.QueryEscape(s) -} - -// ChangeToGet turns the specified http.Request into a GET (it assumes it wasn't). -// This is mainly useful for long-running operations that use the Azure-AsyncOperation -// header, so we change the initial PUT into a GET to retrieve the final result. -func ChangeToGet(req *http.Request) *http.Request { - req.Method = "GET" - req.Body = nil - req.ContentLength = 0 - req.Header.Del("Content-Length") - return req -} - -// IsTokenRefreshError returns true if the specified error implements the TokenRefreshError -// interface. If err is a DetailedError it will walk the chain of Original errors. -func IsTokenRefreshError(err error) bool { - if _, ok := err.(adal.TokenRefreshError); ok { - return true - } - if de, ok := err.(DetailedError); ok { - return IsTokenRefreshError(de.Original) - } - return false -} diff --git a/vendor/github.com/Azure/go-autorest/autorest/version.go b/vendor/github.com/Azure/go-autorest/autorest/version.go deleted file mode 100644 index 4ad7754ad..000000000 --- a/vendor/github.com/Azure/go-autorest/autorest/version.go +++ /dev/null @@ -1,20 +0,0 @@ -package autorest - -// Copyright 2017 Microsoft Corporation -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Version returns the semantic version (see http://semver.org). -func Version() string { - return "v10.5.0" -} diff --git a/vendor/github.com/BurntSushi/toml/COPYING b/vendor/github.com/BurntSushi/toml/COPYING deleted file mode 100644 index 01b574320..000000000 --- a/vendor/github.com/BurntSushi/toml/COPYING +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 TOML authors - -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/BurntSushi/toml/cmd/toml-test-decoder/COPYING b/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING deleted file mode 100644 index 5a8e33254..000000000 --- a/vendor/github.com/BurntSushi/toml/cmd/toml-test-decoder/COPYING +++ /dev/null @@ -1,14 +0,0 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING b/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING deleted file mode 100644 index 5a8e33254..000000000 --- a/vendor/github.com/BurntSushi/toml/cmd/toml-test-encoder/COPYING +++ /dev/null @@ -1,14 +0,0 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING b/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING deleted file mode 100644 index 5a8e33254..000000000 --- a/vendor/github.com/BurntSushi/toml/cmd/tomlv/COPYING +++ /dev/null @@ -1,14 +0,0 @@ - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - Version 2, December 2004 - - Copyright (C) 2004 Sam Hocevar - - Everyone is permitted to copy and distribute verbatim or modified - copies of this license document, and changing it is allowed as long - as the name is changed. - - DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. You just DO WHAT THE FUCK YOU WANT TO. - diff --git a/vendor/github.com/BurntSushi/toml/decode.go b/vendor/github.com/BurntSushi/toml/decode.go deleted file mode 100644 index b0fd51d5b..000000000 --- a/vendor/github.com/BurntSushi/toml/decode.go +++ /dev/null @@ -1,509 +0,0 @@ -package toml - -import ( - "fmt" - "io" - "io/ioutil" - "math" - "reflect" - "strings" - "time" -) - -func e(format string, args ...interface{}) error { - return fmt.Errorf("toml: "+format, args...) -} - -// Unmarshaler is the interface implemented by objects that can unmarshal a -// TOML description of themselves. -type Unmarshaler interface { - UnmarshalTOML(interface{}) error -} - -// Unmarshal decodes the contents of `p` in TOML format into a pointer `v`. -func Unmarshal(p []byte, v interface{}) error { - _, err := Decode(string(p), v) - return err -} - -// Primitive is a TOML value that hasn't been decoded into a Go value. -// When using the various `Decode*` functions, the type `Primitive` may -// be given to any value, and its decoding will be delayed. -// -// A `Primitive` value can be decoded using the `PrimitiveDecode` function. -// -// The underlying representation of a `Primitive` value is subject to change. -// Do not rely on it. -// -// N.B. Primitive values are still parsed, so using them will only avoid -// the overhead of reflection. They can be useful when you don't know the -// exact type of TOML data until run time. -type Primitive struct { - undecoded interface{} - context Key -} - -// DEPRECATED! -// -// Use MetaData.PrimitiveDecode instead. -func PrimitiveDecode(primValue Primitive, v interface{}) error { - md := MetaData{decoded: make(map[string]bool)} - return md.unify(primValue.undecoded, rvalue(v)) -} - -// PrimitiveDecode is just like the other `Decode*` functions, except it -// decodes a TOML value that has already been parsed. Valid primitive values -// can *only* be obtained from values filled by the decoder functions, -// including this method. (i.e., `v` may contain more `Primitive` -// values.) -// -// Meta data for primitive values is included in the meta data returned by -// the `Decode*` functions with one exception: keys returned by the Undecoded -// method will only reflect keys that were decoded. Namely, any keys hidden -// behind a Primitive will be considered undecoded. Executing this method will -// update the undecoded keys in the meta data. (See the example.) -func (md *MetaData) PrimitiveDecode(primValue Primitive, v interface{}) error { - md.context = primValue.context - defer func() { md.context = nil }() - return md.unify(primValue.undecoded, rvalue(v)) -} - -// Decode will decode the contents of `data` in TOML format into a pointer -// `v`. -// -// TOML hashes correspond to Go structs or maps. (Dealer's choice. They can be -// used interchangeably.) -// -// TOML arrays of tables correspond to either a slice of structs or a slice -// of maps. -// -// TOML datetimes correspond to Go `time.Time` values. -// -// All other TOML types (float, string, int, bool and array) correspond -// to the obvious Go types. -// -// An exception to the above rules is if a type implements the -// encoding.TextUnmarshaler interface. In this case, any primitive TOML value -// (floats, strings, integers, booleans and datetimes) will be converted to -// a byte string and given to the value's UnmarshalText method. See the -// Unmarshaler example for a demonstration with time duration strings. -// -// Key mapping -// -// TOML keys can map to either keys in a Go map or field names in a Go -// struct. The special `toml` struct tag may be used to map TOML keys to -// struct fields that don't match the key name exactly. (See the example.) -// A case insensitive match to struct names will be tried if an exact match -// can't be found. -// -// The mapping between TOML values and Go values is loose. That is, there -// may exist TOML values that cannot be placed into your representation, and -// there may be parts of your representation that do not correspond to -// TOML values. This loose mapping can be made stricter by using the IsDefined -// and/or Undecoded methods on the MetaData returned. -// -// This decoder will not handle cyclic types. If a cyclic type is passed, -// `Decode` will not terminate. -func Decode(data string, v interface{}) (MetaData, error) { - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr { - return MetaData{}, e("Decode of non-pointer %s", reflect.TypeOf(v)) - } - if rv.IsNil() { - return MetaData{}, e("Decode of nil %s", reflect.TypeOf(v)) - } - p, err := parse(data) - if err != nil { - return MetaData{}, err - } - md := MetaData{ - p.mapping, p.types, p.ordered, - make(map[string]bool, len(p.ordered)), nil, - } - return md, md.unify(p.mapping, indirect(rv)) -} - -// DecodeFile is just like Decode, except it will automatically read the -// contents of the file at `fpath` and decode it for you. -func DecodeFile(fpath string, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadFile(fpath) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// DecodeReader is just like Decode, except it will consume all bytes -// from the reader and decode it for you. -func DecodeReader(r io.Reader, v interface{}) (MetaData, error) { - bs, err := ioutil.ReadAll(r) - if err != nil { - return MetaData{}, err - } - return Decode(string(bs), v) -} - -// unify performs a sort of type unification based on the structure of `rv`, -// which is the client representation. -// -// Any type mismatch produces an error. Finding a type that we don't know -// how to handle produces an unsupported type error. -func (md *MetaData) unify(data interface{}, rv reflect.Value) error { - - // Special case. Look for a `Primitive` value. - if rv.Type() == reflect.TypeOf((*Primitive)(nil)).Elem() { - // Save the undecoded data and the key context into the primitive - // value. - context := make(Key, len(md.context)) - copy(context, md.context) - rv.Set(reflect.ValueOf(Primitive{ - undecoded: data, - context: context, - })) - return nil - } - - // Special case. Unmarshaler Interface support. - if rv.CanAddr() { - if v, ok := rv.Addr().Interface().(Unmarshaler); ok { - return v.UnmarshalTOML(data) - } - } - - // Special case. Handle time.Time values specifically. - // TODO: Remove this code when we decide to drop support for Go 1.1. - // This isn't necessary in Go 1.2 because time.Time satisfies the encoding - // interfaces. - if rv.Type().AssignableTo(rvalue(time.Time{}).Type()) { - return md.unifyDatetime(data, rv) - } - - // Special case. Look for a value satisfying the TextUnmarshaler interface. - if v, ok := rv.Interface().(TextUnmarshaler); ok { - return md.unifyText(data, v) - } - // BUG(burntsushi) - // The behavior here is incorrect whenever a Go type satisfies the - // encoding.TextUnmarshaler interface but also corresponds to a TOML - // hash or array. In particular, the unmarshaler should only be applied - // to primitive TOML values. But at this point, it will be applied to - // all kinds of values and produce an incorrect error whenever those values - // are hashes or arrays (including arrays of tables). - - k := rv.Kind() - - // laziness - if k >= reflect.Int && k <= reflect.Uint64 { - return md.unifyInt(data, rv) - } - switch k { - case reflect.Ptr: - elem := reflect.New(rv.Type().Elem()) - err := md.unify(data, reflect.Indirect(elem)) - if err != nil { - return err - } - rv.Set(elem) - return nil - case reflect.Struct: - return md.unifyStruct(data, rv) - case reflect.Map: - return md.unifyMap(data, rv) - case reflect.Array: - return md.unifyArray(data, rv) - case reflect.Slice: - return md.unifySlice(data, rv) - case reflect.String: - return md.unifyString(data, rv) - case reflect.Bool: - return md.unifyBool(data, rv) - case reflect.Interface: - // we only support empty interfaces. - if rv.NumMethod() > 0 { - return e("unsupported type %s", rv.Type()) - } - return md.unifyAnything(data, rv) - case reflect.Float32: - fallthrough - case reflect.Float64: - return md.unifyFloat64(data, rv) - } - return e("unsupported type %s", rv.Kind()) -} - -func (md *MetaData) unifyStruct(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - if mapping == nil { - return nil - } - return e("type mismatch for %s: expected table but found %T", - rv.Type().String(), mapping) - } - - for key, datum := range tmap { - var f *field - fields := cachedTypeFields(rv.Type()) - for i := range fields { - ff := &fields[i] - if ff.name == key { - f = ff - break - } - if f == nil && strings.EqualFold(ff.name, key) { - f = ff - } - } - if f != nil { - subv := rv - for _, i := range f.index { - subv = indirect(subv.Field(i)) - } - if isUnifiable(subv) { - md.decoded[md.context.add(key).String()] = true - md.context = append(md.context, key) - if err := md.unify(datum, subv); err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - } else if f.name != "" { - // Bad user! No soup for you! - return e("cannot write unexported field %s.%s", - rv.Type().String(), f.name) - } - } - } - return nil -} - -func (md *MetaData) unifyMap(mapping interface{}, rv reflect.Value) error { - tmap, ok := mapping.(map[string]interface{}) - if !ok { - if tmap == nil { - return nil - } - return badtype("map", mapping) - } - if rv.IsNil() { - rv.Set(reflect.MakeMap(rv.Type())) - } - for k, v := range tmap { - md.decoded[md.context.add(k).String()] = true - md.context = append(md.context, k) - - rvkey := indirect(reflect.New(rv.Type().Key())) - rvval := reflect.Indirect(reflect.New(rv.Type().Elem())) - if err := md.unify(v, rvval); err != nil { - return err - } - md.context = md.context[0 : len(md.context)-1] - - rvkey.SetString(k) - rv.SetMapIndex(rvkey, rvval) - } - return nil -} - -func (md *MetaData) unifyArray(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return badtype("slice", data) - } - sliceLen := datav.Len() - if sliceLen != rv.Len() { - return e("expected array length %d; got TOML array of length %d", - rv.Len(), sliceLen) - } - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySlice(data interface{}, rv reflect.Value) error { - datav := reflect.ValueOf(data) - if datav.Kind() != reflect.Slice { - if !datav.IsValid() { - return nil - } - return badtype("slice", data) - } - n := datav.Len() - if rv.IsNil() || rv.Cap() < n { - rv.Set(reflect.MakeSlice(rv.Type(), n, n)) - } - rv.SetLen(n) - return md.unifySliceArray(datav, rv) -} - -func (md *MetaData) unifySliceArray(data, rv reflect.Value) error { - sliceLen := data.Len() - for i := 0; i < sliceLen; i++ { - v := data.Index(i).Interface() - sliceval := indirect(rv.Index(i)) - if err := md.unify(v, sliceval); err != nil { - return err - } - } - return nil -} - -func (md *MetaData) unifyDatetime(data interface{}, rv reflect.Value) error { - if _, ok := data.(time.Time); ok { - rv.Set(reflect.ValueOf(data)) - return nil - } - return badtype("time.Time", data) -} - -func (md *MetaData) unifyString(data interface{}, rv reflect.Value) error { - if s, ok := data.(string); ok { - rv.SetString(s) - return nil - } - return badtype("string", data) -} - -func (md *MetaData) unifyFloat64(data interface{}, rv reflect.Value) error { - if num, ok := data.(float64); ok { - switch rv.Kind() { - case reflect.Float32: - fallthrough - case reflect.Float64: - rv.SetFloat(num) - default: - panic("bug") - } - return nil - } - return badtype("float", data) -} - -func (md *MetaData) unifyInt(data interface{}, rv reflect.Value) error { - if num, ok := data.(int64); ok { - if rv.Kind() >= reflect.Int && rv.Kind() <= reflect.Int64 { - switch rv.Kind() { - case reflect.Int, reflect.Int64: - // No bounds checking necessary. - case reflect.Int8: - if num < math.MinInt8 || num > math.MaxInt8 { - return e("value %d is out of range for int8", num) - } - case reflect.Int16: - if num < math.MinInt16 || num > math.MaxInt16 { - return e("value %d is out of range for int16", num) - } - case reflect.Int32: - if num < math.MinInt32 || num > math.MaxInt32 { - return e("value %d is out of range for int32", num) - } - } - rv.SetInt(num) - } else if rv.Kind() >= reflect.Uint && rv.Kind() <= reflect.Uint64 { - unum := uint64(num) - switch rv.Kind() { - case reflect.Uint, reflect.Uint64: - // No bounds checking necessary. - case reflect.Uint8: - if num < 0 || unum > math.MaxUint8 { - return e("value %d is out of range for uint8", num) - } - case reflect.Uint16: - if num < 0 || unum > math.MaxUint16 { - return e("value %d is out of range for uint16", num) - } - case reflect.Uint32: - if num < 0 || unum > math.MaxUint32 { - return e("value %d is out of range for uint32", num) - } - } - rv.SetUint(unum) - } else { - panic("unreachable") - } - return nil - } - return badtype("integer", data) -} - -func (md *MetaData) unifyBool(data interface{}, rv reflect.Value) error { - if b, ok := data.(bool); ok { - rv.SetBool(b) - return nil - } - return badtype("boolean", data) -} - -func (md *MetaData) unifyAnything(data interface{}, rv reflect.Value) error { - rv.Set(reflect.ValueOf(data)) - return nil -} - -func (md *MetaData) unifyText(data interface{}, v TextUnmarshaler) error { - var s string - switch sdata := data.(type) { - case TextMarshaler: - text, err := sdata.MarshalText() - if err != nil { - return err - } - s = string(text) - case fmt.Stringer: - s = sdata.String() - case string: - s = sdata - case bool: - s = fmt.Sprintf("%v", sdata) - case int64: - s = fmt.Sprintf("%d", sdata) - case float64: - s = fmt.Sprintf("%f", sdata) - default: - return badtype("primitive (string-like)", data) - } - if err := v.UnmarshalText([]byte(s)); err != nil { - return err - } - return nil -} - -// rvalue returns a reflect.Value of `v`. All pointers are resolved. -func rvalue(v interface{}) reflect.Value { - return indirect(reflect.ValueOf(v)) -} - -// indirect returns the value pointed to by a pointer. -// Pointers are followed until the value is not a pointer. -// New values are allocated for each nil pointer. -// -// An exception to this rule is if the value satisfies an interface of -// interest to us (like encoding.TextUnmarshaler). -func indirect(v reflect.Value) reflect.Value { - if v.Kind() != reflect.Ptr { - if v.CanSet() { - pv := v.Addr() - if _, ok := pv.Interface().(TextUnmarshaler); ok { - return pv - } - } - return v - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - return indirect(reflect.Indirect(v)) -} - -func isUnifiable(rv reflect.Value) bool { - if rv.CanSet() { - return true - } - if _, ok := rv.Interface().(TextUnmarshaler); ok { - return true - } - return false -} - -func badtype(expected string, data interface{}) error { - return e("cannot load TOML value of type %T into a Go %s", data, expected) -} diff --git a/vendor/github.com/BurntSushi/toml/decode_meta.go b/vendor/github.com/BurntSushi/toml/decode_meta.go deleted file mode 100644 index b9914a679..000000000 --- a/vendor/github.com/BurntSushi/toml/decode_meta.go +++ /dev/null @@ -1,121 +0,0 @@ -package toml - -import "strings" - -// MetaData allows access to meta information about TOML data that may not -// be inferrable via reflection. In particular, whether a key has been defined -// and the TOML type of a key. -type MetaData struct { - mapping map[string]interface{} - types map[string]tomlType - keys []Key - decoded map[string]bool - context Key // Used only during decoding. -} - -// IsDefined returns true if the key given exists in the TOML data. The key -// should be specified hierarchially. e.g., -// -// // access the TOML key 'a.b.c' -// IsDefined("a", "b", "c") -// -// IsDefined will return false if an empty key given. Keys are case sensitive. -func (md *MetaData) IsDefined(key ...string) bool { - if len(key) == 0 { - return false - } - - var hash map[string]interface{} - var ok bool - var hashOrVal interface{} = md.mapping - for _, k := range key { - if hash, ok = hashOrVal.(map[string]interface{}); !ok { - return false - } - if hashOrVal, ok = hash[k]; !ok { - return false - } - } - return true -} - -// Type returns a string representation of the type of the key specified. -// -// Type will return the empty string if given an empty key or a key that -// does not exist. Keys are case sensitive. -func (md *MetaData) Type(key ...string) string { - fullkey := strings.Join(key, ".") - if typ, ok := md.types[fullkey]; ok { - return typ.typeString() - } - return "" -} - -// Key is the type of any TOML key, including key groups. Use (MetaData).Keys -// to get values of this type. -type Key []string - -func (k Key) String() string { - return strings.Join(k, ".") -} - -func (k Key) maybeQuotedAll() string { - var ss []string - for i := range k { - ss = append(ss, k.maybeQuoted(i)) - } - return strings.Join(ss, ".") -} - -func (k Key) maybeQuoted(i int) string { - quote := false - for _, c := range k[i] { - if !isBareKeyChar(c) { - quote = true - break - } - } - if quote { - return "\"" + strings.Replace(k[i], "\"", "\\\"", -1) + "\"" - } - return k[i] -} - -func (k Key) add(piece string) Key { - newKey := make(Key, len(k)+1) - copy(newKey, k) - newKey[len(k)] = piece - return newKey -} - -// Keys returns a slice of every key in the TOML data, including key groups. -// Each key is itself a slice, where the first element is the top of the -// hierarchy and the last is the most specific. -// -// The list will have the same order as the keys appeared in the TOML data. -// -// All keys returned are non-empty. -func (md *MetaData) Keys() []Key { - return md.keys -} - -// Undecoded returns all keys that have not been decoded in the order in which -// they appear in the original TOML document. -// -// This includes keys that haven't been decoded because of a Primitive value. -// Once the Primitive value is decoded, the keys will be considered decoded. -// -// Also note that decoding into an empty interface will result in no decoding, -// and so no keys will be considered decoded. -// -// In this sense, the Undecoded keys correspond to keys in the TOML document -// that do not have a concrete type in your representation. -func (md *MetaData) Undecoded() []Key { - undecoded := make([]Key, 0, len(md.keys)) - for _, key := range md.keys { - if !md.decoded[key.String()] { - undecoded = append(undecoded, key) - } - } - return undecoded -} diff --git a/vendor/github.com/BurntSushi/toml/doc.go b/vendor/github.com/BurntSushi/toml/doc.go deleted file mode 100644 index b371f396e..000000000 --- a/vendor/github.com/BurntSushi/toml/doc.go +++ /dev/null @@ -1,27 +0,0 @@ -/* -Package toml provides facilities for decoding and encoding TOML configuration -files via reflection. There is also support for delaying decoding with -the Primitive type, and querying the set of keys in a TOML document with the -MetaData type. - -The specification implemented: https://github.com/toml-lang/toml - -The sub-command github.com/BurntSushi/toml/cmd/tomlv can be used to verify -whether a file is a valid TOML document. It can also be used to print the -type of each key in a TOML document. - -Testing - -There are two important types of tests used for this package. The first is -contained inside '*_test.go' files and uses the standard Go unit testing -framework. These tests are primarily devoted to holistically testing the -decoder and encoder. - -The second type of testing is used to verify the implementation's adherence -to the TOML specification. These tests have been factored into their own -project: https://github.com/BurntSushi/toml-test - -The reason the tests are in a separate project is so that they can be used by -any implementation of TOML. Namely, it is language agnostic. -*/ -package toml diff --git a/vendor/github.com/BurntSushi/toml/encode.go b/vendor/github.com/BurntSushi/toml/encode.go deleted file mode 100644 index d905c21a2..000000000 --- a/vendor/github.com/BurntSushi/toml/encode.go +++ /dev/null @@ -1,568 +0,0 @@ -package toml - -import ( - "bufio" - "errors" - "fmt" - "io" - "reflect" - "sort" - "strconv" - "strings" - "time" -) - -type tomlEncodeError struct{ error } - -var ( - errArrayMixedElementTypes = errors.New( - "toml: cannot encode array with mixed element types") - errArrayNilElement = errors.New( - "toml: cannot encode array with nil element") - errNonString = errors.New( - "toml: cannot encode a map with non-string key type") - errAnonNonStruct = errors.New( - "toml: cannot encode an anonymous field that is not a struct") - errArrayNoTable = errors.New( - "toml: TOML array element cannot contain a table") - errNoKey = errors.New( - "toml: top-level values must be Go maps or structs") - errAnything = errors.New("") // used in testing -) - -var quotedReplacer = strings.NewReplacer( - "\t", "\\t", - "\n", "\\n", - "\r", "\\r", - "\"", "\\\"", - "\\", "\\\\", -) - -// Encoder controls the encoding of Go values to a TOML document to some -// io.Writer. -// -// The indentation level can be controlled with the Indent field. -type Encoder struct { - // A single indentation level. By default it is two spaces. - Indent string - - // hasWritten is whether we have written any output to w yet. - hasWritten bool - w *bufio.Writer -} - -// NewEncoder returns a TOML encoder that encodes Go values to the io.Writer -// given. By default, a single indentation level is 2 spaces. -func NewEncoder(w io.Writer) *Encoder { - return &Encoder{ - w: bufio.NewWriter(w), - Indent: " ", - } -} - -// Encode writes a TOML representation of the Go value to the underlying -// io.Writer. If the value given cannot be encoded to a valid TOML document, -// then an error is returned. -// -// The mapping between Go values and TOML values should be precisely the same -// as for the Decode* functions. Similarly, the TextMarshaler interface is -// supported by encoding the resulting bytes as strings. (If you want to write -// arbitrary binary data then you will need to use something like base64 since -// TOML does not have any binary types.) -// -// When encoding TOML hashes (i.e., Go maps or structs), keys without any -// sub-hashes are encoded first. -// -// If a Go map is encoded, then its keys are sorted alphabetically for -// deterministic output. More control over this behavior may be provided if -// there is demand for it. -// -// Encoding Go values without a corresponding TOML representation---like map -// types with non-string keys---will cause an error to be returned. Similarly -// for mixed arrays/slices, arrays/slices with nil elements, embedded -// non-struct types and nested slices containing maps or structs. -// (e.g., [][]map[string]string is not allowed but []map[string]string is OK -// and so is []map[string][]string.) -func (enc *Encoder) Encode(v interface{}) error { - rv := eindirect(reflect.ValueOf(v)) - if err := enc.safeEncode(Key([]string{}), rv); err != nil { - return err - } - return enc.w.Flush() -} - -func (enc *Encoder) safeEncode(key Key, rv reflect.Value) (err error) { - defer func() { - if r := recover(); r != nil { - if terr, ok := r.(tomlEncodeError); ok { - err = terr.error - return - } - panic(r) - } - }() - enc.encode(key, rv) - return nil -} - -func (enc *Encoder) encode(key Key, rv reflect.Value) { - // Special case. Time needs to be in ISO8601 format. - // Special case. If we can marshal the type to text, then we used that. - // Basically, this prevents the encoder for handling these types as - // generic structs (or whatever the underlying type of a TextMarshaler is). - switch rv.Interface().(type) { - case time.Time, TextMarshaler: - enc.keyEqElement(key, rv) - return - } - - k := rv.Kind() - switch k { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64, - reflect.Float32, reflect.Float64, reflect.String, reflect.Bool: - enc.keyEqElement(key, rv) - case reflect.Array, reflect.Slice: - if typeEqual(tomlArrayHash, tomlTypeOfGo(rv)) { - enc.eArrayOfTables(key, rv) - } else { - enc.keyEqElement(key, rv) - } - case reflect.Interface: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Map: - if rv.IsNil() { - return - } - enc.eTable(key, rv) - case reflect.Ptr: - if rv.IsNil() { - return - } - enc.encode(key, rv.Elem()) - case reflect.Struct: - enc.eTable(key, rv) - default: - panic(e("unsupported type for key '%s': %s", key, k)) - } -} - -// eElement encodes any value that can be an array element (primitives and -// arrays). -func (enc *Encoder) eElement(rv reflect.Value) { - switch v := rv.Interface().(type) { - case time.Time: - // Special case time.Time as a primitive. Has to come before - // TextMarshaler below because time.Time implements - // encoding.TextMarshaler, but we need to always use UTC. - enc.wf(v.UTC().Format("2006-01-02T15:04:05Z")) - return - case TextMarshaler: - // Special case. Use text marshaler if it's available for this value. - if s, err := v.MarshalText(); err != nil { - encPanic(err) - } else { - enc.writeQuoted(string(s)) - } - return - } - switch rv.Kind() { - case reflect.Bool: - enc.wf(strconv.FormatBool(rv.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64: - enc.wf(strconv.FormatInt(rv.Int(), 10)) - case reflect.Uint, reflect.Uint8, reflect.Uint16, - reflect.Uint32, reflect.Uint64: - enc.wf(strconv.FormatUint(rv.Uint(), 10)) - case reflect.Float32: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 32))) - case reflect.Float64: - enc.wf(floatAddDecimal(strconv.FormatFloat(rv.Float(), 'f', -1, 64))) - case reflect.Array, reflect.Slice: - enc.eArrayOrSliceElement(rv) - case reflect.Interface: - enc.eElement(rv.Elem()) - case reflect.String: - enc.writeQuoted(rv.String()) - default: - panic(e("unexpected primitive type: %s", rv.Kind())) - } -} - -// By the TOML spec, all floats must have a decimal with at least one -// number on either side. -func floatAddDecimal(fstr string) string { - if !strings.Contains(fstr, ".") { - return fstr + ".0" - } - return fstr -} - -func (enc *Encoder) writeQuoted(s string) { - enc.wf("\"%s\"", quotedReplacer.Replace(s)) -} - -func (enc *Encoder) eArrayOrSliceElement(rv reflect.Value) { - length := rv.Len() - enc.wf("[") - for i := 0; i < length; i++ { - elem := rv.Index(i) - enc.eElement(elem) - if i != length-1 { - enc.wf(", ") - } - } - enc.wf("]") -} - -func (enc *Encoder) eArrayOfTables(key Key, rv reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - for i := 0; i < rv.Len(); i++ { - trv := rv.Index(i) - if isNil(trv) { - continue - } - panicIfInvalidKey(key) - enc.newline() - enc.wf("%s[[%s]]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - enc.eMapOrStruct(key, trv) - } -} - -func (enc *Encoder) eTable(key Key, rv reflect.Value) { - panicIfInvalidKey(key) - if len(key) == 1 { - // Output an extra newline between top-level tables. - // (The newline isn't written if nothing else has been written though.) - enc.newline() - } - if len(key) > 0 { - enc.wf("%s[%s]", enc.indentStr(key), key.maybeQuotedAll()) - enc.newline() - } - enc.eMapOrStruct(key, rv) -} - -func (enc *Encoder) eMapOrStruct(key Key, rv reflect.Value) { - switch rv := eindirect(rv); rv.Kind() { - case reflect.Map: - enc.eMap(key, rv) - case reflect.Struct: - enc.eStruct(key, rv) - default: - panic("eTable: unhandled reflect.Value Kind: " + rv.Kind().String()) - } -} - -func (enc *Encoder) eMap(key Key, rv reflect.Value) { - rt := rv.Type() - if rt.Key().Kind() != reflect.String { - encPanic(errNonString) - } - - // Sort keys so that we have deterministic output. And write keys directly - // underneath this key first, before writing sub-structs or sub-maps. - var mapKeysDirect, mapKeysSub []string - for _, mapKey := range rv.MapKeys() { - k := mapKey.String() - if typeIsHash(tomlTypeOfGo(rv.MapIndex(mapKey))) { - mapKeysSub = append(mapKeysSub, k) - } else { - mapKeysDirect = append(mapKeysDirect, k) - } - } - - var writeMapKeys = func(mapKeys []string) { - sort.Strings(mapKeys) - for _, mapKey := range mapKeys { - mrv := rv.MapIndex(reflect.ValueOf(mapKey)) - if isNil(mrv) { - // Don't write anything for nil fields. - continue - } - enc.encode(key.add(mapKey), mrv) - } - } - writeMapKeys(mapKeysDirect) - writeMapKeys(mapKeysSub) -} - -func (enc *Encoder) eStruct(key Key, rv reflect.Value) { - // Write keys for fields directly under this key first, because if we write - // a field that creates a new table, then all keys under it will be in that - // table (not the one we're writing here). - rt := rv.Type() - var fieldsDirect, fieldsSub [][]int - var addFields func(rt reflect.Type, rv reflect.Value, start []int) - addFields = func(rt reflect.Type, rv reflect.Value, start []int) { - for i := 0; i < rt.NumField(); i++ { - f := rt.Field(i) - // skip unexported fields - if f.PkgPath != "" && !f.Anonymous { - continue - } - frv := rv.Field(i) - if f.Anonymous { - t := f.Type - switch t.Kind() { - case reflect.Struct: - // Treat anonymous struct fields with - // tag names as though they are not - // anonymous, like encoding/json does. - if getOptions(f.Tag).name == "" { - addFields(t, frv, f.Index) - continue - } - case reflect.Ptr: - if t.Elem().Kind() == reflect.Struct && - getOptions(f.Tag).name == "" { - if !frv.IsNil() { - addFields(t.Elem(), frv.Elem(), f.Index) - } - continue - } - // Fall through to the normal field encoding logic below - // for non-struct anonymous fields. - } - } - - if typeIsHash(tomlTypeOfGo(frv)) { - fieldsSub = append(fieldsSub, append(start, f.Index...)) - } else { - fieldsDirect = append(fieldsDirect, append(start, f.Index...)) - } - } - } - addFields(rt, rv, nil) - - var writeFields = func(fields [][]int) { - for _, fieldIndex := range fields { - sft := rt.FieldByIndex(fieldIndex) - sf := rv.FieldByIndex(fieldIndex) - if isNil(sf) { - // Don't write anything for nil fields. - continue - } - - opts := getOptions(sft.Tag) - if opts.skip { - continue - } - keyName := sft.Name - if opts.name != "" { - keyName = opts.name - } - if opts.omitempty && isEmpty(sf) { - continue - } - if opts.omitzero && isZero(sf) { - continue - } - - enc.encode(key.add(keyName), sf) - } - } - writeFields(fieldsDirect) - writeFields(fieldsSub) -} - -// tomlTypeName returns the TOML type name of the Go value's type. It is -// used to determine whether the types of array elements are mixed (which is -// forbidden). If the Go value is nil, then it is illegal for it to be an array -// element, and valueIsNil is returned as true. - -// Returns the TOML type of a Go value. The type may be `nil`, which means -// no concrete TOML type could be found. -func tomlTypeOfGo(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() { - return nil - } - switch rv.Kind() { - case reflect.Bool: - return tomlBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, - reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, - reflect.Uint64: - return tomlInteger - case reflect.Float32, reflect.Float64: - return tomlFloat - case reflect.Array, reflect.Slice: - if typeEqual(tomlHash, tomlArrayType(rv)) { - return tomlArrayHash - } - return tomlArray - case reflect.Ptr, reflect.Interface: - return tomlTypeOfGo(rv.Elem()) - case reflect.String: - return tomlString - case reflect.Map: - return tomlHash - case reflect.Struct: - switch rv.Interface().(type) { - case time.Time: - return tomlDatetime - case TextMarshaler: - return tomlString - default: - return tomlHash - } - default: - panic("unexpected reflect.Kind: " + rv.Kind().String()) - } -} - -// tomlArrayType returns the element type of a TOML array. The type returned -// may be nil if it cannot be determined (e.g., a nil slice or a zero length -// slize). This function may also panic if it finds a type that cannot be -// expressed in TOML (such as nil elements, heterogeneous arrays or directly -// nested arrays of tables). -func tomlArrayType(rv reflect.Value) tomlType { - if isNil(rv) || !rv.IsValid() || rv.Len() == 0 { - return nil - } - firstType := tomlTypeOfGo(rv.Index(0)) - if firstType == nil { - encPanic(errArrayNilElement) - } - - rvlen := rv.Len() - for i := 1; i < rvlen; i++ { - elem := rv.Index(i) - switch elemType := tomlTypeOfGo(elem); { - case elemType == nil: - encPanic(errArrayNilElement) - case !typeEqual(firstType, elemType): - encPanic(errArrayMixedElementTypes) - } - } - // If we have a nested array, then we must make sure that the nested - // array contains ONLY primitives. - // This checks arbitrarily nested arrays. - if typeEqual(firstType, tomlArray) || typeEqual(firstType, tomlArrayHash) { - nest := tomlArrayType(eindirect(rv.Index(0))) - if typeEqual(nest, tomlHash) || typeEqual(nest, tomlArrayHash) { - encPanic(errArrayNoTable) - } - } - return firstType -} - -type tagOptions struct { - skip bool // "-" - name string - omitempty bool - omitzero bool -} - -func getOptions(tag reflect.StructTag) tagOptions { - t := tag.Get("toml") - if t == "-" { - return tagOptions{skip: true} - } - var opts tagOptions - parts := strings.Split(t, ",") - opts.name = parts[0] - for _, s := range parts[1:] { - switch s { - case "omitempty": - opts.omitempty = true - case "omitzero": - opts.omitzero = true - } - } - return opts -} - -func isZero(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return rv.Uint() == 0 - case reflect.Float32, reflect.Float64: - return rv.Float() == 0.0 - } - return false -} - -func isEmpty(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Array, reflect.Slice, reflect.Map, reflect.String: - return rv.Len() == 0 - case reflect.Bool: - return !rv.Bool() - } - return false -} - -func (enc *Encoder) newline() { - if enc.hasWritten { - enc.wf("\n") - } -} - -func (enc *Encoder) keyEqElement(key Key, val reflect.Value) { - if len(key) == 0 { - encPanic(errNoKey) - } - panicIfInvalidKey(key) - enc.wf("%s%s = ", enc.indentStr(key), key.maybeQuoted(len(key)-1)) - enc.eElement(val) - enc.newline() -} - -func (enc *Encoder) wf(format string, v ...interface{}) { - if _, err := fmt.Fprintf(enc.w, format, v...); err != nil { - encPanic(err) - } - enc.hasWritten = true -} - -func (enc *Encoder) indentStr(key Key) string { - return strings.Repeat(enc.Indent, len(key)-1) -} - -func encPanic(err error) { - panic(tomlEncodeError{err}) -} - -func eindirect(v reflect.Value) reflect.Value { - switch v.Kind() { - case reflect.Ptr, reflect.Interface: - return eindirect(v.Elem()) - default: - return v - } -} - -func isNil(rv reflect.Value) bool { - switch rv.Kind() { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return rv.IsNil() - default: - return false - } -} - -func panicIfInvalidKey(key Key) { - for _, k := range key { - if len(k) == 0 { - encPanic(e("Key '%s' is not a valid table name. Key names "+ - "cannot be empty.", key.maybeQuotedAll())) - } - } -} - -func isValidKeyName(s string) bool { - return len(s) != 0 -} diff --git a/vendor/github.com/BurntSushi/toml/encoding_types.go b/vendor/github.com/BurntSushi/toml/encoding_types.go deleted file mode 100644 index d36e1dd60..000000000 --- a/vendor/github.com/BurntSushi/toml/encoding_types.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build go1.2 - -package toml - -// In order to support Go 1.1, we define our own TextMarshaler and -// TextUnmarshaler types. For Go 1.2+, we just alias them with the -// standard library interfaces. - -import ( - "encoding" -) - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler encoding.TextMarshaler - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler encoding.TextUnmarshaler diff --git a/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go b/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go deleted file mode 100644 index e8d503d04..000000000 --- a/vendor/github.com/BurntSushi/toml/encoding_types_1.1.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build !go1.2 - -package toml - -// These interfaces were introduced in Go 1.2, so we add them manually when -// compiling for Go 1.1. - -// TextMarshaler is a synonym for encoding.TextMarshaler. It is defined here -// so that Go 1.1 can be supported. -type TextMarshaler interface { - MarshalText() (text []byte, err error) -} - -// TextUnmarshaler is a synonym for encoding.TextUnmarshaler. It is defined -// here so that Go 1.1 can be supported. -type TextUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/vendor/github.com/BurntSushi/toml/lex.go b/vendor/github.com/BurntSushi/toml/lex.go deleted file mode 100644 index e0a742a88..000000000 --- a/vendor/github.com/BurntSushi/toml/lex.go +++ /dev/null @@ -1,953 +0,0 @@ -package toml - -import ( - "fmt" - "strings" - "unicode" - "unicode/utf8" -) - -type itemType int - -const ( - itemError itemType = iota - itemNIL // used in the parser to indicate no type - itemEOF - itemText - itemString - itemRawString - itemMultilineString - itemRawMultilineString - itemBool - itemInteger - itemFloat - itemDatetime - itemArray // the start of an array - itemArrayEnd - itemTableStart - itemTableEnd - itemArrayTableStart - itemArrayTableEnd - itemKeyStart - itemCommentStart - itemInlineTableStart - itemInlineTableEnd -) - -const ( - eof = 0 - comma = ',' - tableStart = '[' - tableEnd = ']' - arrayTableStart = '[' - arrayTableEnd = ']' - tableSep = '.' - keySep = '=' - arrayStart = '[' - arrayEnd = ']' - commentStart = '#' - stringStart = '"' - stringEnd = '"' - rawStringStart = '\'' - rawStringEnd = '\'' - inlineTableStart = '{' - inlineTableEnd = '}' -) - -type stateFn func(lx *lexer) stateFn - -type lexer struct { - input string - start int - pos int - line int - state stateFn - items chan item - - // Allow for backing up up to three runes. - // This is necessary because TOML contains 3-rune tokens (""" and '''). - prevWidths [3]int - nprev int // how many of prevWidths are in use - // If we emit an eof, we can still back up, but it is not OK to call - // next again. - atEOF bool - - // A stack of state functions used to maintain context. - // The idea is to reuse parts of the state machine in various places. - // For example, values can appear at the top level or within arbitrarily - // nested arrays. The last state on the stack is used after a value has - // been lexed. Similarly for comments. - stack []stateFn -} - -type item struct { - typ itemType - val string - line int -} - -func (lx *lexer) nextItem() item { - for { - select { - case item := <-lx.items: - return item - default: - lx.state = lx.state(lx) - } - } -} - -func lex(input string) *lexer { - lx := &lexer{ - input: input, - state: lexTop, - line: 1, - items: make(chan item, 10), - stack: make([]stateFn, 0, 10), - } - return lx -} - -func (lx *lexer) push(state stateFn) { - lx.stack = append(lx.stack, state) -} - -func (lx *lexer) pop() stateFn { - if len(lx.stack) == 0 { - return lx.errorf("BUG in lexer: no states to pop") - } - last := lx.stack[len(lx.stack)-1] - lx.stack = lx.stack[0 : len(lx.stack)-1] - return last -} - -func (lx *lexer) current() string { - return lx.input[lx.start:lx.pos] -} - -func (lx *lexer) emit(typ itemType) { - lx.items <- item{typ, lx.current(), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) emitTrim(typ itemType) { - lx.items <- item{typ, strings.TrimSpace(lx.current()), lx.line} - lx.start = lx.pos -} - -func (lx *lexer) next() (r rune) { - if lx.atEOF { - panic("next called after EOF") - } - if lx.pos >= len(lx.input) { - lx.atEOF = true - return eof - } - - if lx.input[lx.pos] == '\n' { - lx.line++ - } - lx.prevWidths[2] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[0] - if lx.nprev < 3 { - lx.nprev++ - } - r, w := utf8.DecodeRuneInString(lx.input[lx.pos:]) - lx.prevWidths[0] = w - lx.pos += w - return r -} - -// ignore skips over the pending input before this point. -func (lx *lexer) ignore() { - lx.start = lx.pos -} - -// backup steps back one rune. Can be called only twice between calls to next. -func (lx *lexer) backup() { - if lx.atEOF { - lx.atEOF = false - return - } - if lx.nprev < 1 { - panic("backed up too far") - } - w := lx.prevWidths[0] - lx.prevWidths[0] = lx.prevWidths[1] - lx.prevWidths[1] = lx.prevWidths[2] - lx.nprev-- - lx.pos -= w - if lx.pos < len(lx.input) && lx.input[lx.pos] == '\n' { - lx.line-- - } -} - -// accept consumes the next rune if it's equal to `valid`. -func (lx *lexer) accept(valid rune) bool { - if lx.next() == valid { - return true - } - lx.backup() - return false -} - -// peek returns but does not consume the next rune in the input. -func (lx *lexer) peek() rune { - r := lx.next() - lx.backup() - return r -} - -// skip ignores all input that matches the given predicate. -func (lx *lexer) skip(pred func(rune) bool) { - for { - r := lx.next() - if pred(r) { - continue - } - lx.backup() - lx.ignore() - return - } -} - -// errorf stops all lexing by emitting an error and returning `nil`. -// Note that any value that is a character is escaped if it's a special -// character (newlines, tabs, etc.). -func (lx *lexer) errorf(format string, values ...interface{}) stateFn { - lx.items <- item{ - itemError, - fmt.Sprintf(format, values...), - lx.line, - } - return nil -} - -// lexTop consumes elements at the top level of TOML data. -func lexTop(lx *lexer) stateFn { - r := lx.next() - if isWhitespace(r) || isNL(r) { - return lexSkip(lx, lexTop) - } - switch r { - case commentStart: - lx.push(lexTop) - return lexCommentStart - case tableStart: - return lexTableStart - case eof: - if lx.pos > lx.start { - return lx.errorf("unexpected EOF") - } - lx.emit(itemEOF) - return nil - } - - // At this point, the only valid item can be a key, so we back up - // and let the key lexer do the rest. - lx.backup() - lx.push(lexTopEnd) - return lexKeyStart -} - -// lexTopEnd is entered whenever a top-level item has been consumed. (A value -// or a table.) It must see only whitespace, and will turn back to lexTop -// upon a newline. If it sees EOF, it will quit the lexer successfully. -func lexTopEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case r == commentStart: - // a comment will read to a newline for us. - lx.push(lexTop) - return lexCommentStart - case isWhitespace(r): - return lexTopEnd - case isNL(r): - lx.ignore() - return lexTop - case r == eof: - lx.emit(itemEOF) - return nil - } - return lx.errorf("expected a top-level item to end with a newline, "+ - "comment, or EOF, but got %q instead", r) -} - -// lexTable lexes the beginning of a table. Namely, it makes sure that -// it starts with a character other than '.' and ']'. -// It assumes that '[' has already been consumed. -// It also handles the case that this is an item in an array of tables. -// e.g., '[[name]]'. -func lexTableStart(lx *lexer) stateFn { - if lx.peek() == arrayTableStart { - lx.next() - lx.emit(itemArrayTableStart) - lx.push(lexArrayTableEnd) - } else { - lx.emit(itemTableStart) - lx.push(lexTableEnd) - } - return lexTableNameStart -} - -func lexTableEnd(lx *lexer) stateFn { - lx.emit(itemTableEnd) - return lexTopEnd -} - -func lexArrayTableEnd(lx *lexer) stateFn { - if r := lx.next(); r != arrayTableEnd { - return lx.errorf("expected end of table array name delimiter %q, "+ - "but got %q instead", arrayTableEnd, r) - } - lx.emit(itemArrayTableEnd) - return lexTopEnd -} - -func lexTableNameStart(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.peek(); { - case r == tableEnd || r == eof: - return lx.errorf("unexpected end of table name " + - "(table names cannot be empty)") - case r == tableSep: - return lx.errorf("unexpected table separator " + - "(table names cannot be empty)") - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.push(lexTableNameEnd) - return lexValue // reuse string lexing - default: - return lexBareTableName - } -} - -// lexBareTableName lexes the name of a table. It assumes that at least one -// valid character for the table has already been read. -func lexBareTableName(lx *lexer) stateFn { - r := lx.next() - if isBareKeyChar(r) { - return lexBareTableName - } - lx.backup() - lx.emit(itemText) - return lexTableNameEnd -} - -// lexTableNameEnd reads the end of a piece of a table name, optionally -// consuming whitespace. -func lexTableNameEnd(lx *lexer) stateFn { - lx.skip(isWhitespace) - switch r := lx.next(); { - case isWhitespace(r): - return lexTableNameEnd - case r == tableSep: - lx.ignore() - return lexTableNameStart - case r == tableEnd: - return lx.pop() - default: - return lx.errorf("expected '.' or ']' to end table name, "+ - "but got %q instead", r) - } -} - -// lexKeyStart consumes a key name up until the first non-whitespace character. -// lexKeyStart will ignore whitespace. -func lexKeyStart(lx *lexer) stateFn { - r := lx.peek() - switch { - case r == keySep: - return lx.errorf("unexpected key separator %q", keySep) - case isWhitespace(r) || isNL(r): - lx.next() - return lexSkip(lx, lexKeyStart) - case r == stringStart || r == rawStringStart: - lx.ignore() - lx.emit(itemKeyStart) - lx.push(lexKeyEnd) - return lexValue // reuse string lexing - default: - lx.ignore() - lx.emit(itemKeyStart) - return lexBareKey - } -} - -// lexBareKey consumes the text of a bare key. Assumes that the first character -// (which is not whitespace) has not yet been consumed. -func lexBareKey(lx *lexer) stateFn { - switch r := lx.next(); { - case isBareKeyChar(r): - return lexBareKey - case isWhitespace(r): - lx.backup() - lx.emit(itemText) - return lexKeyEnd - case r == keySep: - lx.backup() - lx.emit(itemText) - return lexKeyEnd - default: - return lx.errorf("bare keys cannot contain %q", r) - } -} - -// lexKeyEnd consumes the end of a key and trims whitespace (up to the key -// separator). -func lexKeyEnd(lx *lexer) stateFn { - switch r := lx.next(); { - case r == keySep: - return lexSkip(lx, lexValue) - case isWhitespace(r): - return lexSkip(lx, lexKeyEnd) - default: - return lx.errorf("expected key separator %q, but got %q instead", - keySep, r) - } -} - -// lexValue starts the consumption of a value anywhere a value is expected. -// lexValue will ignore whitespace. -// After a value is lexed, the last state on the next is popped and returned. -func lexValue(lx *lexer) stateFn { - // We allow whitespace to precede a value, but NOT newlines. - // In array syntax, the array states are responsible for ignoring newlines. - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexValue) - case isDigit(r): - lx.backup() // avoid an extra state and use the same as above - return lexNumberOrDateStart - } - switch r { - case arrayStart: - lx.ignore() - lx.emit(itemArray) - return lexArrayValue - case inlineTableStart: - lx.ignore() - lx.emit(itemInlineTableStart) - return lexInlineTableValue - case stringStart: - if lx.accept(stringStart) { - if lx.accept(stringStart) { - lx.ignore() // Ignore """ - return lexMultilineString - } - lx.backup() - } - lx.ignore() // ignore the '"' - return lexString - case rawStringStart: - if lx.accept(rawStringStart) { - if lx.accept(rawStringStart) { - lx.ignore() // Ignore """ - return lexMultilineRawString - } - lx.backup() - } - lx.ignore() // ignore the "'" - return lexRawString - case '+', '-': - return lexNumberStart - case '.': // special error case, be kind to users - return lx.errorf("floats must start with a digit, not '.'") - } - if unicode.IsLetter(r) { - // Be permissive here; lexBool will give a nice error if the - // user wrote something like - // x = foo - // (i.e. not 'true' or 'false' but is something else word-like.) - lx.backup() - return lexBool - } - return lx.errorf("expected value but found %q instead", r) -} - -// lexArrayValue consumes one value in an array. It assumes that '[' or ',' -// have already been consumed. All whitespace and newlines are ignored. -func lexArrayValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValue) - case r == commentStart: - lx.push(lexArrayValue) - return lexCommentStart - case r == comma: - return lx.errorf("unexpected comma") - case r == arrayEnd: - // NOTE(caleb): The spec isn't clear about whether you can have - // a trailing comma or not, so we'll allow it. - return lexArrayEnd - } - - lx.backup() - lx.push(lexArrayValueEnd) - return lexValue -} - -// lexArrayValueEnd consumes everything between the end of an array value and -// the next value (or the end of the array): it ignores whitespace and newlines -// and expects either a ',' or a ']'. -func lexArrayValueEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r) || isNL(r): - return lexSkip(lx, lexArrayValueEnd) - case r == commentStart: - lx.push(lexArrayValueEnd) - return lexCommentStart - case r == comma: - lx.ignore() - return lexArrayValue // move on to the next value - case r == arrayEnd: - return lexArrayEnd - } - return lx.errorf( - "expected a comma or array terminator %q, but got %q instead", - arrayEnd, r, - ) -} - -// lexArrayEnd finishes the lexing of an array. -// It assumes that a ']' has just been consumed. -func lexArrayEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemArrayEnd) - return lx.pop() -} - -// lexInlineTableValue consumes one key/value pair in an inline table. -// It assumes that '{' or ',' have already been consumed. Whitespace is ignored. -func lexInlineTableValue(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValue) - case isNL(r): - return lx.errorf("newlines not allowed within inline tables") - case r == commentStart: - lx.push(lexInlineTableValue) - return lexCommentStart - case r == comma: - return lx.errorf("unexpected comma") - case r == inlineTableEnd: - return lexInlineTableEnd - } - lx.backup() - lx.push(lexInlineTableValueEnd) - return lexKeyStart -} - -// lexInlineTableValueEnd consumes everything between the end of an inline table -// key/value pair and the next pair (or the end of the table): -// it ignores whitespace and expects either a ',' or a '}'. -func lexInlineTableValueEnd(lx *lexer) stateFn { - r := lx.next() - switch { - case isWhitespace(r): - return lexSkip(lx, lexInlineTableValueEnd) - case isNL(r): - return lx.errorf("newlines not allowed within inline tables") - case r == commentStart: - lx.push(lexInlineTableValueEnd) - return lexCommentStart - case r == comma: - lx.ignore() - return lexInlineTableValue - case r == inlineTableEnd: - return lexInlineTableEnd - } - return lx.errorf("expected a comma or an inline table terminator %q, "+ - "but got %q instead", inlineTableEnd, r) -} - -// lexInlineTableEnd finishes the lexing of an inline table. -// It assumes that a '}' has just been consumed. -func lexInlineTableEnd(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemInlineTableEnd) - return lx.pop() -} - -// lexString consumes the inner contents of a string. It assumes that the -// beginning '"' has already been consumed and ignored. -func lexString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == eof: - return lx.errorf("unexpected EOF") - case isNL(r): - return lx.errorf("strings cannot contain newlines") - case r == '\\': - lx.push(lexString) - return lexStringEscape - case r == stringEnd: - lx.backup() - lx.emit(itemString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexString -} - -// lexMultilineString consumes the inner contents of a string. It assumes that -// the beginning '"""' has already been consumed and ignored. -func lexMultilineString(lx *lexer) stateFn { - switch lx.next() { - case eof: - return lx.errorf("unexpected EOF") - case '\\': - return lexMultilineStringEscape - case stringEnd: - if lx.accept(stringEnd) { - if lx.accept(stringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineString -} - -// lexRawString consumes a raw string. Nothing can be escaped in such a string. -// It assumes that the beginning "'" has already been consumed and ignored. -func lexRawString(lx *lexer) stateFn { - r := lx.next() - switch { - case r == eof: - return lx.errorf("unexpected EOF") - case isNL(r): - return lx.errorf("strings cannot contain newlines") - case r == rawStringEnd: - lx.backup() - lx.emit(itemRawString) - lx.next() - lx.ignore() - return lx.pop() - } - return lexRawString -} - -// lexMultilineRawString consumes a raw string. Nothing can be escaped in such -// a string. It assumes that the beginning "'''" has already been consumed and -// ignored. -func lexMultilineRawString(lx *lexer) stateFn { - switch lx.next() { - case eof: - return lx.errorf("unexpected EOF") - case rawStringEnd: - if lx.accept(rawStringEnd) { - if lx.accept(rawStringEnd) { - lx.backup() - lx.backup() - lx.backup() - lx.emit(itemRawMultilineString) - lx.next() - lx.next() - lx.next() - lx.ignore() - return lx.pop() - } - lx.backup() - } - } - return lexMultilineRawString -} - -// lexMultilineStringEscape consumes an escaped character. It assumes that the -// preceding '\\' has already been consumed. -func lexMultilineStringEscape(lx *lexer) stateFn { - // Handle the special case first: - if isNL(lx.next()) { - return lexMultilineString - } - lx.backup() - lx.push(lexMultilineString) - return lexStringEscape(lx) -} - -func lexStringEscape(lx *lexer) stateFn { - r := lx.next() - switch r { - case 'b': - fallthrough - case 't': - fallthrough - case 'n': - fallthrough - case 'f': - fallthrough - case 'r': - fallthrough - case '"': - fallthrough - case '\\': - return lx.pop() - case 'u': - return lexShortUnicodeEscape - case 'U': - return lexLongUnicodeEscape - } - return lx.errorf("invalid escape character %q; only the following "+ - "escape characters are allowed: "+ - `\b, \t, \n, \f, \r, \", \\, \uXXXX, and \UXXXXXXXX`, r) -} - -func lexShortUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 4; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf(`expected four hexadecimal digits after '\u', `+ - "but got %q instead", lx.current()) - } - } - return lx.pop() -} - -func lexLongUnicodeEscape(lx *lexer) stateFn { - var r rune - for i := 0; i < 8; i++ { - r = lx.next() - if !isHexadecimal(r) { - return lx.errorf(`expected eight hexadecimal digits after '\U', `+ - "but got %q instead", lx.current()) - } - } - return lx.pop() -} - -// lexNumberOrDateStart consumes either an integer, a float, or datetime. -func lexNumberOrDateStart(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '_': - return lexNumber - case 'e', 'E': - return lexFloat - case '.': - return lx.errorf("floats must start with a digit, not '.'") - } - return lx.errorf("expected a digit but got %q", r) -} - -// lexNumberOrDate consumes either an integer, float or datetime. -func lexNumberOrDate(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumberOrDate - } - switch r { - case '-': - return lexDatetime - case '_': - return lexNumber - case '.', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexDatetime consumes a Datetime, to a first approximation. -// The parser validates that it matches one of the accepted formats. -func lexDatetime(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexDatetime - } - switch r { - case '-', 'T', ':', '.', 'Z', '+': - return lexDatetime - } - - lx.backup() - lx.emit(itemDatetime) - return lx.pop() -} - -// lexNumberStart consumes either an integer or a float. It assumes that a sign -// has already been read, but that *no* digits have been consumed. -// lexNumberStart will move to the appropriate integer or float states. -func lexNumberStart(lx *lexer) stateFn { - // We MUST see a digit. Even floats have to start with a digit. - r := lx.next() - if !isDigit(r) { - if r == '.' { - return lx.errorf("floats must start with a digit, not '.'") - } - return lx.errorf("expected a digit but got %q", r) - } - return lexNumber -} - -// lexNumber consumes an integer or a float after seeing the first digit. -func lexNumber(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexNumber - } - switch r { - case '_': - return lexNumber - case '.', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemInteger) - return lx.pop() -} - -// lexFloat consumes the elements of a float. It allows any sequence of -// float-like characters, so floats emitted by the lexer are only a first -// approximation and must be validated by the parser. -func lexFloat(lx *lexer) stateFn { - r := lx.next() - if isDigit(r) { - return lexFloat - } - switch r { - case '_', '.', '-', '+', 'e', 'E': - return lexFloat - } - - lx.backup() - lx.emit(itemFloat) - return lx.pop() -} - -// lexBool consumes a bool string: 'true' or 'false. -func lexBool(lx *lexer) stateFn { - var rs []rune - for { - r := lx.next() - if !unicode.IsLetter(r) { - lx.backup() - break - } - rs = append(rs, r) - } - s := string(rs) - switch s { - case "true", "false": - lx.emit(itemBool) - return lx.pop() - } - return lx.errorf("expected value but found %q instead", s) -} - -// lexCommentStart begins the lexing of a comment. It will emit -// itemCommentStart and consume no characters, passing control to lexComment. -func lexCommentStart(lx *lexer) stateFn { - lx.ignore() - lx.emit(itemCommentStart) - return lexComment -} - -// lexComment lexes an entire comment. It assumes that '#' has been consumed. -// It will consume *up to* the first newline character, and pass control -// back to the last state on the stack. -func lexComment(lx *lexer) stateFn { - r := lx.peek() - if isNL(r) || r == eof { - lx.emit(itemText) - return lx.pop() - } - lx.next() - return lexComment -} - -// lexSkip ignores all slurped input and moves on to the next state. -func lexSkip(lx *lexer, nextState stateFn) stateFn { - return func(lx *lexer) stateFn { - lx.ignore() - return nextState - } -} - -// isWhitespace returns true if `r` is a whitespace character according -// to the spec. -func isWhitespace(r rune) bool { - return r == '\t' || r == ' ' -} - -func isNL(r rune) bool { - return r == '\n' || r == '\r' -} - -func isDigit(r rune) bool { - return r >= '0' && r <= '9' -} - -func isHexadecimal(r rune) bool { - return (r >= '0' && r <= '9') || - (r >= 'a' && r <= 'f') || - (r >= 'A' && r <= 'F') -} - -func isBareKeyChar(r rune) bool { - return (r >= 'A' && r <= 'Z') || - (r >= 'a' && r <= 'z') || - (r >= '0' && r <= '9') || - r == '_' || - r == '-' -} - -func (itype itemType) String() string { - switch itype { - case itemError: - return "Error" - case itemNIL: - return "NIL" - case itemEOF: - return "EOF" - case itemText: - return "Text" - case itemString, itemRawString, itemMultilineString, itemRawMultilineString: - return "String" - case itemBool: - return "Bool" - case itemInteger: - return "Integer" - case itemFloat: - return "Float" - case itemDatetime: - return "DateTime" - case itemTableStart: - return "TableStart" - case itemTableEnd: - return "TableEnd" - case itemKeyStart: - return "KeyStart" - case itemArray: - return "Array" - case itemArrayEnd: - return "ArrayEnd" - case itemCommentStart: - return "CommentStart" - } - panic(fmt.Sprintf("BUG: Unknown type '%d'.", int(itype))) -} - -func (item item) String() string { - return fmt.Sprintf("(%s, %s)", item.typ.String(), item.val) -} diff --git a/vendor/github.com/BurntSushi/toml/parse.go b/vendor/github.com/BurntSushi/toml/parse.go deleted file mode 100644 index 50869ef92..000000000 --- a/vendor/github.com/BurntSushi/toml/parse.go +++ /dev/null @@ -1,592 +0,0 @@ -package toml - -import ( - "fmt" - "strconv" - "strings" - "time" - "unicode" - "unicode/utf8" -) - -type parser struct { - mapping map[string]interface{} - types map[string]tomlType - lx *lexer - - // A list of keys in the order that they appear in the TOML data. - ordered []Key - - // the full key for the current hash in scope - context Key - - // the base key name for everything except hashes - currentKey string - - // rough approximation of line number - approxLine int - - // A map of 'key.group.names' to whether they were created implicitly. - implicits map[string]bool -} - -type parseError string - -func (pe parseError) Error() string { - return string(pe) -} - -func parse(data string) (p *parser, err error) { - defer func() { - if r := recover(); r != nil { - var ok bool - if err, ok = r.(parseError); ok { - return - } - panic(r) - } - }() - - p = &parser{ - mapping: make(map[string]interface{}), - types: make(map[string]tomlType), - lx: lex(data), - ordered: make([]Key, 0), - implicits: make(map[string]bool), - } - for { - item := p.next() - if item.typ == itemEOF { - break - } - p.topLevel(item) - } - - return p, nil -} - -func (p *parser) panicf(format string, v ...interface{}) { - msg := fmt.Sprintf("Near line %d (last key parsed '%s'): %s", - p.approxLine, p.current(), fmt.Sprintf(format, v...)) - panic(parseError(msg)) -} - -func (p *parser) next() item { - it := p.lx.nextItem() - if it.typ == itemError { - p.panicf("%s", it.val) - } - return it -} - -func (p *parser) bug(format string, v ...interface{}) { - panic(fmt.Sprintf("BUG: "+format+"\n\n", v...)) -} - -func (p *parser) expect(typ itemType) item { - it := p.next() - p.assertEqual(typ, it.typ) - return it -} - -func (p *parser) assertEqual(expected, got itemType) { - if expected != got { - p.bug("Expected '%s' but got '%s'.", expected, got) - } -} - -func (p *parser) topLevel(item item) { - switch item.typ { - case itemCommentStart: - p.approxLine = item.line - p.expect(itemText) - case itemTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemTableEnd, kg.typ) - - p.establishContext(key, false) - p.setType("", tomlHash) - p.ordered = append(p.ordered, key) - case itemArrayTableStart: - kg := p.next() - p.approxLine = kg.line - - var key Key - for ; kg.typ != itemArrayTableEnd && kg.typ != itemEOF; kg = p.next() { - key = append(key, p.keyString(kg)) - } - p.assertEqual(itemArrayTableEnd, kg.typ) - - p.establishContext(key, true) - p.setType("", tomlArrayHash) - p.ordered = append(p.ordered, key) - case itemKeyStart: - kname := p.next() - p.approxLine = kname.line - p.currentKey = p.keyString(kname) - - val, typ := p.value(p.next()) - p.setValue(p.currentKey, val) - p.setType(p.currentKey, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - p.currentKey = "" - default: - p.bug("Unexpected type at top level: %s", item.typ) - } -} - -// Gets a string for a key (or part of a key in a table name). -func (p *parser) keyString(it item) string { - switch it.typ { - case itemText: - return it.val - case itemString, itemMultilineString, - itemRawString, itemRawMultilineString: - s, _ := p.value(it) - return s.(string) - default: - p.bug("Unexpected key type: %s", it.typ) - panic("unreachable") - } -} - -// value translates an expected value from the lexer into a Go value wrapped -// as an empty interface. -func (p *parser) value(it item) (interface{}, tomlType) { - switch it.typ { - case itemString: - return p.replaceEscapes(it.val), p.typeOfPrimitive(it) - case itemMultilineString: - trimmed := stripFirstNewline(stripEscapedWhitespace(it.val)) - return p.replaceEscapes(trimmed), p.typeOfPrimitive(it) - case itemRawString: - return it.val, p.typeOfPrimitive(it) - case itemRawMultilineString: - return stripFirstNewline(it.val), p.typeOfPrimitive(it) - case itemBool: - switch it.val { - case "true": - return true, p.typeOfPrimitive(it) - case "false": - return false, p.typeOfPrimitive(it) - } - p.bug("Expected boolean value, but got '%s'.", it.val) - case itemInteger: - if !numUnderscoresOK(it.val) { - p.panicf("Invalid integer %q: underscores must be surrounded by digits", - it.val) - } - val := strings.Replace(it.val, "_", "", -1) - num, err := strconv.ParseInt(val, 10, 64) - if err != nil { - // Distinguish integer values. Normally, it'd be a bug if the lexer - // provides an invalid integer, but it's possible that the number is - // out of range of valid values (which the lexer cannot determine). - // So mark the former as a bug but the latter as a legitimate user - // error. - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Integer '%s' is out of the range of 64-bit "+ - "signed integers.", it.val) - } else { - p.bug("Expected integer value, but got '%s'.", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemFloat: - parts := strings.FieldsFunc(it.val, func(r rune) bool { - switch r { - case '.', 'e', 'E': - return true - } - return false - }) - for _, part := range parts { - if !numUnderscoresOK(part) { - p.panicf("Invalid float %q: underscores must be "+ - "surrounded by digits", it.val) - } - } - if !numPeriodsOK(it.val) { - // As a special case, numbers like '123.' or '1.e2', - // which are valid as far as Go/strconv are concerned, - // must be rejected because TOML says that a fractional - // part consists of '.' followed by 1+ digits. - p.panicf("Invalid float %q: '.' must be followed "+ - "by one or more digits", it.val) - } - val := strings.Replace(it.val, "_", "", -1) - num, err := strconv.ParseFloat(val, 64) - if err != nil { - if e, ok := err.(*strconv.NumError); ok && - e.Err == strconv.ErrRange { - - p.panicf("Float '%s' is out of the range of 64-bit "+ - "IEEE-754 floating-point numbers.", it.val) - } else { - p.panicf("Invalid float value: %q", it.val) - } - } - return num, p.typeOfPrimitive(it) - case itemDatetime: - var t time.Time - var ok bool - var err error - for _, format := range []string{ - "2006-01-02T15:04:05Z07:00", - "2006-01-02T15:04:05", - "2006-01-02", - } { - t, err = time.ParseInLocation(format, it.val, time.Local) - if err == nil { - ok = true - break - } - } - if !ok { - p.panicf("Invalid TOML Datetime: %q.", it.val) - } - return t, p.typeOfPrimitive(it) - case itemArray: - array := make([]interface{}, 0) - types := make([]tomlType, 0) - - for it = p.next(); it.typ != itemArrayEnd; it = p.next() { - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - val, typ := p.value(it) - array = append(array, val) - types = append(types, typ) - } - return array, p.typeOfArray(types) - case itemInlineTableStart: - var ( - hash = make(map[string]interface{}) - outerContext = p.context - outerKey = p.currentKey - ) - - p.context = append(p.context, p.currentKey) - p.currentKey = "" - for it := p.next(); it.typ != itemInlineTableEnd; it = p.next() { - if it.typ != itemKeyStart { - p.bug("Expected key start but instead found %q, around line %d", - it.val, p.approxLine) - } - if it.typ == itemCommentStart { - p.expect(itemText) - continue - } - - // retrieve key - k := p.next() - p.approxLine = k.line - kname := p.keyString(k) - - // retrieve value - p.currentKey = kname - val, typ := p.value(p.next()) - // make sure we keep metadata up to date - p.setType(kname, typ) - p.ordered = append(p.ordered, p.context.add(p.currentKey)) - hash[kname] = val - } - p.context = outerContext - p.currentKey = outerKey - return hash, tomlHash - } - p.bug("Unexpected value type: %s", it.typ) - panic("unreachable") -} - -// numUnderscoresOK checks whether each underscore in s is surrounded by -// characters that are not underscores. -func numUnderscoresOK(s string) bool { - accept := false - for _, r := range s { - if r == '_' { - if !accept { - return false - } - accept = false - continue - } - accept = true - } - return accept -} - -// numPeriodsOK checks whether every period in s is followed by a digit. -func numPeriodsOK(s string) bool { - period := false - for _, r := range s { - if period && !isDigit(r) { - return false - } - period = r == '.' - } - return !period -} - -// establishContext sets the current context of the parser, -// where the context is either a hash or an array of hashes. Which one is -// set depends on the value of the `array` parameter. -// -// Establishing the context also makes sure that the key isn't a duplicate, and -// will create implicit hashes automatically. -func (p *parser) establishContext(key Key, array bool) { - var ok bool - - // Always start at the top level and drill down for our context. - hashContext := p.mapping - keyContext := make(Key, 0) - - // We only need implicit hashes for key[0:-1] - for _, k := range key[0 : len(key)-1] { - _, ok = hashContext[k] - keyContext = append(keyContext, k) - - // No key? Make an implicit hash and move on. - if !ok { - p.addImplicit(keyContext) - hashContext[k] = make(map[string]interface{}) - } - - // If the hash context is actually an array of tables, then set - // the hash context to the last element in that array. - // - // Otherwise, it better be a table, since this MUST be a key group (by - // virtue of it not being the last element in a key). - switch t := hashContext[k].(type) { - case []map[string]interface{}: - hashContext = t[len(t)-1] - case map[string]interface{}: - hashContext = t - default: - p.panicf("Key '%s' was already created as a hash.", keyContext) - } - } - - p.context = keyContext - if array { - // If this is the first element for this array, then allocate a new - // list of tables for it. - k := key[len(key)-1] - if _, ok := hashContext[k]; !ok { - hashContext[k] = make([]map[string]interface{}, 0, 5) - } - - // Add a new table. But make sure the key hasn't already been used - // for something else. - if hash, ok := hashContext[k].([]map[string]interface{}); ok { - hashContext[k] = append(hash, make(map[string]interface{})) - } else { - p.panicf("Key '%s' was already created and cannot be used as "+ - "an array.", keyContext) - } - } else { - p.setValue(key[len(key)-1], make(map[string]interface{})) - } - p.context = append(p.context, key[len(key)-1]) -} - -// setValue sets the given key to the given value in the current context. -// It will make sure that the key hasn't already been defined, account for -// implicit key groups. -func (p *parser) setValue(key string, value interface{}) { - var tmpHash interface{} - var ok bool - - hash := p.mapping - keyContext := make(Key, 0) - for _, k := range p.context { - keyContext = append(keyContext, k) - if tmpHash, ok = hash[k]; !ok { - p.bug("Context for key '%s' has not been established.", keyContext) - } - switch t := tmpHash.(type) { - case []map[string]interface{}: - // The context is a table of hashes. Pick the most recent table - // defined as the current hash. - hash = t[len(t)-1] - case map[string]interface{}: - hash = t - default: - p.bug("Expected hash to have type 'map[string]interface{}', but "+ - "it has '%T' instead.", tmpHash) - } - } - keyContext = append(keyContext, key) - - if _, ok := hash[key]; ok { - // Typically, if the given key has already been set, then we have - // to raise an error since duplicate keys are disallowed. However, - // it's possible that a key was previously defined implicitly. In this - // case, it is allowed to be redefined concretely. (See the - // `tests/valid/implicit-and-explicit-after.toml` test in `toml-test`.) - // - // But we have to make sure to stop marking it as an implicit. (So that - // another redefinition provokes an error.) - // - // Note that since it has already been defined (as a hash), we don't - // want to overwrite it. So our business is done. - if p.isImplicit(keyContext) { - p.removeImplicit(keyContext) - return - } - - // Otherwise, we have a concrete key trying to override a previous - // key, which is *always* wrong. - p.panicf("Key '%s' has already been defined.", keyContext) - } - hash[key] = value -} - -// setType sets the type of a particular value at a given key. -// It should be called immediately AFTER setValue. -// -// Note that if `key` is empty, then the type given will be applied to the -// current context (which is either a table or an array of tables). -func (p *parser) setType(key string, typ tomlType) { - keyContext := make(Key, 0, len(p.context)+1) - for _, k := range p.context { - keyContext = append(keyContext, k) - } - if len(key) > 0 { // allow type setting for hashes - keyContext = append(keyContext, key) - } - p.types[keyContext.String()] = typ -} - -// addImplicit sets the given Key as having been created implicitly. -func (p *parser) addImplicit(key Key) { - p.implicits[key.String()] = true -} - -// removeImplicit stops tagging the given key as having been implicitly -// created. -func (p *parser) removeImplicit(key Key) { - p.implicits[key.String()] = false -} - -// isImplicit returns true if the key group pointed to by the key was created -// implicitly. -func (p *parser) isImplicit(key Key) bool { - return p.implicits[key.String()] -} - -// current returns the full key name of the current context. -func (p *parser) current() string { - if len(p.currentKey) == 0 { - return p.context.String() - } - if len(p.context) == 0 { - return p.currentKey - } - return fmt.Sprintf("%s.%s", p.context, p.currentKey) -} - -func stripFirstNewline(s string) string { - if len(s) == 0 || s[0] != '\n' { - return s - } - return s[1:] -} - -func stripEscapedWhitespace(s string) string { - esc := strings.Split(s, "\\\n") - if len(esc) > 1 { - for i := 1; i < len(esc); i++ { - esc[i] = strings.TrimLeftFunc(esc[i], unicode.IsSpace) - } - } - return strings.Join(esc, "") -} - -func (p *parser) replaceEscapes(str string) string { - var replaced []rune - s := []byte(str) - r := 0 - for r < len(s) { - if s[r] != '\\' { - c, size := utf8.DecodeRune(s[r:]) - r += size - replaced = append(replaced, c) - continue - } - r += 1 - if r >= len(s) { - p.bug("Escape sequence at end of string.") - return "" - } - switch s[r] { - default: - p.bug("Expected valid escape code after \\, but got %q.", s[r]) - return "" - case 'b': - replaced = append(replaced, rune(0x0008)) - r += 1 - case 't': - replaced = append(replaced, rune(0x0009)) - r += 1 - case 'n': - replaced = append(replaced, rune(0x000A)) - r += 1 - case 'f': - replaced = append(replaced, rune(0x000C)) - r += 1 - case 'r': - replaced = append(replaced, rune(0x000D)) - r += 1 - case '"': - replaced = append(replaced, rune(0x0022)) - r += 1 - case '\\': - replaced = append(replaced, rune(0x005C)) - r += 1 - case 'u': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+5). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+5]) - replaced = append(replaced, escaped) - r += 5 - case 'U': - // At this point, we know we have a Unicode escape of the form - // `uXXXX` at [r, r+9). (Because the lexer guarantees this - // for us.) - escaped := p.asciiEscapeToUnicode(s[r+1 : r+9]) - replaced = append(replaced, escaped) - r += 9 - } - } - return string(replaced) -} - -func (p *parser) asciiEscapeToUnicode(bs []byte) rune { - s := string(bs) - hex, err := strconv.ParseUint(strings.ToLower(s), 16, 32) - if err != nil { - p.bug("Could not parse '%s' as a hexadecimal number, but the "+ - "lexer claims it's OK: %s", s, err) - } - if !utf8.ValidRune(rune(hex)) { - p.panicf("Escaped character '\\u%s' is not valid UTF-8.", s) - } - return rune(hex) -} - -func isStringType(ty itemType) bool { - return ty == itemString || ty == itemMultilineString || - ty == itemRawString || ty == itemRawMultilineString -} diff --git a/vendor/github.com/BurntSushi/toml/type_check.go b/vendor/github.com/BurntSushi/toml/type_check.go deleted file mode 100644 index c73f8afc1..000000000 --- a/vendor/github.com/BurntSushi/toml/type_check.go +++ /dev/null @@ -1,91 +0,0 @@ -package toml - -// tomlType represents any Go type that corresponds to a TOML type. -// While the first draft of the TOML spec has a simplistic type system that -// probably doesn't need this level of sophistication, we seem to be militating -// toward adding real composite types. -type tomlType interface { - typeString() string -} - -// typeEqual accepts any two types and returns true if they are equal. -func typeEqual(t1, t2 tomlType) bool { - if t1 == nil || t2 == nil { - return false - } - return t1.typeString() == t2.typeString() -} - -func typeIsHash(t tomlType) bool { - return typeEqual(t, tomlHash) || typeEqual(t, tomlArrayHash) -} - -type tomlBaseType string - -func (btype tomlBaseType) typeString() string { - return string(btype) -} - -func (btype tomlBaseType) String() string { - return btype.typeString() -} - -var ( - tomlInteger tomlBaseType = "Integer" - tomlFloat tomlBaseType = "Float" - tomlDatetime tomlBaseType = "Datetime" - tomlString tomlBaseType = "String" - tomlBool tomlBaseType = "Bool" - tomlArray tomlBaseType = "Array" - tomlHash tomlBaseType = "Hash" - tomlArrayHash tomlBaseType = "ArrayHash" -) - -// typeOfPrimitive returns a tomlType of any primitive value in TOML. -// Primitive values are: Integer, Float, Datetime, String and Bool. -// -// Passing a lexer item other than the following will cause a BUG message -// to occur: itemString, itemBool, itemInteger, itemFloat, itemDatetime. -func (p *parser) typeOfPrimitive(lexItem item) tomlType { - switch lexItem.typ { - case itemInteger: - return tomlInteger - case itemFloat: - return tomlFloat - case itemDatetime: - return tomlDatetime - case itemString: - return tomlString - case itemMultilineString: - return tomlString - case itemRawString: - return tomlString - case itemRawMultilineString: - return tomlString - case itemBool: - return tomlBool - } - p.bug("Cannot infer primitive type of lex item '%s'.", lexItem) - panic("unreachable") -} - -// typeOfArray returns a tomlType for an array given a list of types of its -// values. -// -// In the current spec, if an array is homogeneous, then its type is always -// "Array". If the array is not homogeneous, an error is generated. -func (p *parser) typeOfArray(types []tomlType) tomlType { - // Empty arrays are cool. - if len(types) == 0 { - return tomlArray - } - - theType := types[0] - for _, t := range types[1:] { - if !typeEqual(theType, t) { - p.panicf("Array contains values of type '%s' and '%s', but "+ - "arrays must be homogeneous.", theType, t) - } - } - return tomlArray -} diff --git a/vendor/github.com/BurntSushi/toml/type_fields.go b/vendor/github.com/BurntSushi/toml/type_fields.go deleted file mode 100644 index 608997c22..000000000 --- a/vendor/github.com/BurntSushi/toml/type_fields.go +++ /dev/null @@ -1,242 +0,0 @@ -package toml - -// Struct field handling is adapted from code in encoding/json: -// -// 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 Go distribution. - -import ( - "reflect" - "sort" - "sync" -) - -// A field represents a single field found in a struct. -type field struct { - name string // the name of the field (`toml` tag included) - tag bool // whether field has a `toml` tag - index []int // represents the depth of an anonymous field - typ reflect.Type // the type of the field -} - -// byName sorts field by name, breaking ties with depth, -// then breaking ties with "name came from toml tag", then -// breaking ties with index sequence. -type byName []field - -func (x byName) Len() int { return len(x) } - -func (x byName) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byName) Less(i, j int) bool { - if x[i].name != x[j].name { - return x[i].name < x[j].name - } - if len(x[i].index) != len(x[j].index) { - return len(x[i].index) < len(x[j].index) - } - if x[i].tag != x[j].tag { - return x[i].tag - } - return byIndex(x).Less(i, j) -} - -// byIndex sorts field by index sequence. -type byIndex []field - -func (x byIndex) Len() int { return len(x) } - -func (x byIndex) Swap(i, j int) { x[i], x[j] = x[j], x[i] } - -func (x byIndex) Less(i, j int) bool { - for k, xik := range x[i].index { - if k >= len(x[j].index) { - return false - } - if xik != x[j].index[k] { - return xik < x[j].index[k] - } - } - return len(x[i].index) < len(x[j].index) -} - -// typeFields returns a list of fields that TOML should recognize for the given -// type. The algorithm is breadth-first search over the set of structs to -// include - the top struct and then any reachable anonymous structs. -func typeFields(t reflect.Type) []field { - // Anonymous fields to explore at the current level and the next. - current := []field{} - next := []field{{typ: t}} - - // Count of queued names for current level and the next. - count := map[reflect.Type]int{} - nextCount := map[reflect.Type]int{} - - // Types already visited at an earlier level. - visited := map[reflect.Type]bool{} - - // Fields found. - var fields []field - - for len(next) > 0 { - current, next = next, current[:0] - count, nextCount = nextCount, map[reflect.Type]int{} - - for _, f := range current { - if visited[f.typ] { - continue - } - visited[f.typ] = true - - // Scan f.typ for fields to include. - for i := 0; i < f.typ.NumField(); i++ { - sf := f.typ.Field(i) - if sf.PkgPath != "" && !sf.Anonymous { // unexported - continue - } - opts := getOptions(sf.Tag) - if opts.skip { - continue - } - index := make([]int, len(f.index)+1) - copy(index, f.index) - index[len(f.index)] = i - - ft := sf.Type - if ft.Name() == "" && ft.Kind() == reflect.Ptr { - // Follow pointer. - ft = ft.Elem() - } - - // Record found field and index sequence. - if opts.name != "" || !sf.Anonymous || ft.Kind() != reflect.Struct { - tagged := opts.name != "" - name := opts.name - if name == "" { - name = sf.Name - } - fields = append(fields, field{name, tagged, index, ft}) - if count[f.typ] > 1 { - // If there were multiple instances, add a second, - // so that the annihilation code will see a duplicate. - // It only cares about the distinction between 1 or 2, - // so don't bother generating any more copies. - fields = append(fields, fields[len(fields)-1]) - } - continue - } - - // Record new anonymous struct to explore in next round. - nextCount[ft]++ - if nextCount[ft] == 1 { - f := field{name: ft.Name(), index: index, typ: ft} - next = append(next, f) - } - } - } - } - - sort.Sort(byName(fields)) - - // Delete all fields that are hidden by the Go rules for embedded fields, - // except that fields with TOML tags are promoted. - - // The fields are sorted in primary order of name, secondary order - // of field index length. Loop over names; for each name, delete - // hidden fields by choosing the one dominant field that survives. - out := fields[:0] - for advance, i := 0, 0; i < len(fields); i += advance { - // One iteration per name. - // Find the sequence of fields with the name of this first field. - fi := fields[i] - name := fi.name - for advance = 1; i+advance < len(fields); advance++ { - fj := fields[i+advance] - if fj.name != name { - break - } - } - if advance == 1 { // Only one field with this name - out = append(out, fi) - continue - } - dominant, ok := dominantField(fields[i : i+advance]) - if ok { - out = append(out, dominant) - } - } - - fields = out - sort.Sort(byIndex(fields)) - - return fields -} - -// dominantField looks through the fields, all of which are known to -// have the same name, to find the single field that dominates the -// others using Go's embedding rules, modified by the presence of -// TOML tags. If there are multiple top-level fields, the boolean -// will be false: This condition is an error in Go and we skip all -// the fields. -func dominantField(fields []field) (field, bool) { - // The fields are sorted in increasing index-length order. The winner - // must therefore be one with the shortest index length. Drop all - // longer entries, which is easy: just truncate the slice. - length := len(fields[0].index) - tagged := -1 // Index of first tagged field. - for i, f := range fields { - if len(f.index) > length { - fields = fields[:i] - break - } - if f.tag { - if tagged >= 0 { - // Multiple tagged fields at the same level: conflict. - // Return no field. - return field{}, false - } - tagged = i - } - } - if tagged >= 0 { - return fields[tagged], true - } - // All remaining fields have the same length. If there's more than one, - // we have a conflict (two fields named "X" at the same level) and we - // return no field. - if len(fields) > 1 { - return field{}, false - } - return fields[0], true -} - -var fieldCache struct { - sync.RWMutex - m map[reflect.Type][]field -} - -// cachedTypeFields is like typeFields but uses a cache to avoid repeated work. -func cachedTypeFields(t reflect.Type) []field { - fieldCache.RLock() - f := fieldCache.m[t] - fieldCache.RUnlock() - if f != nil { - return f - } - - // Compute fields without lock. - // Might duplicate effort but won't hold other computations back. - f = typeFields(t) - if f == nil { - f = []field{} - } - - fieldCache.Lock() - if fieldCache.m == nil { - fieldCache.m = map[reflect.Type][]field{} - } - fieldCache.m[t] = f - fieldCache.Unlock() - return f -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/LICENSE b/vendor/github.com/ExpediaDotCom/haystack-client-go/LICENSE deleted file mode 100644 index 76cead035..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/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 [2018] Expedia Group. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/ExpediaDotCom/haystack-client-go/dispatcher.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/dispatcher.go deleted file mode 100644 index 8507d065e..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/dispatcher.go +++ /dev/null @@ -1,356 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "fmt" - "os" - "os/signal" - "time" - - "github.com/opentracing/opentracing-go/ext" - "github.com/opentracing/opentracing-go/log" -) - -/*Dispatcher dispatches the span object*/ -type Dispatcher interface { - Name() string - Dispatch(span *_Span) - DispatchProtoSpan(span *Span) - Close() - SetLogger(logger Logger) -} - -/*InMemoryDispatcher implements the Dispatcher interface*/ -type InMemoryDispatcher struct { - spans []*_Span - logger Logger -} - -/*NewInMemoryDispatcher creates a new in memory dispatcher*/ -func NewInMemoryDispatcher() Dispatcher { - return &InMemoryDispatcher{} -} - -/*Name gives the Dispatcher name*/ -func (d *InMemoryDispatcher) Name() string { - return "InMemoryDispatcher" -} - -/*SetLogger sets the logger to use*/ -func (d *InMemoryDispatcher) SetLogger(logger Logger) { - d.logger = logger -} - -/*Dispatch dispatches the span object*/ -func (d *InMemoryDispatcher) Dispatch(span *_Span) { - d.spans = append(d.spans, span) -} - -/*DispatchProtoSpan dispatches proto span object*/ -func (d *InMemoryDispatcher) DispatchProtoSpan(span *Span) { - /* not implemented */ -} - -/*Close down the inMemory dispatcher*/ -func (d *InMemoryDispatcher) Close() { - d.spans = nil -} - -/*FileDispatcher file dispatcher*/ -type FileDispatcher struct { - fileHandle *os.File - logger Logger -} - -/*NewFileDispatcher creates a new file dispatcher*/ -func NewFileDispatcher(filename string) Dispatcher { - fd, err := os.OpenFile(filename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0644) - if err != nil { - panic(err) - } - return &FileDispatcher{ - fileHandle: fd, - } -} - -/*Name gives the Dispatcher name*/ -func (d *FileDispatcher) Name() string { - return "FileDispatcher" -} - -/*SetLogger sets the logger to use*/ -func (d *FileDispatcher) SetLogger(logger Logger) { - d.logger = logger -} - -/*Dispatch dispatches the span object*/ -func (d *FileDispatcher) Dispatch(span *_Span) { - _, err := d.fileHandle.WriteString(span.String() + "\n") - if err != nil { - panic(err) - } -} - -/*DispatchProtoSpan dispatches proto span object*/ -func (d *FileDispatcher) DispatchProtoSpan(span *Span) { - /* not implemented */ -} - -/*Close down the file dispatcher*/ -func (d *FileDispatcher) Close() { - err := d.fileHandle.Close() - if err != nil { - panic(err) - } -} - -/*RemoteDispatcher dispatcher, client can be grpc or http*/ -type RemoteDispatcher struct { - client RemoteClient - timeout time.Duration - logger Logger - spanChannel chan *Span -} - -/*NewHTTPDispatcher creates a new haystack-agent dispatcher*/ -func NewHTTPDispatcher(url string, timeout time.Duration, headers map[string]string, maxQueueLength int) Dispatcher { - dispatcher := &RemoteDispatcher{ - client: NewHTTPClient(url, headers, timeout), - timeout: timeout, - spanChannel: make(chan *Span, maxQueueLength), - } - - go startListener(dispatcher) - return dispatcher -} - -/*NewDefaultHTTPDispatcher creates a new http dispatcher*/ -func NewDefaultHTTPDispatcher() Dispatcher { - return NewHTTPDispatcher("http://haystack-collector/span", 3*time.Second, make(map[string](string)), 1000) -} - -/*NewAgentDispatcher creates a new haystack-agent dispatcher*/ -func NewAgentDispatcher(host string, port int, timeout time.Duration, maxQueueLength int) Dispatcher { - dispatcher := &RemoteDispatcher{ - client: NewGrpcClient(host, port, timeout), - timeout: timeout, - spanChannel: make(chan *Span, maxQueueLength), - } - - go startListener(dispatcher) - return dispatcher -} - -/*NewDefaultAgentDispatcher creates a new haystack-agent dispatcher*/ -func NewDefaultAgentDispatcher() Dispatcher { - return NewAgentDispatcher("haystack-agent", 35000, 3*time.Second, 1000) -} - -func startListener(dispatcher *RemoteDispatcher) { - signals := make(chan os.Signal, 1) - signal.Notify(signals, os.Interrupt, os.Kill) - - for { - select { - case sp := <-dispatcher.spanChannel: - dispatcher.client.Send(sp) - case <-signals: - break - } - } -} - -/*Name gives the Dispatcher name*/ -func (d *RemoteDispatcher) Name() string { - return "RemoteDispatcher" -} - -/*SetLogger sets the logger to use*/ -func (d *RemoteDispatcher) SetLogger(logger Logger) { - d.logger = logger - d.client.SetLogger(logger) -} - -/*Dispatch dispatches the span object*/ -func (d *RemoteDispatcher) Dispatch(span *_Span) { - s := &Span{ - TraceId: span.context.TraceID, - SpanId: span.context.SpanID, - ParentSpanId: span.context.ParentID, - ServiceName: span.ServiceName(), - OperationName: span.OperationName(), - StartTime: span.startTime.UnixNano() / int64(time.Microsecond), - Duration: span.duration.Nanoseconds() / int64(time.Microsecond), - Tags: d.tags(span), - Logs: d.logs(span), - } - d.spanChannel <- s -} - -/*DispatchProtoSpan dispatches the proto span object*/ -func (d *RemoteDispatcher) DispatchProtoSpan(s *Span) { - d.spanChannel <- s -} - -func (d *RemoteDispatcher) logs(span *_Span) []*Log { - var spanLogs []*Log - for _, lg := range span.logs { - spanLogs = append(spanLogs, &Log{ - Timestamp: lg.Timestamp.UnixNano() / int64(time.Microsecond), - Fields: d.logFieldsToTags(lg.Fields), - }) - } - return spanLogs -} - -func (d *RemoteDispatcher) logFieldsToTags(fields []log.Field) []*Tag { - var spanTags []*Tag - for _, field := range fields { - spanTags = append(spanTags, ConvertToProtoTag(field.Key(), field.Value())) - } - return spanTags -} - -func (d *RemoteDispatcher) tags(span *_Span) []*Tag { - var spanTags []*Tag - for _, tag := range span.tags { - spanTags = append(spanTags, ConvertToProtoTag(tag.Key, tag.Value)) - } - return spanTags -} - -/*Close down the file dispatcher*/ -func (d *RemoteDispatcher) Close() { - err := d.client.Close() - if err != nil { - d.logger.Error("Fail to close the haystack-agent dispatcher %v", err) - } -} - -/*ConvertToProtoTag converts to proto tag*/ -func ConvertToProtoTag(key string, value interface{}) *Tag { - switch v := value.(type) { - case string: - return &Tag{ - Key: key, - Myvalue: &Tag_VStr{ - VStr: value.(string), - }, - Type: Tag_STRING, - } - case int: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(int)), - }, - Type: Tag_LONG, - } - case int32: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(int32)), - }, - Type: Tag_LONG, - } - case int16: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(int16)), - }, - Type: Tag_LONG, - } - case int64: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: value.(int64), - }, - Type: Tag_LONG, - } - case uint16: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(uint16)), - }, - Type: Tag_LONG, - } - case uint32: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(uint32)), - }, - Type: Tag_LONG, - } - case uint64: - return &Tag{ - Key: key, - Myvalue: &Tag_VLong{ - VLong: int64(value.(uint64)), - }, - Type: Tag_LONG, - } - case float32: - return &Tag{ - Key: key, - Myvalue: &Tag_VDouble{ - VDouble: float64(value.(float32)), - }, - Type: Tag_DOUBLE, - } - case float64: - return &Tag{ - Key: key, - Myvalue: &Tag_VDouble{ - VDouble: value.(float64), - }, - Type: Tag_DOUBLE, - } - case bool: - return &Tag{ - Key: key, - Myvalue: &Tag_VBool{ - VBool: value.(bool), - }, - Type: Tag_BOOL, - } - case []byte: - return &Tag{ - Key: key, - Myvalue: &Tag_VBytes{ - VBytes: value.([]byte), - }, - Type: Tag_BINARY, - } - case ext.SpanKindEnum: - return &Tag{ - Key: key, - Myvalue: &Tag_VStr{ - VStr: string(value.(ext.SpanKindEnum)), - }, - Type: Tag_STRING, - } - default: - panic(fmt.Errorf("unknown format %v", v)) - } -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/logger.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/logger.go deleted file mode 100644 index 12a6e4e7f..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/logger.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -/*Logger defines a new logger interface*/ -type Logger interface { - Info(format string, v ...interface{}) - Error(format string, v ...interface{}) - Debug(format string, v ...interface{}) -} - -/*NullLogger does nothing*/ -type NullLogger struct{} - -/*Error prints the error message*/ -func (logger NullLogger) Error(format string, v ...interface{}) {} - -/*Info prints the info message*/ -func (logger NullLogger) Info(format string, v ...interface{}) {} - -/*Debug prints the info message*/ -func (logger NullLogger) Debug(format string, v ...interface{}) {} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/propagator.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/propagator.go deleted file mode 100644 index b1bfdeb9d..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/propagator.go +++ /dev/null @@ -1,193 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "fmt" - "net/url" - "strings" - - "github.com/opentracing/opentracing-go" -) - -/*Propagator defines the interface for injecting and extracing the SpanContext from the carrier*/ -type Propagator interface { - // Inject takes `SpanContext` and injects it into `carrier` - Inject(ctx *SpanContext, carrier interface{}) error - - // Extract `SpanContext` from the `carrier` - Extract(carrier interface{}) (*SpanContext, error) -} - -/*Codex defines the interface for encoding and decoding the propagated data*/ -type Codex interface { - Encode(value string) string - Decode(value string) string -} - -/*DefaultCodex is a no op*/ -type DefaultCodex struct{} - -/*Encode a no-op for encoding the value*/ -func (c DefaultCodex) Encode(value string) string { return value } - -/*Decode a no-op for decoding the value*/ -func (c DefaultCodex) Decode(value string) string { return value } - -/*URLCodex encodes decodes a url*/ -type URLCodex struct{} - -/*Encode a no-op for encoding the value*/ -func (c URLCodex) Encode(value string) string { return url.QueryEscape(value) } - -/*Decode a no-op for decoding the value*/ -func (c URLCodex) Decode(value string) string { - decoded, err := url.QueryUnescape(value) - if err == nil { - return decoded - } - return "" -} - -/*PropagatorOpts defines the options need by a propagator*/ -type PropagatorOpts struct { - TraceIDKEYName string - SpanIDKEYName string - ParentSpanIDKEYName string - BaggagePrefixKEYName string -} - -var defaultPropagatorOpts = PropagatorOpts{} -var defaultCodex = DefaultCodex{} - -/*TraceIDKEY returns the trace id key in the propagator*/ -func (p *PropagatorOpts) TraceIDKEY() string { - if p.TraceIDKEYName != "" { - return p.TraceIDKEYName - } - return "Trace-ID" -} - -/*SpanIDKEY returns the span id key in the propagator*/ -func (p *PropagatorOpts) SpanIDKEY() string { - if p.SpanIDKEYName != "" { - return p.SpanIDKEYName - } - return "Span-ID" -} - -/*ParentSpanIDKEY returns the parent span id key in the propagator*/ -func (p *PropagatorOpts) ParentSpanIDKEY() string { - if p.ParentSpanIDKEYName != "" { - return p.ParentSpanIDKEYName - } - return "Parent-ID" -} - -/*BaggageKeyPrefix returns the baggage key prefix*/ -func (p *PropagatorOpts) BaggageKeyPrefix() string { - if p.BaggagePrefixKEYName != "" { - return p.BaggagePrefixKEYName - } - return "Baggage-" -} - -/*TextMapPropagator implements Propagator interface*/ -type TextMapPropagator struct { - opts PropagatorOpts - codex Codex -} - -/*Inject injects the span context in the carrier*/ -func (p *TextMapPropagator) Inject(ctx *SpanContext, carrier interface{}) error { - textMapWriter, ok := carrier.(opentracing.TextMapWriter) - if !ok { - return opentracing.ErrInvalidCarrier - } - - textMapWriter.Set(p.opts.TraceIDKEY(), ctx.TraceID) - textMapWriter.Set(p.opts.SpanIDKEY(), ctx.SpanID) - textMapWriter.Set(p.opts.ParentSpanIDKEY(), ctx.ParentID) - - ctx.ForeachBaggageItem(func(key, value string) bool { - textMapWriter.Set(fmt.Sprintf("%s%s", p.opts.BaggageKeyPrefix(), key), p.codex.Encode(ctx.Baggage[key])) - return true - }) - - return nil -} - -/*Extract the span context from the carrier*/ -func (p *TextMapPropagator) Extract(carrier interface{}) (*SpanContext, error) { - textMapReader, ok := carrier.(opentracing.TextMapReader) - - if !ok { - return nil, opentracing.ErrInvalidCarrier - } - - baggageKeyLowerCasePrefix := strings.ToLower(p.opts.BaggageKeyPrefix()) - traceIDKeyLowerCase := strings.ToLower(p.opts.TraceIDKEY()) - spanIDKeyLowerCase := strings.ToLower(p.opts.SpanIDKEY()) - parentSpanIDKeyLowerCase := strings.ToLower(p.opts.ParentSpanIDKEY()) - - traceID := "" - spanID := "" - parentSpanID := "" - - baggage := make(map[string]string) - err := textMapReader.ForeachKey(func(k, v string) error { - lcKey := strings.ToLower(k) - - if strings.HasPrefix(lcKey, baggageKeyLowerCasePrefix) { - keySansPrefix := lcKey[len(p.opts.BaggageKeyPrefix()):] - baggage[keySansPrefix] = p.codex.Decode(v) - } else if lcKey == traceIDKeyLowerCase { - traceID = v - } else if lcKey == spanIDKeyLowerCase { - spanID = v - } else if lcKey == parentSpanIDKeyLowerCase { - parentSpanID = v - } - return nil - }) - - if err != nil { - return nil, err - } - - return &SpanContext{ - TraceID: traceID, - SpanID: spanID, - ParentID: parentSpanID, - Baggage: baggage, - IsExtractedContext: true, - }, nil -} - -/*NewDefaultTextMapPropagator returns a default text map propagator*/ -func NewDefaultTextMapPropagator() *TextMapPropagator { - return NewTextMapPropagator(defaultPropagatorOpts, defaultCodex) -} - -/*NewTextMapPropagator returns a text map propagator*/ -func NewTextMapPropagator(opts PropagatorOpts, codex Codex) *TextMapPropagator { - return &TextMapPropagator{ - opts: opts, - codex: codex, - } -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/remote_client.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/remote_client.go deleted file mode 100644 index d2abc392c..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/remote_client.go +++ /dev/null @@ -1,165 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "time" - - "github.com/golang/protobuf/proto" - context "golang.org/x/net/context" - grpc "google.golang.org/grpc" -) - -/*RemoteClient remote client*/ -type RemoteClient interface { - Send(span *Span) - Close() error - SetLogger(logger Logger) -} - -/*GrpcClient grpc client*/ -type GrpcClient struct { - conn *grpc.ClientConn - client SpanAgentClient - timeout time.Duration - logger Logger -} - -/*NewGrpcClient returns a new grpc client*/ -func NewGrpcClient(host string, port int, timeout time.Duration) *GrpcClient { - targetHost := fmt.Sprintf("%s:%d", host, port) - conn, err := grpc.Dial(targetHost, grpc.WithInsecure()) - - if err != nil { - panic(fmt.Sprintf("fail to connect to agent with error: %v", err)) - } - - return &GrpcClient{ - conn: conn, - client: NewSpanAgentClient(conn), - timeout: timeout, - } -} - -/*Send a proto span to grpc server*/ -func (c *GrpcClient) Send(span *Span) { - ctx, cancel := context.WithTimeout(context.Background(), c.timeout) - defer cancel() - - result, err := c.client.Dispatch(ctx, span) - - if err != nil { - c.logger.Error("Fail to dispatch to haystack-agent with error %v", err) - } else if result.GetCode() != DispatchResult_SUCCESS { - c.logger.Error(fmt.Sprintf("Fail to dispatch to haystack-agent with error code: %d, message :%s", result.GetCode(), result.GetErrorMessage())) - } else { - c.logger.Debug(fmt.Sprintf("span [%v] has been successfully dispatched to haystack", span)) - } -} - -/*Close the grpc client*/ -func (c *GrpcClient) Close() error { - return c.conn.Close() -} - -/*SetLogger sets the logger*/ -func (c *GrpcClient) SetLogger(logger Logger) { - c.logger = logger -} - -/*HTTPClient a http client*/ -type HTTPClient struct { - url string - headers map[string]string - client *http.Client - logger Logger -} - -/*NewHTTPClient returns a new http client*/ -func NewHTTPClient(url string, headers map[string]string, timeout time.Duration) *HTTPClient { - httpClient := &http.Client{ - Timeout: timeout, - } - - return &HTTPClient{ - url: url, - headers: headers, - client: httpClient, - } -} - -/*Send a proto span to http server*/ -func (c *HTTPClient) Send(span *Span) { - serializedBytes, marshalErr := proto.Marshal(span) - - if marshalErr != nil { - c.logger.Error("Fail to serialize the span to proto bytes, error=%v", marshalErr) - return - } - - postRequest, requestErr := http.NewRequest(http.MethodPost, c.url, bytes.NewReader(serializedBytes)) - if requestErr != nil { - c.logger.Error("Fail to create request for posting span to haystack server, error=%v", requestErr) - return - } - - if c.headers != nil { - for k, v := range c.headers { - postRequest.Header.Add(k, v) - } - } - - resp, err := c.client.Do(postRequest) - - if err != nil { - c.logger.Error("Fail to dispatch to haystack http server, error=%v", err) - } - - defer func() { - closeErr := resp.Body.Close() - if closeErr != nil { - /* do nothing */ - } - }() - - respBytes, respErr := ioutil.ReadAll(resp.Body) - if respErr != nil { - c.logger.Error("Fail to read the http response from haystack server, error=%v", respErr) - return - } - - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - c.logger.Error("Fail to dispatch the span to haystack http server with statusCode=%d , payload=%s", resp.StatusCode, string(respBytes)) - } else { - c.logger.Debug(fmt.Sprintf("span [%v] has been successfully dispatched to haystack, response=%s", span, string(respBytes))) - } -} - -/*Close the http client*/ -func (c *HTTPClient) Close() error { - return nil -} - -/*SetLogger sets the logger*/ -func (c *HTTPClient) SetLogger(logger Logger) { - c.logger = logger -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/span.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/span.go deleted file mode 100644 index 61c0b2080..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/span.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "encoding/json" - "time" - - "github.com/opentracing/opentracing-go" - "github.com/opentracing/opentracing-go/log" -) - -/*_Span implements opentracing.Span*/ -type _Span struct { - tracer *Tracer - context *SpanContext - - operationName string - - // startTime is the timestamp indicating when the span began, with microseconds precision. - startTime time.Time - // duration returns duration of the span with microseconds precision. - duration time.Duration - - tags []opentracing.Tag - logs []opentracing.LogRecord -} - -// SetOperationName sets or changes the operation name. -func (span *_Span) SetOperationName(operationName string) opentracing.Span { - span.operationName = operationName - return span -} - -// SetTag implements SetTag() of opentracing.Span -func (span *_Span) SetTag(key string, value interface{}) opentracing.Span { - span.tags = append(span.tags, - opentracing.Tag{ - Key: key, - Value: value, - }) - return span -} - -// LogFields implements opentracing.Span API -func (span *_Span) LogFields(fields ...log.Field) { - log := opentracing.LogRecord{ - Fields: fields, - Timestamp: time.Now(), - } - span.logs = append(span.logs, log) -} - -// LogKV implements opentracing.Span API -func (span *_Span) LogKV(alternatingKeyValues ...interface{}) { - fields, err := log.InterleavedKVToFields(alternatingKeyValues...) - if err != nil { - span.LogFields(log.Error(err), log.String("function", "LogKV")) - return - } - span.LogFields(fields...) -} - -// LogEvent implements opentracing.Span API -func (span *_Span) LogEvent(event string) { - span.Log(opentracing.LogData{Event: event}) -} - -// LogEventWithPayload implements opentracing.Span API -func (span *_Span) LogEventWithPayload(event string, payload interface{}) { - span.Log(opentracing.LogData{Event: event, Payload: payload}) -} - -// Log implements opentracing.Span API -func (span *_Span) Log(ld opentracing.LogData) { - span.logs = append(span.logs, ld.ToLogRecord()) -} - -// SetBaggageItem implements SetBaggageItem() of opentracing.SpanContext -func (span *_Span) SetBaggageItem(key, value string) opentracing.Span { - span.context = span.context.WithBaggageItem(key, value) - span.LogFields(log.String("event", "baggage"), log.String("payload", key), log.String("payload", value)) - return span -} - -// BaggageItem implements BaggageItem() of opentracing.SpanContext -func (span *_Span) BaggageItem(key string) string { - return span.context.Baggage[key] -} - -// Finish implements opentracing.Span API -func (span *_Span) Finish() { - span.FinishWithOptions(opentracing.FinishOptions{}) -} - -// FinishWithOptions implements opentracing.Span API -func (span *_Span) FinishWithOptions(options opentracing.FinishOptions) { - if options.FinishTime.IsZero() { - options.FinishTime = span.tracer.timeNow() - } - span.duration = options.FinishTime.Sub(span.startTime) - if options.LogRecords != nil { - span.logs = append(span.logs, options.LogRecords...) - } - for _, ld := range options.BulkLogData { - span.logs = append(span.logs, ld.ToLogRecord()) - } - span.tracer.DispatchSpan(span) -} - -// Context implements opentracing.Span API -func (span *_Span) Context() opentracing.SpanContext { - return span.context -} - -/*Tracer returns the tracer*/ -func (span *_Span) Tracer() opentracing.Tracer { - return span.tracer -} - -/*OperationName allows retrieving current operation name*/ -func (span *_Span) OperationName() string { - return span.operationName -} - -/*ServiceName returns the name of the service*/ -func (span *_Span) ServiceName() string { - return span.tracer.serviceName -} - -func (span *_Span) String() string { - data, err := json.Marshal(map[string]interface{}{ - "traceId": span.context.TraceID, - "spanId": span.context.SpanID, - "parentSpanId": span.context.ParentID, - "operationName": span.OperationName(), - "serviceName": span.ServiceName(), - "tags": span.Tags(), - "logs": span.logs, - }) - if err != nil { - panic(err) - } - return string(data) -} - -func (span *_Span) Tags() []opentracing.Tag { - return span.tags -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/span.pb.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/span.pb.go deleted file mode 100644 index 6799ea967..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/span.pb.go +++ /dev/null @@ -1,433 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: span.proto - -package haystack - -import ( - fmt "fmt" - proto "github.com/golang/protobuf/proto" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -// TagType denotes the type of a Tag's value. -type Tag_TagType int32 - -const ( - Tag_STRING Tag_TagType = 0 - Tag_DOUBLE Tag_TagType = 1 - Tag_BOOL Tag_TagType = 2 - Tag_LONG Tag_TagType = 3 - Tag_BINARY Tag_TagType = 4 -) - -var Tag_TagType_name = map[int32]string{ - 0: "STRING", - 1: "DOUBLE", - 2: "BOOL", - 3: "LONG", - 4: "BINARY", -} - -var Tag_TagType_value = map[string]int32{ - "STRING": 0, - "DOUBLE": 1, - "BOOL": 2, - "LONG": 3, - "BINARY": 4, -} - -func (x Tag_TagType) String() string { - return proto.EnumName(Tag_TagType_name, int32(x)) -} - -func (Tag_TagType) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_fc5f2b88b579999f, []int{2, 0} -} - -// Span represents a unit of work performed by a service. -type Span struct { - TraceId string `protobuf:"bytes,1,opt,name=traceId,proto3" json:"traceId,omitempty"` - SpanId string `protobuf:"bytes,2,opt,name=spanId,proto3" json:"spanId,omitempty"` - ParentSpanId string `protobuf:"bytes,3,opt,name=parentSpanId,proto3" json:"parentSpanId,omitempty"` - ServiceName string `protobuf:"bytes,4,opt,name=serviceName,proto3" json:"serviceName,omitempty"` - OperationName string `protobuf:"bytes,5,opt,name=operationName,proto3" json:"operationName,omitempty"` - StartTime int64 `protobuf:"varint,6,opt,name=startTime,proto3" json:"startTime,omitempty"` - Duration int64 `protobuf:"varint,7,opt,name=duration,proto3" json:"duration,omitempty"` - Logs []*Log `protobuf:"bytes,8,rep,name=logs,proto3" json:"logs,omitempty"` - Tags []*Tag `protobuf:"bytes,9,rep,name=tags,proto3" json:"tags,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Span) Reset() { *m = Span{} } -func (m *Span) String() string { return proto.CompactTextString(m) } -func (*Span) ProtoMessage() {} -func (*Span) Descriptor() ([]byte, []int) { - return fileDescriptor_fc5f2b88b579999f, []int{0} -} - -func (m *Span) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Span.Unmarshal(m, b) -} -func (m *Span) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Span.Marshal(b, m, deterministic) -} -func (m *Span) XXX_Merge(src proto.Message) { - xxx_messageInfo_Span.Merge(m, src) -} -func (m *Span) XXX_Size() int { - return xxx_messageInfo_Span.Size(m) -} -func (m *Span) XXX_DiscardUnknown() { - xxx_messageInfo_Span.DiscardUnknown(m) -} - -var xxx_messageInfo_Span proto.InternalMessageInfo - -func (m *Span) GetTraceId() string { - if m != nil { - return m.TraceId - } - return "" -} - -func (m *Span) GetSpanId() string { - if m != nil { - return m.SpanId - } - return "" -} - -func (m *Span) GetParentSpanId() string { - if m != nil { - return m.ParentSpanId - } - return "" -} - -func (m *Span) GetServiceName() string { - if m != nil { - return m.ServiceName - } - return "" -} - -func (m *Span) GetOperationName() string { - if m != nil { - return m.OperationName - } - return "" -} - -func (m *Span) GetStartTime() int64 { - if m != nil { - return m.StartTime - } - return 0 -} - -func (m *Span) GetDuration() int64 { - if m != nil { - return m.Duration - } - return 0 -} - -func (m *Span) GetLogs() []*Log { - if m != nil { - return m.Logs - } - return nil -} - -func (m *Span) GetTags() []*Tag { - if m != nil { - return m.Tags - } - return nil -} - -// Log is a timestamped event with a set of tags. -type Log struct { - Timestamp int64 `protobuf:"varint,1,opt,name=timestamp,proto3" json:"timestamp,omitempty"` - Fields []*Tag `protobuf:"bytes,2,rep,name=fields,proto3" json:"fields,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Log) Reset() { *m = Log{} } -func (m *Log) String() string { return proto.CompactTextString(m) } -func (*Log) ProtoMessage() {} -func (*Log) Descriptor() ([]byte, []int) { - return fileDescriptor_fc5f2b88b579999f, []int{1} -} - -func (m *Log) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Log.Unmarshal(m, b) -} -func (m *Log) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Log.Marshal(b, m, deterministic) -} -func (m *Log) XXX_Merge(src proto.Message) { - xxx_messageInfo_Log.Merge(m, src) -} -func (m *Log) XXX_Size() int { - return xxx_messageInfo_Log.Size(m) -} -func (m *Log) XXX_DiscardUnknown() { - xxx_messageInfo_Log.DiscardUnknown(m) -} - -var xxx_messageInfo_Log proto.InternalMessageInfo - -func (m *Log) GetTimestamp() int64 { - if m != nil { - return m.Timestamp - } - return 0 -} - -func (m *Log) GetFields() []*Tag { - if m != nil { - return m.Fields - } - return nil -} - -// Tag is a strongly typed key/value pair. We use 'oneof' protobuf attribute to represent the possible tagTypes -type Tag struct { - Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` - Type Tag_TagType `protobuf:"varint,2,opt,name=type,proto3,enum=Tag_TagType" json:"type,omitempty"` - // Types that are valid to be assigned to Myvalue: - // *Tag_VStr - // *Tag_VLong - // *Tag_VDouble - // *Tag_VBool - // *Tag_VBytes - Myvalue isTag_Myvalue `protobuf_oneof:"myvalue"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Tag) Reset() { *m = Tag{} } -func (m *Tag) String() string { return proto.CompactTextString(m) } -func (*Tag) ProtoMessage() {} -func (*Tag) Descriptor() ([]byte, []int) { - return fileDescriptor_fc5f2b88b579999f, []int{2} -} - -func (m *Tag) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Tag.Unmarshal(m, b) -} -func (m *Tag) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Tag.Marshal(b, m, deterministic) -} -func (m *Tag) XXX_Merge(src proto.Message) { - xxx_messageInfo_Tag.Merge(m, src) -} -func (m *Tag) XXX_Size() int { - return xxx_messageInfo_Tag.Size(m) -} -func (m *Tag) XXX_DiscardUnknown() { - xxx_messageInfo_Tag.DiscardUnknown(m) -} - -var xxx_messageInfo_Tag proto.InternalMessageInfo - -func (m *Tag) GetKey() string { - if m != nil { - return m.Key - } - return "" -} - -func (m *Tag) GetType() Tag_TagType { - if m != nil { - return m.Type - } - return Tag_STRING -} - -type isTag_Myvalue interface { - isTag_Myvalue() -} - -type Tag_VStr struct { - VStr string `protobuf:"bytes,3,opt,name=vStr,proto3,oneof"` -} - -type Tag_VLong struct { - VLong int64 `protobuf:"varint,4,opt,name=vLong,proto3,oneof"` -} - -type Tag_VDouble struct { - VDouble float64 `protobuf:"fixed64,5,opt,name=vDouble,proto3,oneof"` -} - -type Tag_VBool struct { - VBool bool `protobuf:"varint,6,opt,name=vBool,proto3,oneof"` -} - -type Tag_VBytes struct { - VBytes []byte `protobuf:"bytes,7,opt,name=vBytes,proto3,oneof"` -} - -func (*Tag_VStr) isTag_Myvalue() {} - -func (*Tag_VLong) isTag_Myvalue() {} - -func (*Tag_VDouble) isTag_Myvalue() {} - -func (*Tag_VBool) isTag_Myvalue() {} - -func (*Tag_VBytes) isTag_Myvalue() {} - -func (m *Tag) GetMyvalue() isTag_Myvalue { - if m != nil { - return m.Myvalue - } - return nil -} - -func (m *Tag) GetVStr() string { - if x, ok := m.GetMyvalue().(*Tag_VStr); ok { - return x.VStr - } - return "" -} - -func (m *Tag) GetVLong() int64 { - if x, ok := m.GetMyvalue().(*Tag_VLong); ok { - return x.VLong - } - return 0 -} - -func (m *Tag) GetVDouble() float64 { - if x, ok := m.GetMyvalue().(*Tag_VDouble); ok { - return x.VDouble - } - return 0 -} - -func (m *Tag) GetVBool() bool { - if x, ok := m.GetMyvalue().(*Tag_VBool); ok { - return x.VBool - } - return false -} - -func (m *Tag) GetVBytes() []byte { - if x, ok := m.GetMyvalue().(*Tag_VBytes); ok { - return x.VBytes - } - return nil -} - -// XXX_OneofWrappers is for the internal use of the proto package. -func (*Tag) XXX_OneofWrappers() []interface{} { - return []interface{}{ - (*Tag_VStr)(nil), - (*Tag_VLong)(nil), - (*Tag_VDouble)(nil), - (*Tag_VBool)(nil), - (*Tag_VBytes)(nil), - } -} - -// You can optionally use Batch to send a collection of spans. Spans may not necessarily belong to one traceId. -type Batch struct { - Spans []*Span `protobuf:"bytes,1,rep,name=spans,proto3" json:"spans,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *Batch) Reset() { *m = Batch{} } -func (m *Batch) String() string { return proto.CompactTextString(m) } -func (*Batch) ProtoMessage() {} -func (*Batch) Descriptor() ([]byte, []int) { - return fileDescriptor_fc5f2b88b579999f, []int{3} -} - -func (m *Batch) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_Batch.Unmarshal(m, b) -} -func (m *Batch) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_Batch.Marshal(b, m, deterministic) -} -func (m *Batch) XXX_Merge(src proto.Message) { - xxx_messageInfo_Batch.Merge(m, src) -} -func (m *Batch) XXX_Size() int { - return xxx_messageInfo_Batch.Size(m) -} -func (m *Batch) XXX_DiscardUnknown() { - xxx_messageInfo_Batch.DiscardUnknown(m) -} - -var xxx_messageInfo_Batch proto.InternalMessageInfo - -func (m *Batch) GetSpans() []*Span { - if m != nil { - return m.Spans - } - return nil -} - -func init() { - proto.RegisterEnum("Tag_TagType", Tag_TagType_name, Tag_TagType_value) - proto.RegisterType((*Span)(nil), "Span") - proto.RegisterType((*Log)(nil), "Log") - proto.RegisterType((*Tag)(nil), "Tag") - proto.RegisterType((*Batch)(nil), "Batch") -} - -func init() { proto.RegisterFile("span.proto", fileDescriptor_fc5f2b88b579999f) } - -var fileDescriptor_fc5f2b88b579999f = []byte{ - // 456 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x54, 0x92, 0xcd, 0x8a, 0x9c, 0x40, - 0x14, 0x85, 0xdb, 0xf6, 0xb7, 0xef, 0x74, 0x82, 0x14, 0x61, 0x28, 0x26, 0xb3, 0x10, 0x19, 0x42, - 0xaf, 0x5c, 0x4c, 0x9e, 0xa0, 0x65, 0xc2, 0x74, 0x83, 0x74, 0x87, 0x6a, 0xb3, 0x48, 0x76, 0x35, - 0x5a, 0x71, 0x64, 0xd4, 0x2a, 0xac, 0x6a, 0x89, 0xeb, 0xbc, 0x41, 0x9e, 0x38, 0x54, 0xe9, 0xfc, - 0x2d, 0x84, 0x7b, 0xbe, 0x73, 0xaf, 0xca, 0xe1, 0x00, 0x48, 0x41, 0xbb, 0x44, 0xf4, 0x5c, 0xf1, - 0xf8, 0xdf, 0x12, 0x9c, 0x93, 0xa0, 0x1d, 0xc2, 0xe0, 0xab, 0x9e, 0x16, 0x6c, 0x5f, 0x62, 0x2b, - 0xb2, 0x36, 0x2b, 0xf2, 0x2c, 0xd1, 0x25, 0x78, 0xfa, 0x60, 0x5f, 0xe2, 0xa5, 0x31, 0x66, 0x85, - 0x62, 0x58, 0x0b, 0xda, 0xb3, 0x4e, 0x9d, 0x26, 0xd7, 0x36, 0xee, 0x3b, 0x86, 0x22, 0xb8, 0x90, - 0xac, 0x1f, 0xea, 0x82, 0x1d, 0x68, 0xcb, 0xb0, 0x63, 0x56, 0xde, 0x22, 0x74, 0x03, 0x1f, 0xb8, - 0x60, 0x3d, 0x55, 0x35, 0xef, 0xcc, 0x8e, 0x6b, 0x76, 0xde, 0x43, 0x74, 0x0d, 0x2b, 0xa9, 0x68, - 0xaf, 0xf2, 0xba, 0x65, 0xd8, 0x8b, 0xac, 0x8d, 0x4d, 0x5e, 0x01, 0xba, 0x82, 0xa0, 0x3c, 0x4f, - 0xdb, 0xd8, 0x37, 0xe6, 0x8b, 0x46, 0x18, 0x9c, 0x86, 0x57, 0x12, 0x07, 0x91, 0xbd, 0xb9, 0xb8, - 0x75, 0x92, 0x8c, 0x57, 0xc4, 0x10, 0xed, 0x28, 0x5a, 0x49, 0xbc, 0x9a, 0x9d, 0x9c, 0x56, 0xc4, - 0x90, 0x78, 0x0b, 0x76, 0xc6, 0x2b, 0xfd, 0x51, 0x55, 0xb7, 0x4c, 0x2a, 0xda, 0x0a, 0x13, 0x8a, - 0x4d, 0x5e, 0x01, 0xba, 0x06, 0xef, 0x77, 0xcd, 0x9a, 0x52, 0xe2, 0xe5, 0x9b, 0x17, 0xcc, 0x2c, - 0xfe, 0xbb, 0x04, 0x3b, 0xa7, 0x15, 0x0a, 0xc1, 0x7e, 0x62, 0xe3, 0x1c, 0xa9, 0x1e, 0x51, 0x04, - 0x8e, 0x1a, 0x05, 0x33, 0x61, 0x7e, 0xbc, 0x5d, 0xeb, 0x2b, 0xfd, 0xe4, 0xa3, 0x60, 0xc4, 0x38, - 0xe8, 0x13, 0x38, 0xc3, 0x49, 0xf5, 0x53, 0xa0, 0xbb, 0x05, 0x31, 0x0a, 0x5d, 0x82, 0x3b, 0x64, - 0xbc, 0xab, 0x4c, 0x88, 0xf6, 0x6e, 0x41, 0x26, 0x89, 0xae, 0xc0, 0x1f, 0xee, 0xf8, 0xf9, 0xa1, - 0x99, 0xa2, 0xb3, 0x76, 0x0b, 0xf2, 0x0c, 0xcc, 0x4d, 0xca, 0x79, 0x63, 0x22, 0x0b, 0xcc, 0x8d, - 0x96, 0x08, 0x83, 0x37, 0xa4, 0xa3, 0x62, 0xd2, 0xc4, 0xb5, 0xde, 0x2d, 0xc8, 0xac, 0xe3, 0x2d, - 0xf8, 0xf3, 0xcf, 0x20, 0x00, 0xef, 0x94, 0x93, 0xfd, 0xe1, 0x3e, 0x5c, 0xe8, 0xf9, 0xee, 0xf8, - 0x23, 0xcd, 0xbe, 0x85, 0x16, 0x0a, 0xc0, 0x49, 0x8f, 0xc7, 0x2c, 0x5c, 0xea, 0x29, 0x3b, 0x1e, - 0xee, 0x43, 0x5b, 0xfb, 0xe9, 0xfe, 0xb0, 0x25, 0x3f, 0x43, 0x27, 0x5d, 0x81, 0xdf, 0x8e, 0x03, - 0x6d, 0xce, 0x2c, 0xbe, 0x01, 0x37, 0xa5, 0xaa, 0x78, 0x44, 0x9f, 0xc1, 0xd5, 0xad, 0x91, 0xd8, - 0x32, 0x59, 0xb9, 0x89, 0xee, 0x07, 0x99, 0x58, 0xfa, 0x05, 0x70, 0xc1, 0xdb, 0x84, 0xfd, 0x11, - 0xac, 0xac, 0x69, 0xc2, 0x05, 0xeb, 0x12, 0x5d, 0xbe, 0xba, 0xab, 0xbe, 0x5b, 0xbf, 0x82, 0x47, - 0x3a, 0x4a, 0x45, 0x8b, 0xa7, 0x07, 0xcf, 0x54, 0xf6, 0xeb, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, - 0xdd, 0x60, 0xee, 0x6b, 0xc0, 0x02, 0x00, 0x00, -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/spanAgent.pb.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/spanAgent.pb.go deleted file mode 100644 index 72d1ab6d2..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/spanAgent.pb.go +++ /dev/null @@ -1,197 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: spanAgent.proto - -package haystack - -import ( - context "context" - fmt "fmt" - proto "github.com/golang/protobuf/proto" - grpc "google.golang.org/grpc" - math "math" -) - -// Reference imports to suppress errors if they are not otherwise used. -var _ = proto.Marshal -var _ = fmt.Errorf -var _ = math.Inf - -// This is a compile-time assertion to ensure that this generated file -// is compatible with the proto package it is being compiled against. -// A compilation error at this line likely means your copy of the -// proto package needs to be updated. -const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package - -type DispatchResult_ResultCode int32 - -const ( - DispatchResult_SUCCESS DispatchResult_ResultCode = 0 - DispatchResult_UNKNOWN_ERROR DispatchResult_ResultCode = 1 - DispatchResult_RATE_LIMIT_ERROR DispatchResult_ResultCode = 2 -) - -var DispatchResult_ResultCode_name = map[int32]string{ - 0: "SUCCESS", - 1: "UNKNOWN_ERROR", - 2: "RATE_LIMIT_ERROR", -} - -var DispatchResult_ResultCode_value = map[string]int32{ - "SUCCESS": 0, - "UNKNOWN_ERROR": 1, - "RATE_LIMIT_ERROR": 2, -} - -func (x DispatchResult_ResultCode) String() string { - return proto.EnumName(DispatchResult_ResultCode_name, int32(x)) -} - -func (DispatchResult_ResultCode) EnumDescriptor() ([]byte, []int) { - return fileDescriptor_5a4cb81dd7dcc459, []int{0, 0} -} - -type DispatchResult struct { - Code DispatchResult_ResultCode `protobuf:"varint,1,opt,name=code,proto3,enum=DispatchResult_ResultCode" json:"code,omitempty"` - ErrorMessage string `protobuf:"bytes,2,opt,name=error_message,json=errorMessage,proto3" json:"error_message,omitempty"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` -} - -func (m *DispatchResult) Reset() { *m = DispatchResult{} } -func (m *DispatchResult) String() string { return proto.CompactTextString(m) } -func (*DispatchResult) ProtoMessage() {} -func (*DispatchResult) Descriptor() ([]byte, []int) { - return fileDescriptor_5a4cb81dd7dcc459, []int{0} -} - -func (m *DispatchResult) XXX_Unmarshal(b []byte) error { - return xxx_messageInfo_DispatchResult.Unmarshal(m, b) -} -func (m *DispatchResult) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { - return xxx_messageInfo_DispatchResult.Marshal(b, m, deterministic) -} -func (m *DispatchResult) XXX_Merge(src proto.Message) { - xxx_messageInfo_DispatchResult.Merge(m, src) -} -func (m *DispatchResult) XXX_Size() int { - return xxx_messageInfo_DispatchResult.Size(m) -} -func (m *DispatchResult) XXX_DiscardUnknown() { - xxx_messageInfo_DispatchResult.DiscardUnknown(m) -} - -var xxx_messageInfo_DispatchResult proto.InternalMessageInfo - -func (m *DispatchResult) GetCode() DispatchResult_ResultCode { - if m != nil { - return m.Code - } - return DispatchResult_SUCCESS -} - -func (m *DispatchResult) GetErrorMessage() string { - if m != nil { - return m.ErrorMessage - } - return "" -} - -func init() { - proto.RegisterEnum("DispatchResult_ResultCode", DispatchResult_ResultCode_name, DispatchResult_ResultCode_value) - proto.RegisterType((*DispatchResult)(nil), "DispatchResult") -} - -func init() { proto.RegisterFile("spanAgent.proto", fileDescriptor_5a4cb81dd7dcc459) } - -var fileDescriptor_5a4cb81dd7dcc459 = []byte{ - // 254 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x5c, 0x90, 0xc1, 0x4a, 0xf3, 0x40, - 0x10, 0xc7, 0xbf, 0x2d, 0x9f, 0xda, 0x8e, 0xb6, 0x8d, 0x8b, 0x87, 0x92, 0x53, 0x89, 0x97, 0x9e, - 0x56, 0xa9, 0x4f, 0xd0, 0xc6, 0x1c, 0x8a, 0x36, 0x95, 0x4d, 0x8b, 0xe0, 0x25, 0x8c, 0x9b, 0x21, - 0x0d, 0xda, 0xec, 0xb2, 0xbb, 0x82, 0x3e, 0x92, 0x6f, 0x29, 0x4d, 0x2a, 0xa2, 0xa7, 0x19, 0x7e, - 0x33, 0x03, 0xff, 0xf9, 0xc1, 0xd0, 0x19, 0xac, 0x67, 0x25, 0xd5, 0x5e, 0x18, 0xab, 0xbd, 0x0e, - 0x61, 0x0f, 0xda, 0x3e, 0xfa, 0x64, 0x30, 0xb8, 0xad, 0x9c, 0x41, 0xaf, 0xb6, 0x92, 0xdc, 0xdb, - 0xab, 0xe7, 0x02, 0xfe, 0x2b, 0x5d, 0xd0, 0x88, 0x8d, 0xd9, 0x64, 0x30, 0x0d, 0xc5, 0xef, 0xb1, - 0x68, 0x4b, 0xac, 0x0b, 0x92, 0xcd, 0x1e, 0xbf, 0x84, 0x3e, 0x59, 0xab, 0x6d, 0xbe, 0x23, 0xe7, - 0xb0, 0xa4, 0x51, 0x67, 0xcc, 0x26, 0x3d, 0x79, 0xd6, 0xc0, 0x65, 0xcb, 0xa2, 0x39, 0xc0, 0xcf, - 0x21, 0x3f, 0x85, 0x93, 0x6c, 0x13, 0xc7, 0x49, 0x96, 0x05, 0xff, 0xf8, 0x39, 0xf4, 0x37, 0xe9, - 0x5d, 0xba, 0x7a, 0x4c, 0xf3, 0x44, 0xca, 0x95, 0x0c, 0x18, 0xbf, 0x80, 0x40, 0xce, 0xd6, 0x49, - 0x7e, 0xbf, 0x58, 0x2e, 0xd6, 0x07, 0xda, 0x99, 0x5e, 0x41, 0x2f, 0xfb, 0x7e, 0x85, 0x47, 0xd0, - 0x2d, 0x0e, 0xc1, 0xf8, 0x91, 0xd8, 0xf3, 0x70, 0xf8, 0x27, 0xea, 0xfc, 0x1a, 0x22, 0xa5, 0x77, - 0x82, 0xde, 0x0d, 0x15, 0x15, 0x0a, 0x6d, 0xa8, 0x16, 0xde, 0xa2, 0xaa, 0xea, 0x52, 0x60, 0x23, - 0x04, 0x4d, 0xf5, 0xc0, 0x9e, 0xba, 0x5b, 0xfc, 0x70, 0x1e, 0xd5, 0xcb, 0xf3, 0x71, 0x63, 0xe5, - 0xe6, 0x2b, 0x00, 0x00, 0xff, 0xff, 0x30, 0xb9, 0x7d, 0x07, 0x34, 0x01, 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 - -// SpanAgentClient is the client API for SpanAgent service. -// -// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream. -type SpanAgentClient interface { - Dispatch(ctx context.Context, in *Span, opts ...grpc.CallOption) (*DispatchResult, error) -} - -type spanAgentClient struct { - cc *grpc.ClientConn -} - -func NewSpanAgentClient(cc *grpc.ClientConn) SpanAgentClient { - return &spanAgentClient{cc} -} - -func (c *spanAgentClient) Dispatch(ctx context.Context, in *Span, opts ...grpc.CallOption) (*DispatchResult, error) { - out := new(DispatchResult) - err := c.cc.Invoke(ctx, "/SpanAgent/dispatch", in, out, opts...) - if err != nil { - return nil, err - } - return out, nil -} - -// SpanAgentServer is the server API for SpanAgent service. -type SpanAgentServer interface { - Dispatch(context.Context, *Span) (*DispatchResult, error) -} - -func RegisterSpanAgentServer(s *grpc.Server, srv SpanAgentServer) { - s.RegisterService(&_SpanAgent_serviceDesc, srv) -} - -func _SpanAgent_Dispatch_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { - in := new(Span) - if err := dec(in); err != nil { - return nil, err - } - if interceptor == nil { - return srv.(SpanAgentServer).Dispatch(ctx, in) - } - info := &grpc.UnaryServerInfo{ - Server: srv, - FullMethod: "/SpanAgent/Dispatch", - } - handler := func(ctx context.Context, req interface{}) (interface{}, error) { - return srv.(SpanAgentServer).Dispatch(ctx, req.(*Span)) - } - return interceptor(ctx, in, info, handler) -} - -var _SpanAgent_serviceDesc = grpc.ServiceDesc{ - ServiceName: "SpanAgent", - HandlerType: (*SpanAgentServer)(nil), - Methods: []grpc.MethodDesc{ - { - MethodName: "dispatch", - Handler: _SpanAgent_Dispatch_Handler, - }, - }, - Streams: []grpc.StreamDesc{}, - Metadata: "spanAgent.proto", -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/span_context.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/span_context.go deleted file mode 100644 index 1d8e883ee..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/span_context.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "fmt" -) - -/*SpanContext implements opentracing.spanContext*/ -type SpanContext struct { - // traceID represents globally unique ID of the trace. - TraceID string - - // spanID represents span ID that must be unique within its trace - SpanID string - - // parentID refers to the ID of the parent span. - // Should be empty if the current span is a root span. - ParentID string - - //Context baggage. The is a snapshot in time. - Baggage map[string]string - - // set to true if extracted using a extractor in tracer - IsExtractedContext bool -} - -// IsValid indicates whether this context actually represents a valid trace. -func (context SpanContext) IsValid() bool { - return context.TraceID != "" && context.SpanID != "" -} - -/*ForeachBaggageItem implements opentracing.spancontext*/ -func (context SpanContext) ForeachBaggageItem(handler func(k, v string) bool) { - for k, v := range context.Baggage { - if !handler(k, v) { - break - } - } -} - -// WithBaggageItem creates a new context with an extra baggage item. -func (context SpanContext) WithBaggageItem(key, value string) *SpanContext { - var newBaggage map[string]string - if context.Baggage == nil { - newBaggage = map[string]string{key: value} - } else { - newBaggage = make(map[string]string, len(context.Baggage)+1) - for k, v := range context.Baggage { - newBaggage[k] = v - } - newBaggage[key] = value - } - return &SpanContext{ - TraceID: context.TraceID, - SpanID: context.SpanID, - ParentID: context.ParentID, - Baggage: newBaggage, - } -} - -/*ToString represents the string*/ -func (context SpanContext) ToString() string { - return fmt.Sprintf("%+v", context) -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer.go deleted file mode 100644 index 0bf5f6dd2..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer.go +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "io" - "time" - - "github.com/google/uuid" - "github.com/opentracing/opentracing-go" - "github.com/opentracing/opentracing-go/ext" -) - -/*Tracer implements the opentracing.tracer*/ -type Tracer struct { - serviceName string - logger Logger - dispatcher Dispatcher - commonTags []opentracing.Tag - timeNow func() time.Time - idGenerator func() string - propagators map[interface{}]Propagator - useDualSpanMode bool -} - -/*NewTracer creates a new tracer*/ -func NewTracer( - serviceName string, - dispatcher Dispatcher, - options ...TracerOption, -) (opentracing.Tracer, io.Closer) { - tracer := &Tracer{ - serviceName: serviceName, - dispatcher: dispatcher, - useDualSpanMode: false, - } - tracer.propagators = make(map[interface{}]Propagator) - tracer.propagators[opentracing.TextMap] = NewDefaultTextMapPropagator() - tracer.propagators[opentracing.HTTPHeaders] = NewTextMapPropagator(PropagatorOpts{}, URLCodex{}) - for _, option := range options { - option(tracer) - } - - if tracer.timeNow == nil { - tracer.timeNow = time.Now - } - - if tracer.logger == nil { - tracer.logger = NullLogger{} - } - - if tracer.idGenerator == nil { - tracer.idGenerator = func() string { - _uuid, err := uuid.NewUUID() - if err != nil { - panic(err) - } - return _uuid.String() - } - } - - dispatcher.SetLogger(tracer.logger) - return tracer, tracer -} - -/*StartSpan starts a new span*/ -func (tracer *Tracer) StartSpan( - operationName string, - options ...opentracing.StartSpanOption, -) opentracing.Span { - sso := opentracing.StartSpanOptions{} - - for _, o := range options { - o.Apply(&sso) - } - - if sso.StartTime.IsZero() { - sso.StartTime = tracer.timeNow() - } - - var followsFromIsParent = false - var parent *SpanContext - - for _, ref := range sso.References { - if ref.Type == opentracing.ChildOfRef { - if parent == nil || followsFromIsParent { - parent = ref.ReferencedContext.(*SpanContext) - } - } else if ref.Type == opentracing.FollowsFromRef { - if parent == nil { - parent = ref.ReferencedContext.(*SpanContext) - followsFromIsParent = true - } - } - } - - spanContext := tracer.createSpanContext(parent, tracer.isServerSpan(sso.Tags)) - - span := &_Span{ - tracer: tracer, - context: spanContext, - operationName: operationName, - startTime: sso.StartTime, - duration: 0, - } - - for _, tag := range tracer.Tags() { - span.SetTag(tag.Key, tag.Value) - } - for k, v := range sso.Tags { - span.SetTag(k, v) - } - - return span -} - -func (tracer *Tracer) isServerSpan(spanTags map[string]interface{}) bool { - if spanKind, ok := spanTags[string(ext.SpanKind)]; ok && spanKind == "server" { - return true - } - return false -} - -func (tracer *Tracer) createSpanContext(parent *SpanContext, isServerSpan bool) *SpanContext { - if parent == nil || !parent.IsValid() { - return &SpanContext{ - TraceID: tracer.idGenerator(), - SpanID: tracer.idGenerator(), - } - } - - // This is a check to see if the tracer is configured to support single - // single span type (Zipkin style shared span id) or - // dual span type (client and server having their own span ids ). - // a. If tracer is not of dualSpanType and if it is a server span then we - // just return the parent context with the same shared span ids - // b. If tracer is not of dualSpanType and if the parent context is an extracted one from the wire - // then we assume this is the first span in the server and so just return the parent context - // with the same shared span ids - if !tracer.useDualSpanMode && (isServerSpan || parent.IsExtractedContext) { - return &SpanContext{ - TraceID: parent.TraceID, - SpanID: parent.SpanID, - ParentID: parent.ParentID, - Baggage: parent.Baggage, - IsExtractedContext: false, - } - } - return &SpanContext{ - TraceID: parent.TraceID, - SpanID: tracer.idGenerator(), - ParentID: parent.SpanID, - Baggage: parent.Baggage, - IsExtractedContext: false, - } -} - -/*Inject implements Inject() method of opentracing.Tracer*/ -func (tracer *Tracer) Inject(ctx opentracing.SpanContext, format interface{}, carrier interface{}) error { - c, ok := ctx.(*SpanContext) - if !ok { - return opentracing.ErrInvalidSpanContext - } - if injector, ok := tracer.propagators[format]; ok { - return injector.Inject(c, carrier) - } - return opentracing.ErrUnsupportedFormat -} - -/*Extract implements Extract() method of opentracing.Tracer*/ -func (tracer *Tracer) Extract( - format interface{}, - carrier interface{}, -) (opentracing.SpanContext, error) { - if extractor, ok := tracer.propagators[format]; ok { - return extractor.Extract(carrier) - } - return nil, opentracing.ErrUnsupportedFormat -} - -/*Tags return all common tags */ -func (tracer *Tracer) Tags() []opentracing.Tag { - return tracer.commonTags -} - -/*DispatchSpan dispatches the span to a dispatcher*/ -func (tracer *Tracer) DispatchSpan(span *_Span) { - if tracer.dispatcher != nil { - tracer.dispatcher.Dispatch(span) - } -} - -/*Close closes the tracer*/ -func (tracer *Tracer) Close() error { - if tracer.dispatcher != nil { - tracer.dispatcher.Close() - } - return nil -} diff --git a/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer_options.go b/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer_options.go deleted file mode 100644 index 4fb78a27e..000000000 --- a/vendor/github.com/ExpediaDotCom/haystack-client-go/tracer_options.go +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2018 Expedia Group. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ - -package haystack - -import ( - "github.com/opentracing/opentracing-go" -) - -// TracerOption is a function that sets some option on the tracer -type TracerOption func(tracer *Tracer) - -/*TracerOptions a list of tracer options*/ -type TracerOptions struct{} - -/*TracerOptionsFactory factory to create multiple tracer options*/ -var TracerOptionsFactory TracerOptions - -/*Propagator registers a new Propagator*/ -func (t TracerOptions) Propagator(format interface{}, propagator Propagator) TracerOption { - return func(tracer *Tracer) { - tracer.propagators[format] = propagator - } -} - -/*Tag adds a common tag in every span*/ -func (t TracerOptions) Tag(key string, value interface{}) TracerOption { - return func(tracer *Tracer) { - tracer.commonTags = append(tracer.commonTags, opentracing.Tag{Key: key, Value: value}) - } -} - -/*Logger set the logger type*/ -func (t TracerOptions) Logger(logger Logger) TracerOption { - return func(tracer *Tracer) { - tracer.logger = logger - } -} - -/*UseDualSpanMode sets the tracer in dual span mode*/ -func (t TracerOptions) UseDualSpanMode() TracerOption { - return func(tracer *Tracer) { - tracer.useDualSpanMode = true - } -} diff --git a/vendor/github.com/JamesClonk/vultr/LICENSE b/vendor/github.com/JamesClonk/vultr/LICENSE deleted file mode 100644 index be20a1280..000000000 --- a/vendor/github.com/JamesClonk/vultr/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Fabio Berchtold - -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/JamesClonk/vultr/lib/account_info.go b/vendor/github.com/JamesClonk/vultr/lib/account_info.go deleted file mode 100644 index f994f9242..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/account_info.go +++ /dev/null @@ -1,71 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "strconv" -) - -// AccountInfo of Vultr account -type AccountInfo struct { - Balance float64 `json:"balance"` - PendingCharges float64 `json:"pending_charges"` - LastPaymentDate string `json:"last_payment_date"` - LastPaymentAmount float64 `json:"last_payment_amount"` -} - -// GetAccountInfo retrieves the Vultr account information about current balance, pending charges, etc.. -func (c *Client) GetAccountInfo() (info AccountInfo, err error) { - if err := c.get(`account/info`, &info); err != nil { - return AccountInfo{}, err - } - return -} - -// UnmarshalJSON implements json.Unmarshaller on AccountInfo. -// This is needed because the Vultr API is inconsistent in it's JSON responses for account info. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (a *AccountInfo) UnmarshalJSON(data []byte) (err error) { - if a == nil { - *a = AccountInfo{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["balance"]) - if len(value) == 0 || value == "" { - value = "0" - } - b, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.Balance = b - - value = fmt.Sprintf("%v", fields["pending_charges"]) - if len(value) == 0 || value == "" { - value = "0" - } - pc, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.PendingCharges = pc - - value = fmt.Sprintf("%v", fields["last_payment_amount"]) - if len(value) == 0 || value == "" { - value = "0" - } - lpa, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - a.LastPaymentAmount = lpa - - a.LastPaymentDate = fmt.Sprintf("%v", fields["last_payment_date"]) - - return -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/applications.go b/vendor/github.com/JamesClonk/vultr/lib/applications.go deleted file mode 100644 index f44d8c81e..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/applications.go +++ /dev/null @@ -1,38 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// Application on Vultr -type Application struct { - ID string `json:"APPID"` - Name string `json:"name"` - ShortName string `json:"short_name"` - DeployName string `json:"deploy_name"` - Surcharge float64 `json:"surcharge"` -} - -type applications []Application - -func (s applications) Len() int { return len(s) } -func (s applications) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s applications) Less(i, j int) bool { - return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) -} - -// GetApplications returns a list of all available applications on Vultr -func (c *Client) GetApplications() ([]Application, error) { - var appMap map[string]Application - if err := c.get(`app/list`, &appMap); err != nil { - return nil, err - } - - var appList []Application - for _, app := range appMap { - appList = append(appList, app) - } - sort.Sort(applications(appList)) - return appList, nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/block_storage.go b/vendor/github.com/JamesClonk/vultr/lib/block_storage.go deleted file mode 100644 index e9e8e115d..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/block_storage.go +++ /dev/null @@ -1,210 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// BlockStorage on Vultr account -type BlockStorage struct { - ID string `json:"SUBID,string"` - Name string `json:"label"` - RegionID int `json:"DCID,string"` - SizeGB int `json:"size_gb,string"` - Created string `json:"date_created"` - Cost string `json:"cost_per_month"` - Status string `json:"status"` - AttachedTo string `json:"attached_to_SUBID"` -} - -type blockstorages []BlockStorage - -func (b blockstorages) Len() int { return len(b) } -func (b blockstorages) Swap(i, j int) { b[i], b[j] = b[j], b[i] } -func (b blockstorages) Less(i, j int) bool { - // sort order: name, size, status - if strings.ToLower(b[i].Name) < strings.ToLower(b[j].Name) { - return true - } else if strings.ToLower(b[i].Name) > strings.ToLower(b[j].Name) { - return false - } - if b[i].SizeGB < b[j].SizeGB { - return true - } else if b[i].SizeGB > b[j].SizeGB { - return false - } - return b[i].Status < b[j].Status -} - -// UnmarshalJSON implements json.Unmarshaller on BlockStorage. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (b *BlockStorage) UnmarshalJSON(data []byte) (err error) { - if b == nil { - *b = BlockStorage{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - b.ID = "" - } else { - id, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - b.ID = strconv.FormatFloat(id, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - b.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["size_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - size, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - b.SizeGB = int(size) - - value = fmt.Sprintf("%v", fields["attached_to_SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - b.AttachedTo = "" - } else { - attached, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - b.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) - } - - b.Name = fmt.Sprintf("%v", fields["label"]) - b.Created = fmt.Sprintf("%v", fields["date_created"]) - b.Status = fmt.Sprintf("%v", fields["status"]) - b.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) - - return -} - -// GetBlockStorages returns a list of all active block storages on Vultr account -func (c *Client) GetBlockStorages() (storages []BlockStorage, err error) { - if err := c.get(`block/list`, &storages); err != nil { - return nil, err - } - sort.Sort(blockstorages(storages)) - return storages, nil -} - -// GetBlockStorage returns block storage with given ID -func (c *Client) GetBlockStorage(id string) (BlockStorage, error) { - storages, err := c.GetBlockStorages() - if err != nil { - return BlockStorage{}, err - } - - for _, s := range storages { - if s.ID == id { - return s, nil - } - } - return BlockStorage{}, fmt.Errorf("BlockStorage with ID %v not found", id) -} - -// CreateBlockStorage creates a new block storage on Vultr account -func (c *Client) CreateBlockStorage(name string, regionID, size int) (BlockStorage, error) { - values := url.Values{ - "label": {name}, - "DCID": {fmt.Sprintf("%v", regionID)}, - "size_gb": {fmt.Sprintf("%v", size)}, - } - - var storage BlockStorage - if err := c.post(`block/create`, values, &storage); err != nil { - return BlockStorage{}, err - } - storage.RegionID = regionID - storage.Name = name - storage.SizeGB = size - - return storage, nil -} - -// ResizeBlockStorage resizes an existing block storage -func (c *Client) ResizeBlockStorage(id string, size int) error { - values := url.Values{ - "SUBID": {id}, - "size_gb": {fmt.Sprintf("%v", size)}, - } - - if err := c.post(`block/resize`, values, nil); err != nil { - return err - } - return nil -} - -// LabelBlockStorage changes the label on an existing block storage -func (c *Client) LabelBlockStorage(id, name string) error { - values := url.Values{ - "SUBID": {id}, - "label": {name}, - } - - if err := c.post(`block/label_set`, values, nil); err != nil { - return err - } - return nil -} - -// AttachBlockStorage attaches block storage to an existing virtual machine -func (c *Client) AttachBlockStorage(id, serverID string) error { - values := url.Values{ - "SUBID": {id}, - "attach_to_SUBID": {serverID}, - } - - if err := c.post(`block/attach`, values, nil); err != nil { - return err - } - return nil -} - -// DetachBlockStorage detaches block storage from virtual machine -func (c *Client) DetachBlockStorage(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`block/detach`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteBlockStorage deletes an existing block storage -func (c *Client) DeleteBlockStorage(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`block/delete`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/client.go b/vendor/github.com/JamesClonk/vultr/lib/client.go deleted file mode 100644 index 0f805a10c..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/client.go +++ /dev/null @@ -1,249 +0,0 @@ -package lib - -import ( - "bytes" - "crypto/tls" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "math/rand" - "net/http" - "net/url" - "strings" - "time" - - "github.com/juju/ratelimit" -) - -const ( - // Version of this libary - Version = "1.13.0" - - // APIVersion of Vultr - APIVersion = "v1" - - // DefaultEndpoint to be used - DefaultEndpoint = "https://api.vultr.com/" - - mediaType = "application/json" -) - -// retryableStatusCodes are API response status codes that indicate that -// the failed request can be retried without further actions. -var retryableStatusCodes = map[int]struct{}{ - 503: {}, // Rate limit hit - 500: {}, // Internal server error. Try again at a later time. -} - -// Client represents the Vultr API client -type Client struct { - // HTTP client for communication with the Vultr API - client *http.Client - - // User agent for HTTP client - UserAgent string - - // Endpoint URL for API requests - Endpoint *url.URL - - // API key for accessing the Vultr API - APIKey string - - // Max. number of request attempts - MaxAttempts int - - // Throttling struct - bucket *ratelimit.Bucket -} - -// Options represents optional settings and flags that can be passed to NewClient -type Options struct { - // HTTP client for communication with the Vultr API - HTTPClient *http.Client - - // User agent for HTTP client - UserAgent string - - // Endpoint URL for API requests - Endpoint string - - // API rate limitation, calls per duration - RateLimitation time.Duration - - // Max. number of times to retry API calls - MaxRetries int -} - -// NewClient creates new Vultr API client. Options are optional and can be nil. -func NewClient(apiKey string, options *Options) *Client { - userAgent := "vultr-go/" + Version - transport := &http.Transport{ - TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), - } - client := http.DefaultClient - client.Transport = transport - endpoint, _ := url.Parse(DefaultEndpoint) - rate := 505 * time.Millisecond - attempts := 1 - - if options != nil { - if options.HTTPClient != nil { - client = options.HTTPClient - } - if options.UserAgent != "" { - userAgent = options.UserAgent - } - if options.Endpoint != "" { - endpoint, _ = url.Parse(options.Endpoint) - } - if options.RateLimitation != 0 { - rate = options.RateLimitation - } - if options.MaxRetries != 0 { - attempts = options.MaxRetries + 1 - } - } - - return &Client{ - UserAgent: userAgent, - client: client, - Endpoint: endpoint, - APIKey: apiKey, - MaxAttempts: attempts, - bucket: ratelimit.NewBucket(rate, 1), - } -} - -func apiPath(path string) string { - return fmt.Sprintf("/%s/%s", APIVersion, path) -} - -func apiKeyPath(path, apiKey string) string { - if strings.Contains(path, "?") { - return path + "&api_key=" + apiKey - } - return path + "?api_key=" + apiKey -} - -func (c *Client) get(path string, data interface{}) error { - req, err := c.newRequest("GET", apiPath(path), nil) - if err != nil { - return err - } - return c.do(req, data) -} - -func (c *Client) post(path string, values url.Values, data interface{}) error { - req, err := c.newRequest("POST", apiPath(path), strings.NewReader(values.Encode())) - if err != nil { - return err - } - return c.do(req, data) -} - -func (c *Client) newRequest(method string, path string, body io.Reader) (*http.Request, error) { - relPath, err := url.Parse(apiKeyPath(path, c.APIKey)) - if err != nil { - return nil, err - } - - url := c.Endpoint.ResolveReference(relPath) - - req, err := http.NewRequest(method, url.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("User-Agent", c.UserAgent) - req.Header.Add("Accept", mediaType) - - if req.Method == "POST" { - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - } - return req, nil -} - -func (c *Client) do(req *http.Request, data interface{}) error { - // Throttle http requests to avoid hitting Vultr's API rate-limit - c.bucket.Wait(1) - - // Request body gets drained on each read so we - // need to save it's content for retrying requests - var err error - var requestBody []byte - if req.Body != nil { - requestBody, err = ioutil.ReadAll(req.Body) - if err != nil { - return fmt.Errorf("Error reading request body: %v", err) - } - req.Body.Close() - } - - var apiError error - for tryCount := 1; tryCount <= c.MaxAttempts; tryCount++ { - // Restore request body to the original state - if requestBody != nil { - req.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody)) - } - - resp, err := c.client.Do(req) - if err != nil { - return err - } - - body, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - return err - } - - if resp.StatusCode == http.StatusOK { - if data != nil { - // avoid unmarshalling problem because Vultr API returns - // empty array instead of empty map when it shouldn't! - if string(body) == `[]` { - data = nil - } else { - if err := json.Unmarshal(body, data); err != nil { - return err - } - } - } - return nil - } - - apiError = errors.New(string(body)) - if !isCodeRetryable(resp.StatusCode) { - break - } - - delay := backoffDuration(tryCount) - time.Sleep(delay) - } - - return apiError -} - -// backoffDuration returns the duration to wait before retrying the request. -// Duration is an exponential function of the retry count with a jitter of ~0-30%. -func backoffDuration(retryCount int) time.Duration { - // Upper limit of delay at ~1 minute - if retryCount > 7 { - retryCount = 7 - } - - rand.Seed(time.Now().UnixNano()) - delay := (1 << uint(retryCount)) * (rand.Intn(150) + 500) - return time.Duration(delay) * time.Millisecond -} - -// isCodeRetryable returns true if the given status code means that we should retry. -func isCodeRetryable(statusCode int) bool { - if _, ok := retryableStatusCodes[statusCode]; ok { - return true - } - - return false -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/dns.go b/vendor/github.com/JamesClonk/vultr/lib/dns.go deleted file mode 100644 index e66275b68..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/dns.go +++ /dev/null @@ -1,150 +0,0 @@ -package lib - -import ( - "fmt" - "net/url" - "sort" - "strings" -) - -// DNSDomain represents a DNS domain on Vultr -type DNSDomain struct { - Domain string `json:"domain"` - Created string `json:"date_created"` -} - -type dnsdomains []DNSDomain - -func (d dnsdomains) Len() int { return len(d) } -func (d dnsdomains) Swap(i, j int) { d[i], d[j] = d[j], d[i] } -func (d dnsdomains) Less(i, j int) bool { - return strings.ToLower(d[i].Domain) < strings.ToLower(d[j].Domain) -} - -// DNSRecord represents a DNS record on Vultr -type DNSRecord struct { - RecordID int `json:"RECORDID"` - Type string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - Priority int `json:"priority"` - TTL int `json:"ttl"` -} - -type dnsrecords []DNSRecord - -func (d dnsrecords) Len() int { return len(d) } -func (d dnsrecords) Swap(i, j int) { d[i], d[j] = d[j], d[i] } -func (d dnsrecords) Less(i, j int) bool { - // sort order: type, data, name - if d[i].Type < d[j].Type { - return true - } else if d[i].Type > d[j].Type { - return false - } - if d[i].Data < d[j].Data { - return true - } else if d[i].Data > d[j].Data { - return false - } - return strings.ToLower(d[i].Name) < strings.ToLower(d[j].Name) -} - -// GetDNSDomains returns a list of available domains on Vultr account -func (c *Client) GetDNSDomains() (domains []DNSDomain, err error) { - if err := c.get(`dns/list`, &domains); err != nil { - return nil, err - } - sort.Sort(dnsdomains(domains)) - return domains, nil -} - -// GetDNSRecords returns a list of all DNS records of a particular domain -func (c *Client) GetDNSRecords(domain string) (records []DNSRecord, err error) { - if err := c.get(`dns/records?domain=`+domain, &records); err != nil { - return nil, err - } - sort.Sort(dnsrecords(records)) - return records, nil -} - -// CreateDNSDomain creates a new DNS domain name on Vultr -func (c *Client) CreateDNSDomain(domain, serverIP string) error { - values := url.Values{ - "domain": {domain}, - "serverip": {serverIP}, - } - - if err := c.post(`dns/create_domain`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteDNSDomain deletes an existing DNS domain name -func (c *Client) DeleteDNSDomain(domain string) error { - values := url.Values{ - "domain": {domain}, - } - - if err := c.post(`dns/delete_domain`, values, nil); err != nil { - return err - } - return nil -} - -// CreateDNSRecord creates a new DNS record -func (c *Client) CreateDNSRecord(domain, name, rtype, data string, priority, ttl int) error { - values := url.Values{ - "domain": {domain}, - "name": {name}, - "type": {rtype}, - "data": {data}, - "priority": {fmt.Sprintf("%v", priority)}, - "ttl": {fmt.Sprintf("%v", ttl)}, - } - - if err := c.post(`dns/create_record`, values, nil); err != nil { - return err - } - return nil -} - -// UpdateDNSRecord updates an existing DNS record -func (c *Client) UpdateDNSRecord(domain string, dnsrecord DNSRecord) error { - values := url.Values{ - "domain": {domain}, - "RECORDID": {fmt.Sprintf("%v", dnsrecord.RecordID)}, - } - - if dnsrecord.Name != "" { - values.Add("name", dnsrecord.Name) - } - if dnsrecord.Data != "" { - values.Add("data", dnsrecord.Data) - } - if dnsrecord.Priority != 0 { - values.Add("priority", fmt.Sprintf("%v", dnsrecord.Priority)) - } - if dnsrecord.TTL != 0 { - values.Add("ttl", fmt.Sprintf("%v", dnsrecord.TTL)) - } - - if err := c.post(`dns/update_record`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteDNSRecord deletes an existing DNS record -func (c *Client) DeleteDNSRecord(domain string, recordID int) error { - values := url.Values{ - "domain": {domain}, - "RECORDID": {fmt.Sprintf("%v", recordID)}, - } - - if err := c.post(`dns/delete_record`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/firewall.go b/vendor/github.com/JamesClonk/vultr/lib/firewall.go deleted file mode 100644 index c9c54e9d5..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/firewall.go +++ /dev/null @@ -1,248 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net" - "net/url" - "sort" - "strconv" - "strings" -) - -// FirewallGroup represents a firewall group on Vultr -type FirewallGroup struct { - ID string `json:"FIREWALLGROUPID"` - Description string `json:"description"` - Created string `json:"date_created"` - Modified string `json:"date_modified"` - InstanceCount int `json:"instance_count"` - RuleCount int `json:"rule_count"` - MaxRuleCount int `json:"max_rule_count"` -} - -// FirewallRule represents a firewall rule on Vultr -type FirewallRule struct { - RuleNumber int `json:"rulenumber"` - Action string `json:"action"` - Protocol string `json:"protocol"` - Port string `json:"port"` - Network *net.IPNet -} - -type firewallGroups []FirewallGroup - -func (f firewallGroups) Len() int { return len(f) } -func (f firewallGroups) Swap(i, j int) { f[i], f[j] = f[j], f[i] } -func (f firewallGroups) Less(i, j int) bool { - // sort order: description - return strings.ToLower(f[i].Description) < strings.ToLower(f[j].Description) -} - -type firewallRules []FirewallRule - -func (r firewallRules) Len() int { return len(r) } -func (r firewallRules) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r firewallRules) Less(i, j int) bool { - // sort order: rule number - return r[i].RuleNumber < r[j].RuleNumber -} - -// UnmarshalJSON implements json.Unmarshaller on FirewallRule. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (r *FirewallRule) UnmarshalJSON(data []byte) (err error) { - if r == nil { - *r = FirewallRule{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["rulenumber"]) - if len(value) == 0 || value == "" { - value = "0" - } - number, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - r.RuleNumber = int(number) - - value = fmt.Sprintf("%v", fields["subnet_size"]) - if len(value) == 0 || value == "" { - value = "0" - } - subnetSize, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - - r.Action = fmt.Sprintf("%v", fields["action"]) - r.Protocol = fmt.Sprintf("%v", fields["protocol"]) - r.Port = fmt.Sprintf("%v", fields["port"]) - subnet := fmt.Sprintf("%v", fields["subnet"]) - - if subnetSize > 0 && len(subnet) > 0 { - _, r.Network, err = net.ParseCIDR(fmt.Sprintf("%s/%d", subnet, subnetSize)) - if err != nil { - return fmt.Errorf("Failed to parse subnet from Vultr API") - } - } else { - _, r.Network, _ = net.ParseCIDR("0.0.0.0/0") - } - - return -} - -// GetFirewallGroups returns a list of all available firewall groups on Vultr -func (c *Client) GetFirewallGroups() ([]FirewallGroup, error) { - var groupMap map[string]FirewallGroup - if err := c.get(`firewall/group_list`, &groupMap); err != nil { - return nil, err - } - - var groupList []FirewallGroup - for _, g := range groupMap { - groupList = append(groupList, g) - } - sort.Sort(firewallGroups(groupList)) - return groupList, nil -} - -// GetFirewallGroup returns the firewall group with given ID -func (c *Client) GetFirewallGroup(id string) (FirewallGroup, error) { - groups, err := c.GetFirewallGroups() - if err != nil { - return FirewallGroup{}, err - } - - for _, g := range groups { - if g.ID == id { - return g, nil - } - } - return FirewallGroup{}, fmt.Errorf("Firewall group with ID %v not found", id) -} - -// CreateFirewallGroup creates a new firewall group in Vultr account -func (c *Client) CreateFirewallGroup(description string) (string, error) { - values := url.Values{} - - // Optional description - if len(description) > 0 { - values.Add("description", description) - } - - var result FirewallGroup - err := c.post(`firewall/group_create`, values, &result) - if err != nil { - return "", err - } - return result.ID, nil -} - -// DeleteFirewallGroup deletes an existing firewall group -func (c *Client) DeleteFirewallGroup(groupID string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - } - - if err := c.post(`firewall/group_delete`, values, nil); err != nil { - return err - } - return nil -} - -// SetFirewallGroupDescription sets the description of an existing firewall group -func (c *Client) SetFirewallGroupDescription(groupID, description string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - "description": {description}, - } - - if err := c.post(`firewall/group_set_description`, values, nil); err != nil { - return err - } - return nil -} - -// GetFirewallRules returns a list of rules for the given firewall group -func (c *Client) GetFirewallRules(groupID string) ([]FirewallRule, error) { - var ruleMap map[string]FirewallRule - ipTypes := []string{"v4", "v6"} - for _, ipType := range ipTypes { - args := fmt.Sprintf("direction=in&FIREWALLGROUPID=%s&ip_type=%s", - groupID, ipType) - if err := c.get(`firewall/rule_list?`+args, &ruleMap); err != nil { - return nil, err - } - } - - var ruleList []FirewallRule - for _, r := range ruleMap { - ruleList = append(ruleList, r) - } - sort.Sort(firewallRules(ruleList)) - return ruleList, nil -} - -// CreateFirewallRule creates a new firewall rule in Vultr account. -// groupID is the ID of the firewall group to create the rule in -// protocol must be one of: "icmp", "tcp", "udp", "gre" -// port can be a port number or colon separated port range (TCP/UDP only) -func (c *Client) CreateFirewallRule(groupID, protocol, port string, - network *net.IPNet) (int, error) { - ip := network.IP.String() - maskBits, _ := network.Mask.Size() - if ip == "" { - return 0, fmt.Errorf("Invalid network") - } - - var ipType string - if network.IP.To4() != nil { - ipType = "v4" - } else { - ipType = "v6" - } - - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - // possible values: "in" - "direction": {"in"}, - // possible values: "icmp", "tcp", "udp", "gre" - "protocol": {protocol}, - // possible values: "v4", "v6" - "ip_type": {ipType}, - // IP address representing a subnet - "subnet": {ip}, - // IP prefix size in bits - "subnet_size": {fmt.Sprintf("%v", maskBits)}, - } - - if len(port) > 0 { - values.Add("port", port) - } - - var result FirewallRule - err := c.post(`firewall/rule_create`, values, &result) - if err != nil { - return 0, err - } - return result.RuleNumber, nil -} - -// DeleteFirewallRule deletes an existing firewall rule -func (c *Client) DeleteFirewallRule(ruleNumber int, groupID string) error { - values := url.Values{ - "FIREWALLGROUPID": {groupID}, - "rulenumber": {fmt.Sprintf("%v", ruleNumber)}, - } - - if err := c.post(`firewall/rule_delete`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/ip.go b/vendor/github.com/JamesClonk/vultr/lib/ip.go deleted file mode 100644 index 4d169cb3f..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/ip.go +++ /dev/null @@ -1,192 +0,0 @@ -package lib - -import ( - "fmt" - "net/url" - "sort" -) - -// IPv4 information of a virtual machine -type IPv4 struct { - IP string `json:"ip"` - Netmask string `json:"netmask"` - Gateway string `json:"gateway"` - Type string `json:"type"` - ReverseDNS string `json:"reverse"` -} - -type ipv4s []IPv4 - -func (s ipv4s) Len() int { return len(s) } -func (s ipv4s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ipv4s) Less(i, j int) bool { - // sort order: type, ip - if s[i].Type < s[j].Type { - return true - } else if s[i].Type > s[j].Type { - return false - } - return s[i].IP < s[j].IP -} - -// IPv6 information of a virtual machine -type IPv6 struct { - IP string `json:"ip"` - Network string `json:"network"` - NetworkSize string `json:"network_size"` - Type string `json:"type"` -} - -type ipv6s []IPv6 - -func (s ipv6s) Len() int { return len(s) } -func (s ipv6s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ipv6s) Less(i, j int) bool { - // sort order: type, ip - if s[i].Type < s[j].Type { - return true - } else if s[i].Type > s[j].Type { - return false - } - return s[i].IP < s[j].IP -} - -// ReverseDNSIPv6 information of a virtual machine -type ReverseDNSIPv6 struct { - IP string `json:"ip"` - ReverseDNS string `json:"reverse"` -} - -type reverseDNSIPv6s []ReverseDNSIPv6 - -func (s reverseDNSIPv6s) Len() int { return len(s) } -func (s reverseDNSIPv6s) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s reverseDNSIPv6s) Less(i, j int) bool { return s[i].IP < s[j].IP } - -// ListIPv4 lists the IPv4 information of a virtual machine -func (c *Client) ListIPv4(id string) (list []IPv4, err error) { - var ipMap map[string][]IPv4 - if err := c.get(`server/list_ipv4?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(ipv4s(list)) - return list, nil -} - -// CreateIPv4 creates an IPv4 address and attaches it to a virtual machine -func (c *Client) CreateIPv4(id string, reboot bool) error { - values := url.Values{ - "SUBID": {id}, - "reboot": {fmt.Sprintf("%t", reboot)}, - } - - if err := c.post(`server/create_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteIPv4 deletes an IPv4 address and detaches it from a virtual machine -func (c *Client) DeleteIPv4(id, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/destroy_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// ListIPv6 lists the IPv4 information of a virtual machine -func (c *Client) ListIPv6(id string) (list []IPv6, err error) { - var ipMap map[string][]IPv6 - if err := c.get(`server/list_ipv6?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(ipv6s(list)) - return list, nil -} - -// ListIPv6ReverseDNS lists the IPv6 reverse DNS entries of a virtual machine -func (c *Client) ListIPv6ReverseDNS(id string) (list []ReverseDNSIPv6, err error) { - var ipMap map[string][]ReverseDNSIPv6 - if err := c.get(`server/reverse_list_ipv6?SUBID=`+id, &ipMap); err != nil { - return nil, err - } - - for _, iplist := range ipMap { - for _, ip := range iplist { - list = append(list, ip) - } - } - sort.Sort(reverseDNSIPv6s(list)) - return list, nil -} - -// DeleteIPv6ReverseDNS removes a reverse DNS entry for an IPv6 address of a virtual machine -func (c *Client) DeleteIPv6ReverseDNS(id string, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/reverse_delete_ipv6`, values, nil); err != nil { - return err - } - return nil -} - -// SetIPv6ReverseDNS sets a reverse DNS entry for an IPv6 address of a virtual machine -func (c *Client) SetIPv6ReverseDNS(id, ip, entry string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - "entry": {entry}, - } - - if err := c.post(`server/reverse_set_ipv6`, values, nil); err != nil { - return err - } - return nil -} - -// DefaultIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine to the original setting -func (c *Client) DefaultIPv4ReverseDNS(id, ip string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - } - - if err := c.post(`server/reverse_default_ipv4`, values, nil); err != nil { - return err - } - return nil -} - -// SetIPv4ReverseDNS sets a reverse DNS entry for an IPv4 address of a virtual machine -func (c *Client) SetIPv4ReverseDNS(id, ip, entry string) error { - values := url.Values{ - "SUBID": {id}, - "ip": {ip}, - "entry": {entry}, - } - - if err := c.post(`server/reverse_set_ipv4`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/iso.go b/vendor/github.com/JamesClonk/vultr/lib/iso.go deleted file mode 100644 index a9e1880e4..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/iso.go +++ /dev/null @@ -1,44 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// ISO image on Vultr -type ISO struct { - ID int `json:"ISOID"` - Created string `json:"date_created"` - Filename string `json:"filename"` - Size int `json:"size"` - MD5sum string `json:"md5sum"` -} - -type isos []ISO - -func (s isos) Len() int { return len(s) } -func (s isos) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s isos) Less(i, j int) bool { - // sort order: filename, created - if strings.ToLower(s[i].Filename) < strings.ToLower(s[j].Filename) { - return true - } else if strings.ToLower(s[i].Filename) > strings.ToLower(s[j].Filename) { - return false - } - return s[i].Created < s[j].Created -} - -// GetISO returns a list of all ISO images on Vultr account -func (c *Client) GetISO() ([]ISO, error) { - var isoMap map[string]ISO - if err := c.get(`iso/list`, &isoMap); err != nil { - return nil, err - } - - var isoList []ISO - for _, iso := range isoMap { - isoList = append(isoList, iso) - } - sort.Sort(isos(isoList)) - return isoList, nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/os.go b/vendor/github.com/JamesClonk/vultr/lib/os.go deleted file mode 100644 index 647d253f8..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/os.go +++ /dev/null @@ -1,37 +0,0 @@ -package lib - -import ( - "sort" - "strings" -) - -// OS image on Vultr -type OS struct { - ID int `json:"OSID"` - Name string `json:"name"` - Arch string `json:"arch"` - Family string `json:"family"` - Windows bool `json:"windows"` - Surcharge string `json:"surcharge"` -} - -type oses []OS - -func (s oses) Len() int { return len(s) } -func (s oses) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s oses) Less(i, j int) bool { return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) } - -// GetOS returns a list of all available operating systems on Vultr -func (c *Client) GetOS() ([]OS, error) { - var osMap map[string]OS - if err := c.get(`os/list`, &osMap); err != nil { - return nil, err - } - - var osList []OS - for _, os := range osMap { - osList = append(osList, os) - } - sort.Sort(oses(osList)) - return osList, nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/plans.go b/vendor/github.com/JamesClonk/vultr/lib/plans.go deleted file mode 100644 index b3bef4eff..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/plans.go +++ /dev/null @@ -1,78 +0,0 @@ -package lib - -import ( - "fmt" - "sort" - "strconv" - "strings" -) - -// Plan on Vultr -type Plan struct { - ID int `json:"VPSPLANID,string"` - Name string `json:"name"` - VCpus int `json:"vcpu_count,string"` - RAM string `json:"ram"` - Disk string `json:"disk"` - Bandwidth string `json:"bandwidth"` - Price string `json:"price_per_month"` - Regions []int `json:"available_locations"` -} - -type plans []Plan - -func (p plans) Len() int { return len(p) } -func (p plans) Swap(i, j int) { p[i], p[j] = p[j], p[i] } -func (p plans) Less(i, j int) bool { - pa, _ := strconv.ParseFloat(strings.TrimSpace(p[i].Price), 64) - pb, _ := strconv.ParseFloat(strings.TrimSpace(p[j].Price), 64) - ra, _ := strconv.ParseInt(strings.TrimSpace(p[i].RAM), 10, 64) - rb, _ := strconv.ParseInt(strings.TrimSpace(p[j].RAM), 10, 64) - da, _ := strconv.ParseInt(strings.TrimSpace(p[i].Disk), 10, 64) - db, _ := strconv.ParseInt(strings.TrimSpace(p[j].Disk), 10, 64) - - // sort order: price, vcpu, ram, disk - if pa < pb { - return true - } else if pa > pb { - return false - } - - if p[i].VCpus < p[j].VCpus { - return true - } else if p[i].VCpus > p[j].VCpus { - return false - } - - if ra < rb { - return true - } else if ra > rb { - return false - } - - return da < db -} - -// GetPlans returns a list of all available plans on Vultr account -func (c *Client) GetPlans() ([]Plan, error) { - var planMap map[string]Plan - if err := c.get(`plans/list`, &planMap); err != nil { - return nil, err - } - - var p plans - for _, plan := range planMap { - p = append(p, plan) - } - - sort.Sort(plans(p)) - return p, nil -} - -// GetAvailablePlansForRegion returns available plans for specified region -func (c *Client) GetAvailablePlansForRegion(id int) (planIDs []int, err error) { - if err := c.get(fmt.Sprintf(`regions/availability?DCID=%v`, id), &planIDs); err != nil { - return nil, err - } - return -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/regions.go b/vendor/github.com/JamesClonk/vultr/lib/regions.go deleted file mode 100644 index 70ceb2ede..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/regions.go +++ /dev/null @@ -1,44 +0,0 @@ -package lib - -import "sort" - -// Region on Vultr -type Region struct { - ID int `json:"DCID,string"` - Name string `json:"name"` - Country string `json:"country"` - Continent string `json:"continent"` - State string `json:"state"` - Ddos bool `json:"ddos_protection"` - BlockStorage bool `json:"block_storage"` - Code string `json:"regioncode"` -} - -type regions []Region - -func (s regions) Len() int { return len(s) } -func (s regions) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s regions) Less(i, j int) bool { - // sort order: continent, name - if s[i].Continent < s[j].Continent { - return true - } else if s[i].Continent > s[j].Continent { - return false - } - return s[i].Name < s[j].Name -} - -// GetRegions returns a list of all available Vultr regions -func (c *Client) GetRegions() ([]Region, error) { - var regionMap map[string]Region - if err := c.get(`regions/list`, ®ionMap); err != nil { - return nil, err - } - - var regionList []Region - for _, os := range regionMap { - regionList = append(regionList, os) - } - sort.Sort(regions(regionList)) - return regionList, nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/reservedip.go b/vendor/github.com/JamesClonk/vultr/lib/reservedip.go deleted file mode 100644 index 22097cf7d..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/reservedip.go +++ /dev/null @@ -1,192 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// IP on Vultr -type IP struct { - ID string `json:"SUBID,string"` - RegionID int `json:"DCID,string"` - IPType string `json:"ip_type"` - Subnet string `json:"subnet"` - SubnetSize int `json:"subnet_size"` - Label string `json:"label"` - AttachedTo string `json:"attached_SUBID,string"` -} - -type ips []IP - -func (s ips) Len() int { return len(s) } -func (s ips) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s ips) Less(i, j int) bool { - // sort order: label, iptype, subnet - if strings.ToLower(s[i].Label) < strings.ToLower(s[j].Label) { - return true - } else if strings.ToLower(s[i].Label) > strings.ToLower(s[j].Label) { - return false - } - if s[i].IPType < s[j].IPType { - return true - } else if s[i].IPType > s[j].IPType { - return false - } - return s[i].Subnet < s[j].Subnet -} - -// UnmarshalJSON implements json.Unmarshaller on IP. -// This is needed because the Vultr API is inconsistent in it's JSON responses. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (i *IP) UnmarshalJSON(data []byte) (err error) { - if i == nil { - *i = IP{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["SUBID"]) - if len(value) == 0 || value == "" || value == "0" { - i.ID = "" - } else { - id, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - i.ID = strconv.FormatFloat(id, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - i.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["attached_SUBID"]) - if len(value) == 0 || value == "" || value == "0" || value == "false" { - i.AttachedTo = "" - } else { - attached, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - i.AttachedTo = strconv.FormatFloat(attached, 'f', -1, 64) - } - - value = fmt.Sprintf("%v", fields["subnet_size"]) - if len(value) == 0 || value == "" { - value = "0" - } - size, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - i.SubnetSize = int(size) - - i.IPType = fmt.Sprintf("%v", fields["ip_type"]) - i.Subnet = fmt.Sprintf("%v", fields["subnet"]) - i.Label = fmt.Sprintf("%v", fields["label"]) - - return -} - -// ListReservedIP returns a list of all available reserved IPs on Vultr account -func (c *Client) ListReservedIP() ([]IP, error) { - var ipMap map[string]IP - - err := c.get(`reservedip/list`, &ipMap) - if err != nil { - return nil, err - } - - ipList := make([]IP, 0) - for _, ip := range ipMap { - ipList = append(ipList, ip) - } - sort.Sort(ips(ipList)) - return ipList, nil -} - -// GetReservedIP returns reserved IP with given ID -func (c *Client) GetReservedIP(id string) (IP, error) { - var ipMap map[string]IP - - err := c.get(`reservedip/list`, &ipMap) - if err != nil { - return IP{}, err - } - if ip, ok := ipMap[id]; ok { - return ip, nil - } - return IP{}, fmt.Errorf("IP with ID %v not found", id) -} - -// CreateReservedIP creates a new reserved IP on Vultr account -func (c *Client) CreateReservedIP(regionID int, ipType string, label string) (string, error) { - values := url.Values{ - "DCID": {fmt.Sprintf("%v", regionID)}, - "ip_type": {ipType}, - } - if len(label) > 0 { - values.Add("label", label) - } - - result := IP{} - err := c.post(`reservedip/create`, values, &result) - if err != nil { - return "", err - } - return result.ID, nil -} - -// DestroyReservedIP deletes an existing reserved IP -func (c *Client) DestroyReservedIP(id string) error { - values := url.Values{ - "SUBID": {id}, - } - return c.post(`reservedip/destroy`, values, nil) -} - -// AttachReservedIP attaches a reserved IP to a virtual machine -func (c *Client) AttachReservedIP(ip string, serverID string) error { - values := url.Values{ - "ip_address": {ip}, - "attach_SUBID": {serverID}, - } - return c.post(`reservedip/attach`, values, nil) -} - -// DetachReservedIP detaches a reserved IP from an existing virtual machine -func (c *Client) DetachReservedIP(serverID string, ip string) error { - values := url.Values{ - "ip_address": {ip}, - "detach_SUBID": {serverID}, - } - return c.post(`reservedip/detach`, values, nil) -} - -// ConvertReservedIP converts an existing virtual machines IP to a reserved IP -func (c *Client) ConvertReservedIP(serverID string, ip string) (string, error) { - values := url.Values{ - "SUBID": {serverID}, - "ip_address": {ip}, - } - - result := IP{} - err := c.post(`reservedip/convert`, values, &result) - if err != nil { - return "", err - } - return result.ID, err -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/scripts.go b/vendor/github.com/JamesClonk/vultr/lib/scripts.go deleted file mode 100644 index d6639cf1e..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/scripts.go +++ /dev/null @@ -1,126 +0,0 @@ -package lib - -import ( - "encoding/json" - "fmt" - "net/url" - "sort" - "strings" -) - -// StartupScript on Vultr account -type StartupScript struct { - ID string `json:"SCRIPTID"` - Name string `json:"name"` - Type string `json:"type"` - Content string `json:"script"` -} - -type startupscripts []StartupScript - -func (s startupscripts) Len() int { return len(s) } -func (s startupscripts) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s startupscripts) Less(i, j int) bool { - return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) -} - -// UnmarshalJSON implements json.Unmarshaller on StartupScript. -// Necessary because the SCRIPTID field has inconsistent types. -func (s *StartupScript) UnmarshalJSON(data []byte) (err error) { - if s == nil { - *s = StartupScript{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - s.ID = fmt.Sprintf("%v", fields["SCRIPTID"]) - s.Name = fmt.Sprintf("%v", fields["name"]) - s.Type = fmt.Sprintf("%v", fields["type"]) - s.Content = fmt.Sprintf("%v", fields["script"]) - - return -} - -// GetStartupScripts returns a list of all startup scripts on the current Vultr account -func (c *Client) GetStartupScripts() (scripts []StartupScript, err error) { - var scriptMap map[string]StartupScript - if err := c.get(`startupscript/list`, &scriptMap); err != nil { - return nil, err - } - - for _, script := range scriptMap { - if script.Type == "" { - script.Type = "boot" // set default script type - } - scripts = append(scripts, script) - } - sort.Sort(startupscripts(scripts)) - return scripts, nil -} - -// GetStartupScript returns the startup script with the given ID -func (c *Client) GetStartupScript(id string) (StartupScript, error) { - scripts, err := c.GetStartupScripts() - if err != nil { - return StartupScript{}, err - } - - for _, s := range scripts { - if s.ID == id { - return s, nil - } - } - return StartupScript{}, nil -} - -// CreateStartupScript creates a new startup script -func (c *Client) CreateStartupScript(name, content, scriptType string) (StartupScript, error) { - values := url.Values{ - "name": {name}, - "script": {content}, - "type": {scriptType}, - } - - var script StartupScript - if err := c.post(`startupscript/create`, values, &script); err != nil { - return StartupScript{}, err - } - script.Name = name - script.Content = content - script.Type = scriptType - - return script, nil -} - -// UpdateStartupScript updates an existing startup script -func (c *Client) UpdateStartupScript(script StartupScript) error { - values := url.Values{ - "SCRIPTID": {script.ID}, - } - if script.Name != "" { - values.Add("name", script.Name) - } - if script.Content != "" { - values.Add("script", script.Content) - } - - if err := c.post(`startupscript/update`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteStartupScript deletes an existing startup script from Vultr account -func (c *Client) DeleteStartupScript(id string) error { - values := url.Values{ - "SCRIPTID": {id}, - } - - if err := c.post(`startupscript/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/servers.go b/vendor/github.com/JamesClonk/vultr/lib/servers.go deleted file mode 100644 index 418198a71..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/servers.go +++ /dev/null @@ -1,561 +0,0 @@ -package lib - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "net/url" - "sort" - "strconv" - "strings" -) - -// Server (virtual machine) on Vultr account -type Server struct { - ID string `json:"SUBID"` - Name string `json:"label"` - OS string `json:"os"` - RAM string `json:"ram"` - Disk string `json:"disk"` - MainIP string `json:"main_ip"` - VCpus int `json:"vcpu_count,string"` - Location string `json:"location"` - RegionID int `json:"DCID,string"` - DefaultPassword string `json:"default_password"` - Created string `json:"date_created"` - PendingCharges float64 `json:"pending_charges"` - Status string `json:"status"` - Cost string `json:"cost_per_month"` - CurrentBandwidth float64 `json:"current_bandwidth_gb"` - AllowedBandwidth float64 `json:"allowed_bandwidth_gb,string"` - NetmaskV4 string `json:"netmask_v4"` - GatewayV4 string `json:"gateway_v4"` - PowerStatus string `json:"power_status"` - ServerState string `json:"server_state"` - PlanID int `json:"VPSPLANID,string"` - V6Networks []V6Network `json:"v6_networks"` - InternalIP string `json:"internal_ip"` - KVMUrl string `json:"kvm_url"` - AutoBackups string `json:"auto_backups"` - Tag string `json:"tag"` - OSID string `json:"OSID"` - AppID string `json:"APPID"` - FirewallGroupID string `json:"FIREWALLGROUPID"` -} - -// ServerOptions are optional parameters to be used during server creation -type ServerOptions struct { - IPXEChainURL string - ISO int - Script int - UserData string - Snapshot string - SSHKey string - ReservedIP string - IPV6 bool - PrivateNetworking bool - AutoBackups bool - DontNotifyOnActivate bool - Hostname string - Tag string - AppID string - FirewallGroupID string -} - -type servers []Server - -func (s servers) Len() int { return len(s) } -func (s servers) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s servers) Less(i, j int) bool { - // sort order: name, ip - if strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) { - return true - } else if strings.ToLower(s[i].Name) > strings.ToLower(s[j].Name) { - return false - } - return s[i].MainIP < s[j].MainIP -} - -// V6Network represents a IPv6 network of a Vultr server -type V6Network struct { - Network string `json:"v6_network"` - MainIP string `json:"v6_main_ip"` - NetworkSize string `json:"v6_network_size"` -} - -// ISOStatus represents an ISO image attached to a Vultr server -type ISOStatus struct { - State string `json:"state"` - ISOID string `json:"ISOID"` -} - -// UnmarshalJSON implements json.Unmarshaller on Server. -// This is needed because the Vultr API is inconsistent in it's JSON responses for servers. -// Some fields can change type, from JSON number to JSON string and vice-versa. -func (s *Server) UnmarshalJSON(data []byte) (err error) { - if s == nil { - *s = Server{} - } - - var fields map[string]interface{} - if err := json.Unmarshal(data, &fields); err != nil { - return err - } - - value := fmt.Sprintf("%v", fields["vcpu_count"]) - if len(value) == 0 || value == "" { - value = "0" - } - vcpu, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.VCpus = int(vcpu) - - value = fmt.Sprintf("%v", fields["DCID"]) - if len(value) == 0 || value == "" { - value = "0" - } - region, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.RegionID = int(region) - - value = fmt.Sprintf("%v", fields["VPSPLANID"]) - if len(value) == 0 || value == "" { - value = "0" - } - plan, err := strconv.ParseInt(value, 10, 64) - if err != nil { - return err - } - s.PlanID = int(plan) - - value = fmt.Sprintf("%v", fields["pending_charges"]) - if len(value) == 0 || value == "" { - value = "0" - } - pc, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.PendingCharges = pc - - value = fmt.Sprintf("%v", fields["current_bandwidth_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - cb, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.CurrentBandwidth = cb - - value = fmt.Sprintf("%v", fields["allowed_bandwidth_gb"]) - if len(value) == 0 || value == "" { - value = "0" - } - ab, err := strconv.ParseFloat(value, 64) - if err != nil { - return err - } - s.AllowedBandwidth = ab - - value = fmt.Sprintf("%v", fields["OSID"]) - if value == "" { - value = "" - } - s.OSID = value - - value = fmt.Sprintf("%v", fields["APPID"]) - if value == "" || value == "0" { - value = "" - } - s.AppID = value - - value = fmt.Sprintf("%v", fields["FIREWALLGROUPID"]) - if value == "" || value == "0" { - value = "" - } - s.FirewallGroupID = value - - s.ID = fmt.Sprintf("%v", fields["SUBID"]) - s.Name = fmt.Sprintf("%v", fields["label"]) - s.OS = fmt.Sprintf("%v", fields["os"]) - s.RAM = fmt.Sprintf("%v", fields["ram"]) - s.Disk = fmt.Sprintf("%v", fields["disk"]) - s.MainIP = fmt.Sprintf("%v", fields["main_ip"]) - s.Location = fmt.Sprintf("%v", fields["location"]) - s.DefaultPassword = fmt.Sprintf("%v", fields["default_password"]) - s.Created = fmt.Sprintf("%v", fields["date_created"]) - s.Status = fmt.Sprintf("%v", fields["status"]) - s.Cost = fmt.Sprintf("%v", fields["cost_per_month"]) - s.NetmaskV4 = fmt.Sprintf("%v", fields["netmask_v4"]) - s.GatewayV4 = fmt.Sprintf("%v", fields["gateway_v4"]) - s.PowerStatus = fmt.Sprintf("%v", fields["power_status"]) - s.ServerState = fmt.Sprintf("%v", fields["server_state"]) - - v6networks := make([]V6Network, 0) - if networks, ok := fields["v6_networks"].([]interface{}); ok { - for _, network := range networks { - if network, ok := network.(map[string]interface{}); ok { - v6network := V6Network{ - Network: fmt.Sprintf("%v", network["v6_network"]), - MainIP: fmt.Sprintf("%v", network["v6_main_ip"]), - NetworkSize: fmt.Sprintf("%v", network["v6_network_size"]), - } - v6networks = append(v6networks, v6network) - } - } - s.V6Networks = v6networks - } - - s.InternalIP = fmt.Sprintf("%v", fields["internal_ip"]) - s.KVMUrl = fmt.Sprintf("%v", fields["kvm_url"]) - s.AutoBackups = fmt.Sprintf("%v", fields["auto_backups"]) - s.Tag = fmt.Sprintf("%v", fields["tag"]) - - return -} - -// GetServers returns a list of current virtual machines on Vultr account -func (c *Client) GetServers() (serverList []Server, err error) { - var serverMap map[string]Server - if err := c.get(`server/list`, &serverMap); err != nil { - return nil, err - } - - for _, server := range serverMap { - serverList = append(serverList, server) - } - sort.Sort(servers(serverList)) - return serverList, nil -} - -// GetServersByTag returns a list of all virtual machines matching by tag -func (c *Client) GetServersByTag(tag string) (serverList []Server, err error) { - var serverMap map[string]Server - if err := c.get(`server/list?tag=`+tag, &serverMap); err != nil { - return nil, err - } - - for _, server := range serverMap { - serverList = append(serverList, server) - } - sort.Sort(servers(serverList)) - return serverList, nil -} - -// GetServer returns the virtual machine with the given ID -func (c *Client) GetServer(id string) (server Server, err error) { - if err := c.get(`server/list?SUBID=`+id, &server); err != nil { - return Server{}, err - } - return server, nil -} - -// CreateServer creates a new virtual machine on Vultr. ServerOptions are optional settings. -func (c *Client) CreateServer(name string, regionID, planID, osID int, options *ServerOptions) (Server, error) { - values := url.Values{ - "label": {name}, - "DCID": {fmt.Sprintf("%v", regionID)}, - "VPSPLANID": {fmt.Sprintf("%v", planID)}, - "OSID": {fmt.Sprintf("%v", osID)}, - } - - if options != nil { - if options.IPXEChainURL != "" { - values.Add("ipxe_chain_url", options.IPXEChainURL) - } - - if options.ISO != 0 { - values.Add("ISOID", fmt.Sprintf("%v", options.ISO)) - } - - if options.Script != 0 { - values.Add("SCRIPTID", fmt.Sprintf("%v", options.Script)) - } - - if options.UserData != "" { - values.Add("userdata", base64.StdEncoding.EncodeToString([]byte(options.UserData))) - } - - if options.Snapshot != "" { - values.Add("SNAPSHOTID", options.Snapshot) - } - - if options.SSHKey != "" { - values.Add("SSHKEYID", options.SSHKey) - } - - if options.ReservedIP != "" { - values.Add("reserved_ip_v4", options.ReservedIP) - } - - values.Add("enable_ipv6", "no") - if options.IPV6 { - values.Set("enable_ipv6", "yes") - } - - values.Add("enable_private_network", "no") - if options.PrivateNetworking { - values.Set("enable_private_network", "yes") - } - - values.Add("auto_backups", "no") - if options.AutoBackups { - values.Set("auto_backups", "yes") - } - - values.Add("notify_activate", "yes") - if options.DontNotifyOnActivate { - values.Set("notify_activate", "no") - } - - if options.Hostname != "" { - values.Add("hostname", options.Hostname) - } - - if options.Tag != "" { - values.Add("tag", options.Tag) - } - - if options.AppID != "" { - values.Add("APPID", options.AppID) - } - - if options.FirewallGroupID != "" { - values.Add("FIREWALLGROUPID", options.FirewallGroupID) - } - } - - var server Server - if err := c.post(`server/create`, values, &server); err != nil { - return Server{}, err - } - server.Name = name - server.RegionID = regionID - server.PlanID = planID - - return server, nil -} - -// RenameServer renames an existing virtual machine -func (c *Client) RenameServer(id, name string) error { - values := url.Values{ - "SUBID": {id}, - "label": {name}, - } - - if err := c.post(`server/label_set`, values, nil); err != nil { - return err - } - return nil -} - -// TagServer replaces the tag on an existing virtual machine -func (c *Client) TagServer(id, tag string) error { - values := url.Values{ - "SUBID": {id}, - "tag": {tag}, - } - - if err := c.post(`server/tag_set`, values, nil); err != nil { - return err - } - return nil -} - -// StartServer starts an existing virtual machine -func (c *Client) StartServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/start`, values, nil); err != nil { - return err - } - return nil -} - -// HaltServer stops an existing virtual machine -func (c *Client) HaltServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/halt`, values, nil); err != nil { - return err - } - return nil -} - -// RebootServer reboots an existing virtual machine -func (c *Client) RebootServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/reboot`, values, nil); err != nil { - return err - } - return nil -} - -// ReinstallServer reinstalls the operating system on an existing virtual machine -func (c *Client) ReinstallServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/reinstall`, values, nil); err != nil { - return err - } - return nil -} - -// ChangeOSofServer changes the virtual machine to a different operating system -func (c *Client) ChangeOSofServer(id string, osID int) error { - values := url.Values{ - "SUBID": {id}, - "OSID": {fmt.Sprintf("%v", osID)}, - } - - if err := c.post(`server/os_change`, values, nil); err != nil { - return err - } - return nil -} - -// ListOSforServer lists all available operating systems to which an existing virtual machine can be changed -func (c *Client) ListOSforServer(id string) (os []OS, err error) { - var osMap map[string]OS - if err := c.get(`server/os_change_list?SUBID=`+id, &osMap); err != nil { - return nil, err - } - - for _, o := range osMap { - os = append(os, o) - } - sort.Sort(oses(os)) - return os, nil -} - -// AttachISOtoServer attaches an ISO image to an existing virtual machine and reboots it -func (c *Client) AttachISOtoServer(id string, isoID int) error { - values := url.Values{ - "SUBID": {id}, - "ISOID": {fmt.Sprintf("%v", isoID)}, - } - - if err := c.post(`server/iso_attach`, values, nil); err != nil { - return err - } - return nil -} - -// DetachISOfromServer detaches the currently mounted ISO image from the virtual machine and reboots it -func (c *Client) DetachISOfromServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/iso_detach`, values, nil); err != nil { - return err - } - return nil -} - -// GetISOStatusofServer retrieves the current ISO image state of an existing virtual machine -func (c *Client) GetISOStatusofServer(id string) (isoStatus ISOStatus, err error) { - if err := c.get(`server/iso_status?SUBID=`+id, &isoStatus); err != nil { - return ISOStatus{}, err - } - return isoStatus, nil -} - -// DeleteServer deletes an existing virtual machine -func (c *Client) DeleteServer(id string) error { - values := url.Values{ - "SUBID": {id}, - } - - if err := c.post(`server/destroy`, values, nil); err != nil { - return err - } - return nil -} - -// SetFirewallGroup adds a virtual machine to a firewall group -func (c *Client) SetFirewallGroup(id, firewallgroup string) error { - values := url.Values{ - "SUBID": {id}, - "FIREWALLGROUPID": {firewallgroup}, - } - - if err := c.post(`server/firewall_group_set`, values, nil); err != nil { - return err - } - return nil -} - -// UnsetFirewallGroup removes a virtual machine from a firewall group -func (c *Client) UnsetFirewallGroup(id string) error { - return c.SetFirewallGroup(id, "0") -} - -// BandwidthOfServer retrieves the bandwidth used by a virtual machine -func (c *Client) BandwidthOfServer(id string) (bandwidth []map[string]string, err error) { - var bandwidthMap map[string][][]string - if err := c.get(`server/bandwidth?SUBID=`+id, &bandwidthMap); err != nil { - return nil, err - } - - // parse incoming bytes - for _, b := range bandwidthMap["incoming_bytes"] { - bMap := make(map[string]string) - bMap["date"] = b[0] - bMap["incoming"] = b[1] - bandwidth = append(bandwidth, bMap) - } - - // parse outgoing bytes (we'll assume that incoming and outgoing dates are always a match) - for _, b := range bandwidthMap["outgoing_bytes"] { - for i := range bandwidth { - if bandwidth[i]["date"] == b[0] { - bandwidth[i]["outgoing"] = b[1] - break - } - } - } - - return bandwidth, nil -} - -// ChangeApplicationofServer changes the virtual machine to a different application -func (c *Client) ChangeApplicationofServer(id string, appID string) error { - values := url.Values{ - "SUBID": {id}, - "APPID": {appID}, - } - - if err := c.post(`server/app_change`, values, nil); err != nil { - return err - } - return nil -} - -// ListApplicationsforServer lists all available operating systems to which an existing virtual machine can be changed -func (c *Client) ListApplicationsforServer(id string) (apps []Application, err error) { - var appMap map[string]Application - if err := c.get(`server/app_change_list?SUBID=`+id, &appMap); err != nil { - return nil, err - } - - for _, app := range appMap { - apps = append(apps, app) - } - sort.Sort(applications(apps)) - return apps, nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/snapshots.go b/vendor/github.com/JamesClonk/vultr/lib/snapshots.go deleted file mode 100644 index 7e9969306..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/snapshots.go +++ /dev/null @@ -1,72 +0,0 @@ -package lib - -import ( - "net/url" - "sort" - "strings" -) - -// Snapshot of a virtual machine on Vultr account -type Snapshot struct { - ID string `json:"SNAPSHOTID"` - Description string `json:"description"` - Size string `json:"size"` - Status string `json:"status"` - Created string `json:"date_created"` -} - -type snapshots []Snapshot - -func (s snapshots) Len() int { return len(s) } -func (s snapshots) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s snapshots) Less(i, j int) bool { - // sort order: description, created - if strings.ToLower(s[i].Description) < strings.ToLower(s[j].Description) { - return true - } else if strings.ToLower(s[i].Description) > strings.ToLower(s[j].Description) { - return false - } - return s[i].Created < s[j].Created -} - -// GetSnapshots retrieves a list of all snapshots on Vultr account -func (c *Client) GetSnapshots() (snapshotList []Snapshot, err error) { - var snapshotMap map[string]Snapshot - if err := c.get(`snapshot/list`, &snapshotMap); err != nil { - return nil, err - } - - for _, snapshot := range snapshotMap { - snapshotList = append(snapshotList, snapshot) - } - sort.Sort(snapshots(snapshotList)) - return snapshotList, nil -} - -// CreateSnapshot creates a new virtual machine snapshot -func (c *Client) CreateSnapshot(id, description string) (Snapshot, error) { - values := url.Values{ - "SUBID": {id}, - "description": {description}, - } - - var snapshot Snapshot - if err := c.post(`snapshot/create`, values, &snapshot); err != nil { - return Snapshot{}, err - } - snapshot.Description = description - - return snapshot, nil -} - -// DeleteSnapshot deletes an existing virtual machine snapshot -func (c *Client) DeleteSnapshot(id string) error { - values := url.Values{ - "SNAPSHOTID": {id}, - } - - if err := c.post(`snapshot/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go b/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go deleted file mode 100644 index 006e16f2d..000000000 --- a/vendor/github.com/JamesClonk/vultr/lib/sshkeys.go +++ /dev/null @@ -1,82 +0,0 @@ -package lib - -import ( - "net/url" - "sort" - "strings" -) - -// SSHKey on Vultr account -type SSHKey struct { - ID string `json:"SSHKEYID"` - Name string `json:"name"` - Key string `json:"ssh_key"` - Created string `json:"date_created"` -} - -type sshkeys []SSHKey - -func (s sshkeys) Len() int { return len(s) } -func (s sshkeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] } -func (s sshkeys) Less(i, j int) bool { return strings.ToLower(s[i].Name) < strings.ToLower(s[j].Name) } - -// GetSSHKeys returns a list of SSHKeys from Vultr account -func (c *Client) GetSSHKeys() (keys []SSHKey, err error) { - var keyMap map[string]SSHKey - if err := c.get(`sshkey/list`, &keyMap); err != nil { - return nil, err - } - - for _, key := range keyMap { - keys = append(keys, key) - } - sort.Sort(sshkeys(keys)) - return keys, nil -} - -// CreateSSHKey creates new SSHKey on Vultr -func (c *Client) CreateSSHKey(name, key string) (SSHKey, error) { - values := url.Values{ - "name": {name}, - "ssh_key": {key}, - } - - var sshKey SSHKey - if err := c.post(`sshkey/create`, values, &sshKey); err != nil { - return SSHKey{}, err - } - sshKey.Name = name - sshKey.Key = key - - return sshKey, nil -} - -// UpdateSSHKey updates an existing SSHKey entry -func (c *Client) UpdateSSHKey(key SSHKey) error { - values := url.Values{ - "SSHKEYID": {key.ID}, - } - if key.Name != "" { - values.Add("name", key.Name) - } - if key.Key != "" { - values.Add("ssh_key", key.Key) - } - - if err := c.post(`sshkey/update`, values, nil); err != nil { - return err - } - return nil -} - -// DeleteSSHKey deletes an existing SSHKey from Vultr account -func (c *Client) DeleteSSHKey(id string) error { - values := url.Values{ - "SSHKEYID": {id}, - } - - if err := c.post(`sshkey/destroy`, values, nil); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/Masterminds/goutils/LICENSE.txt b/vendor/github.com/Masterminds/goutils/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/Masterminds/goutils/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/Masterminds/goutils/cryptorandomstringutils.go b/vendor/github.com/Masterminds/goutils/cryptorandomstringutils.go deleted file mode 100644 index 177dd8658..000000000 --- a/vendor/github.com/Masterminds/goutils/cryptorandomstringutils.go +++ /dev/null @@ -1,251 +0,0 @@ -/* -Copyright 2014 Alexander Okoli - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package goutils - -import ( - "crypto/rand" - "fmt" - "math" - "math/big" - "regexp" - "unicode" -) - -/* -CryptoRandomNonAlphaNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)). - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomNonAlphaNumeric(count int) (string, error) { - return CryptoRandomAlphaNumericCustom(count, false, false) -} - -/* -CryptoRandomAscii creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive). - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomAscii(count int) (string, error) { - return CryptoRandom(count, 32, 127, false, false) -} - -/* -CryptoRandomNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of numeric characters. - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomNumeric(count int) (string, error) { - return CryptoRandom(count, 0, 0, false, true) -} - -/* -CryptoRandomAlphabetic creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - -Parameters: - count - the length of random string to create - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomAlphabetic(count int) (string, error) { - return CryptoRandom(count, 0, 0, true, false) -} - -/* -CryptoRandomAlphaNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters. - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomAlphaNumeric(count int) (string, error) { - if count == 0 { - return "", nil - } - RandomString, err := CryptoRandom(count, 0, 0, true, true) - if err != nil { - return "", fmt.Errorf("Error: %s", err) - } - match, err := regexp.MatchString("([0-9]+)", RandomString) - if err != nil { - panic(err) - } - - if !match { - //Get the position between 0 and the length of the string-1 to insert a random number - position := getCryptoRandomInt(count) - //Insert a random number between [0-9] in the position - RandomString = RandomString[:position] + string('0' + getCryptoRandomInt(10)) + RandomString[position + 1:] - return RandomString, err - } - return RandomString, err - -} - -/* -CryptoRandomAlphaNumericCustom creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - -Parameters: - count - the length of random string to create - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, CryptoRandom(...) -*/ -func CryptoRandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) { - return CryptoRandom(count, 0, 0, letters, numbers) -} - -/* -CryptoRandom creates a random string based on a variety of options, using using golang's crypto/rand source of randomness. -If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used, -unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively. -If chars is not nil, characters stored in chars that are between start and end are chosen. - -Parameters: - count - the length of random string to create - start - the position in set of chars (ASCII/Unicode int) to start at - end - the position in set of chars (ASCII/Unicode int) to end before - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. - -Returns: - string - the random string - error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars) -*/ -func CryptoRandom(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) { - if count == 0 { - return "", nil - } else if count < 0 { - err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...") - return "", err - } - if chars != nil && len(chars) == 0 { - err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty") - return "", err - } - - if start == 0 && end == 0 { - if chars != nil { - end = len(chars) - } else { - if !letters && !numbers { - end = math.MaxInt32 - } else { - end = 'z' + 1 - start = ' ' - } - } - } else { - if end <= start { - err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start) - return "", err - } - - if chars != nil && end > len(chars) { - err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars)) - return "", err - } - } - - buffer := make([]rune, count) - gap := end - start - - // high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319 - // low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343 - - for count != 0 { - count-- - var ch rune - if chars == nil { - ch = rune(getCryptoRandomInt(gap) + int64(start)) - } else { - ch = chars[getCryptoRandomInt(gap) + int64(start)] - } - - if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers { - if ch >= 56320 && ch <= 57343 { // low surrogate range - if count == 0 { - count++ - } else { - // Insert low surrogate - buffer[count] = ch - count-- - // Insert high surrogate - buffer[count] = rune(55296 + getCryptoRandomInt(128)) - } - } else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial) - if count == 0 { - count++ - } else { - // Insert low surrogate - buffer[count] = rune(56320 + getCryptoRandomInt(128)) - count-- - // Insert high surrogate - buffer[count] = ch - } - } else if ch >= 56192 && ch <= 56319 { - // private high surrogate, skip it - count++ - } else { - // not one of the surrogates* - buffer[count] = ch - } - } else { - count++ - } - } - return string(buffer), nil -} - -func getCryptoRandomInt(count int) int64 { - nBig, err := rand.Int(rand.Reader, big.NewInt(int64(count))) - if err != nil { - panic(err) - } - return nBig.Int64() -} diff --git a/vendor/github.com/Masterminds/goutils/randomstringutils.go b/vendor/github.com/Masterminds/goutils/randomstringutils.go deleted file mode 100644 index 1364e0caf..000000000 --- a/vendor/github.com/Masterminds/goutils/randomstringutils.go +++ /dev/null @@ -1,268 +0,0 @@ -/* -Copyright 2014 Alexander Okoli - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package goutils - -import ( - "fmt" - "math" - "math/rand" - "regexp" - "time" - "unicode" -) - -// RANDOM provides the time-based seed used to generate random numbers -var RANDOM = rand.New(rand.NewSource(time.Now().UnixNano())) - -/* -RandomNonAlphaNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of all characters (ASCII/Unicode values between 0 to 2,147,483,647 (math.MaxInt32)). - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomNonAlphaNumeric(count int) (string, error) { - return RandomAlphaNumericCustom(count, false, false) -} - -/* -RandomAscii creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of characters whose ASCII value is between 32 and 126 (inclusive). - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomAscii(count int) (string, error) { - return Random(count, 32, 127, false, false) -} - -/* -RandomNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of numeric characters. - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomNumeric(count int) (string, error) { - return Random(count, 0, 0, false, true) -} - -/* -RandomAlphabetic creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - -Parameters: - count - the length of random string to create - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomAlphabetic(count int) (string, error) { - return Random(count, 0, 0, true, false) -} - -/* -RandomAlphaNumeric creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters. - -Parameter: - count - the length of random string to create - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomAlphaNumeric(count int) (string, error) { - RandomString, err := Random(count, 0, 0, true, true) - if err != nil { - return "", fmt.Errorf("Error: %s", err) - } - match, err := regexp.MatchString("([0-9]+)", RandomString) - if err != nil { - panic(err) - } - - if !match { - //Get the position between 0 and the length of the string-1 to insert a random number - position := rand.Intn(count) - //Insert a random number between [0-9] in the position - RandomString = RandomString[:position] + string('0'+rand.Intn(10)) + RandomString[position+1:] - return RandomString, err - } - return RandomString, err - -} - -/* -RandomAlphaNumericCustom creates a random string whose length is the number of characters specified. -Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. - -Parameters: - count - the length of random string to create - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func RandomAlphaNumericCustom(count int, letters bool, numbers bool) (string, error) { - return Random(count, 0, 0, letters, numbers) -} - -/* -Random creates a random string based on a variety of options, using default source of randomness. -This method has exactly the same semantics as RandomSeed(int, int, int, bool, bool, []char, *rand.Rand), but -instead of using an externally supplied source of randomness, it uses the internal *rand.Rand instance. - -Parameters: - count - the length of random string to create - start - the position in set of chars (ASCII/Unicode int) to start at - end - the position in set of chars (ASCII/Unicode int) to end before - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. - -Returns: - string - the random string - error - an error stemming from an invalid parameter within underlying function, RandomSeed(...) -*/ -func Random(count int, start int, end int, letters bool, numbers bool, chars ...rune) (string, error) { - return RandomSeed(count, start, end, letters, numbers, chars, RANDOM) -} - -/* -RandomSeed creates a random string based on a variety of options, using supplied source of randomness. -If the parameters start and end are both 0, start and end are set to ' ' and 'z', the ASCII printable characters, will be used, -unless letters and numbers are both false, in which case, start and end are set to 0 and math.MaxInt32, respectively. -If chars is not nil, characters stored in chars that are between start and end are chosen. -This method accepts a user-supplied *rand.Rand instance to use as a source of randomness. By seeding a single *rand.Rand instance -with a fixed seed and using it for each call, the same random sequence of strings can be generated repeatedly and predictably. - -Parameters: - count - the length of random string to create - start - the position in set of chars (ASCII/Unicode decimals) to start at - end - the position in set of chars (ASCII/Unicode decimals) to end before - letters - if true, generated string may include alphabetic characters - numbers - if true, generated string may include numeric characters - chars - the set of chars to choose randoms from. If nil, then it will use the set of all chars. - random - a source of randomness. - -Returns: - string - the random string - error - an error stemming from invalid parameters: if count < 0; or the provided chars array is empty; or end <= start; or end > len(chars) -*/ -func RandomSeed(count int, start int, end int, letters bool, numbers bool, chars []rune, random *rand.Rand) (string, error) { - - if count == 0 { - return "", nil - } else if count < 0 { - err := fmt.Errorf("randomstringutils illegal argument: Requested random string length %v is less than 0.", count) // equiv to err := errors.New("...") - return "", err - } - if chars != nil && len(chars) == 0 { - err := fmt.Errorf("randomstringutils illegal argument: The chars array must not be empty") - return "", err - } - - if start == 0 && end == 0 { - if chars != nil { - end = len(chars) - } else { - if !letters && !numbers { - end = math.MaxInt32 - } else { - end = 'z' + 1 - start = ' ' - } - } - } else { - if end <= start { - err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) must be greater than start (%v)", end, start) - return "", err - } - - if chars != nil && end > len(chars) { - err := fmt.Errorf("randomstringutils illegal argument: Parameter end (%v) cannot be greater than len(chars) (%v)", end, len(chars)) - return "", err - } - } - - buffer := make([]rune, count) - gap := end - start - - // high-surrogates range, (\uD800-\uDBFF) = 55296 - 56319 - // low-surrogates range, (\uDC00-\uDFFF) = 56320 - 57343 - - for count != 0 { - count-- - var ch rune - if chars == nil { - ch = rune(random.Intn(gap) + start) - } else { - ch = chars[random.Intn(gap)+start] - } - - if letters && unicode.IsLetter(ch) || numbers && unicode.IsDigit(ch) || !letters && !numbers { - if ch >= 56320 && ch <= 57343 { // low surrogate range - if count == 0 { - count++ - } else { - // Insert low surrogate - buffer[count] = ch - count-- - // Insert high surrogate - buffer[count] = rune(55296 + random.Intn(128)) - } - } else if ch >= 55296 && ch <= 56191 { // High surrogates range (Partial) - if count == 0 { - count++ - } else { - // Insert low surrogate - buffer[count] = rune(56320 + random.Intn(128)) - count-- - // Insert high surrogate - buffer[count] = ch - } - } else if ch >= 56192 && ch <= 56319 { - // private high surrogate, skip it - count++ - } else { - // not one of the surrogates* - buffer[count] = ch - } - } else { - count++ - } - } - return string(buffer), nil -} diff --git a/vendor/github.com/Masterminds/goutils/stringutils.go b/vendor/github.com/Masterminds/goutils/stringutils.go deleted file mode 100644 index 5037c4516..000000000 --- a/vendor/github.com/Masterminds/goutils/stringutils.go +++ /dev/null @@ -1,224 +0,0 @@ -/* -Copyright 2014 Alexander Okoli - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package goutils - -import ( - "bytes" - "fmt" - "strings" - "unicode" -) - -// Typically returned by functions where a searched item cannot be found -const INDEX_NOT_FOUND = -1 - -/* -Abbreviate abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "Now is the time for..." - -Specifically, the algorithm is as follows: - - - If str is less than maxWidth characters long, return it. - - Else abbreviate it to (str[0:maxWidth - 3] + "..."). - - If maxWidth is less than 4, return an illegal argument error. - - In no case will it return a string of length greater than maxWidth. - -Parameters: - str - the string to check - maxWidth - maximum length of result string, must be at least 4 - -Returns: - string - abbreviated string - error - if the width is too small -*/ -func Abbreviate(str string, maxWidth int) (string, error) { - return AbbreviateFull(str, 0, maxWidth) -} - -/* -AbbreviateFull abbreviates a string using ellipses. This will turn the string "Now is the time for all good men" into "...is the time for..." -This function works like Abbreviate(string, int), but allows you to specify a "left edge" offset. Note that this left edge is not -necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear -somewhere in the result. -In no case will it return a string of length greater than maxWidth. - -Parameters: - str - the string to check - offset - left edge of source string - maxWidth - maximum length of result string, must be at least 4 - -Returns: - string - abbreviated string - error - if the width is too small -*/ -func AbbreviateFull(str string, offset int, maxWidth int) (string, error) { - if str == "" { - return "", nil - } - if maxWidth < 4 { - err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width is 4") - return "", err - } - if len(str) <= maxWidth { - return str, nil - } - if offset > len(str) { - offset = len(str) - } - if len(str)-offset < (maxWidth - 3) { // 15 - 5 < 10 - 3 = 10 < 7 - offset = len(str) - (maxWidth - 3) - } - abrevMarker := "..." - if offset <= 4 { - return str[0:maxWidth-3] + abrevMarker, nil // str.substring(0, maxWidth - 3) + abrevMarker; - } - if maxWidth < 7 { - err := fmt.Errorf("stringutils illegal argument: Minimum abbreviation width with offset is 7") - return "", err - } - if (offset + maxWidth - 3) < len(str) { // 5 + (10-3) < 15 = 12 < 15 - abrevStr, _ := Abbreviate(str[offset:len(str)], (maxWidth - 3)) - return abrevMarker + abrevStr, nil // abrevMarker + abbreviate(str.substring(offset), maxWidth - 3); - } - return abrevMarker + str[(len(str)-(maxWidth-3)):len(str)], nil // abrevMarker + str.substring(str.length() - (maxWidth - 3)); -} - -/* -DeleteWhiteSpace deletes all whitespaces from a string as defined by unicode.IsSpace(rune). -It returns the string without whitespaces. - -Parameter: - str - the string to delete whitespace from, may be nil - -Returns: - the string without whitespaces -*/ -func DeleteWhiteSpace(str string) string { - if str == "" { - return str - } - sz := len(str) - var chs bytes.Buffer - count := 0 - for i := 0; i < sz; i++ { - ch := rune(str[i]) - if !unicode.IsSpace(ch) { - chs.WriteRune(ch) - count++ - } - } - if count == sz { - return str - } - return chs.String() -} - -/* -IndexOfDifference compares two strings, and returns the index at which the strings begin to differ. - -Parameters: - str1 - the first string - str2 - the second string - -Returns: - the index where str1 and str2 begin to differ; -1 if they are equal -*/ -func IndexOfDifference(str1 string, str2 string) int { - if str1 == str2 { - return INDEX_NOT_FOUND - } - if IsEmpty(str1) || IsEmpty(str2) { - return 0 - } - var i int - for i = 0; i < len(str1) && i < len(str2); i++ { - if rune(str1[i]) != rune(str2[i]) { - break - } - } - if i < len(str2) || i < len(str1) { - return i - } - return INDEX_NOT_FOUND -} - -/* -IsBlank checks if a string is whitespace or empty (""). Observe the following behavior: - - goutils.IsBlank("") = true - goutils.IsBlank(" ") = true - goutils.IsBlank("bob") = false - goutils.IsBlank(" bob ") = false - -Parameter: - str - the string to check - -Returns: - true - if the string is whitespace or empty ("") -*/ -func IsBlank(str string) bool { - strLen := len(str) - if str == "" || strLen == 0 { - return true - } - for i := 0; i < strLen; i++ { - if unicode.IsSpace(rune(str[i])) == false { - return false - } - } - return true -} - -/* -IndexOf returns the index of the first instance of sub in str, with the search beginning from the -index start point specified. -1 is returned if sub is not present in str. - -An empty string ("") will return -1 (INDEX_NOT_FOUND). A negative start position is treated as zero. -A start position greater than the string length returns -1. - -Parameters: - str - the string to check - sub - the substring to find - start - the start position; negative treated as zero - -Returns: - the first index where the sub string was found (always >= start) -*/ -func IndexOf(str string, sub string, start int) int { - - if start < 0 { - start = 0 - } - - if len(str) < start { - return INDEX_NOT_FOUND - } - - if IsEmpty(str) || IsEmpty(sub) { - return INDEX_NOT_FOUND - } - - partialIndex := strings.Index(str[start:len(str)], sub) - if partialIndex == -1 { - return INDEX_NOT_FOUND - } - return partialIndex + start -} - -// IsEmpty checks if a string is empty (""). Returns true if empty, and false otherwise. -func IsEmpty(str string) bool { - return len(str) == 0 -} diff --git a/vendor/github.com/Masterminds/goutils/wordutils.go b/vendor/github.com/Masterminds/goutils/wordutils.go deleted file mode 100644 index 034cad8e2..000000000 --- a/vendor/github.com/Masterminds/goutils/wordutils.go +++ /dev/null @@ -1,357 +0,0 @@ -/* -Copyright 2014 Alexander Okoli - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -/* -Package goutils provides utility functions to manipulate strings in various ways. -The code snippets below show examples of how to use goutils. Some functions return -errors while others do not, so usage would vary as a result. - -Example: - - package main - - import ( - "fmt" - "github.com/aokoli/goutils" - ) - - func main() { - - // EXAMPLE 1: A goutils function which returns no errors - fmt.Println (goutils.Initials("John Doe Foo")) // Prints out "JDF" - - - - // EXAMPLE 2: A goutils function which returns an error - rand1, err1 := goutils.Random (-1, 0, 0, true, true) - - if err1 != nil { - fmt.Println(err1) // Prints out error message because -1 was entered as the first parameter in goutils.Random(...) - } else { - fmt.Println(rand1) - } - } -*/ -package goutils - -import ( - "bytes" - "strings" - "unicode" -) - -// VERSION indicates the current version of goutils -const VERSION = "1.0.0" - -/* -Wrap wraps a single line of text, identifying words by ' '. -New lines will be separated by '\n'. Very long words, such as URLs will not be wrapped. -Leading spaces on a new line are stripped. Trailing spaces are not stripped. - -Parameters: - str - the string to be word wrapped - wrapLength - the column (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 - -Returns: - a line with newlines inserted -*/ -func Wrap(str string, wrapLength int) string { - return WrapCustom(str, wrapLength, "", false) -} - -/* -WrapCustom wraps a single line of text, identifying words by ' '. -Leading spaces on a new line are stripped. Trailing spaces are not stripped. - -Parameters: - str - the string to be word wrapped - wrapLength - the column number (a column can fit only one character) to wrap the words at, less than 1 is treated as 1 - newLineStr - the string to insert for a new line, "" uses '\n' - wrapLongWords - true if long words (such as URLs) should be wrapped - -Returns: - a line with newlines inserted -*/ -func WrapCustom(str string, wrapLength int, newLineStr string, wrapLongWords bool) string { - - if str == "" { - return "" - } - if newLineStr == "" { - newLineStr = "\n" // TODO Assumes "\n" is seperator. Explore SystemUtils.LINE_SEPARATOR from Apache Commons - } - if wrapLength < 1 { - wrapLength = 1 - } - - inputLineLength := len(str) - offset := 0 - - var wrappedLine bytes.Buffer - - for inputLineLength-offset > wrapLength { - - if rune(str[offset]) == ' ' { - offset++ - continue - } - - end := wrapLength + offset + 1 - spaceToWrapAt := strings.LastIndex(str[offset:end], " ") + offset - - if spaceToWrapAt >= offset { - // normal word (not longer than wrapLength) - wrappedLine.WriteString(str[offset:spaceToWrapAt]) - wrappedLine.WriteString(newLineStr) - offset = spaceToWrapAt + 1 - - } else { - // long word or URL - if wrapLongWords { - end := wrapLength + offset - // long words are wrapped one line at a time - wrappedLine.WriteString(str[offset:end]) - wrappedLine.WriteString(newLineStr) - offset += wrapLength - } else { - // long words aren't wrapped, just extended beyond limit - end := wrapLength + offset - index := strings.IndexRune(str[end:len(str)], ' ') - if index == -1 { - wrappedLine.WriteString(str[offset:len(str)]) - offset = inputLineLength - } else { - spaceToWrapAt = index + end - wrappedLine.WriteString(str[offset:spaceToWrapAt]) - wrappedLine.WriteString(newLineStr) - offset = spaceToWrapAt + 1 - } - } - } - } - - wrappedLine.WriteString(str[offset:len(str)]) - - return wrappedLine.String() - -} - -/* -Capitalize capitalizes all the delimiter separated words in a string. Only the first letter of each word is changed. -To convert the rest of each word to lowercase at the same time, use CapitalizeFully(str string, delimiters ...rune). -The delimiters represent a set of characters understood to separate words. The first string character -and the first non-delimiter character after a delimiter will be capitalized. A "" input string returns "". -Capitalization uses the Unicode title case, normally equivalent to upper case. - -Parameters: - str - the string to capitalize - delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter - -Returns: - capitalized string -*/ -func Capitalize(str string, delimiters ...rune) string { - - var delimLen int - - if delimiters == nil { - delimLen = -1 - } else { - delimLen = len(delimiters) - } - - if str == "" || delimLen == 0 { - return str - } - - buffer := []rune(str) - capitalizeNext := true - for i := 0; i < len(buffer); i++ { - ch := buffer[i] - if isDelimiter(ch, delimiters...) { - capitalizeNext = true - } else if capitalizeNext { - buffer[i] = unicode.ToTitle(ch) - capitalizeNext = false - } - } - return string(buffer) - -} - -/* -CapitalizeFully converts all the delimiter separated words in a string into capitalized words, that is each word is made up of a -titlecase character and then a series of lowercase characters. The delimiters represent a set of characters understood -to separate words. The first string character and the first non-delimiter character after a delimiter will be capitalized. -Capitalization uses the Unicode title case, normally equivalent to upper case. - -Parameters: - str - the string to capitalize fully - delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter - -Returns: - capitalized string -*/ -func CapitalizeFully(str string, delimiters ...rune) string { - - var delimLen int - - if delimiters == nil { - delimLen = -1 - } else { - delimLen = len(delimiters) - } - - if str == "" || delimLen == 0 { - return str - } - str = strings.ToLower(str) - return Capitalize(str, delimiters...) -} - -/* -Uncapitalize uncapitalizes all the whitespace separated words in a string. Only the first letter of each word is changed. -The delimiters represent a set of characters understood to separate words. The first string character and the first non-delimiter -character after a delimiter will be uncapitalized. Whitespace is defined by unicode.IsSpace(char). - -Parameters: - str - the string to uncapitalize fully - delimiters - set of characters to determine capitalization, exclusion of this parameter means whitespace would be delimeter - -Returns: - uncapitalized string -*/ -func Uncapitalize(str string, delimiters ...rune) string { - - var delimLen int - - if delimiters == nil { - delimLen = -1 - } else { - delimLen = len(delimiters) - } - - if str == "" || delimLen == 0 { - return str - } - - buffer := []rune(str) - uncapitalizeNext := true // TODO Always makes capitalize/un apply to first char. - for i := 0; i < len(buffer); i++ { - ch := buffer[i] - if isDelimiter(ch, delimiters...) { - uncapitalizeNext = true - } else if uncapitalizeNext { - buffer[i] = unicode.ToLower(ch) - uncapitalizeNext = false - } - } - return string(buffer) -} - -/* -SwapCase swaps the case of a string using a word based algorithm. - -Conversion algorithm: - - Upper case character converts to Lower case - Title case character converts to Lower case - Lower case character after Whitespace or at start converts to Title case - Other Lower case character converts to Upper case - Whitespace is defined by unicode.IsSpace(char). - -Parameters: - str - the string to swap case - -Returns: - the changed string -*/ -func SwapCase(str string) string { - if str == "" { - return str - } - buffer := []rune(str) - - whitespace := true - - for i := 0; i < len(buffer); i++ { - ch := buffer[i] - if unicode.IsUpper(ch) { - buffer[i] = unicode.ToLower(ch) - whitespace = false - } else if unicode.IsTitle(ch) { - buffer[i] = unicode.ToLower(ch) - whitespace = false - } else if unicode.IsLower(ch) { - if whitespace { - buffer[i] = unicode.ToTitle(ch) - whitespace = false - } else { - buffer[i] = unicode.ToUpper(ch) - } - } else { - whitespace = unicode.IsSpace(ch) - } - } - return string(buffer) -} - -/* -Initials extracts the initial letters from each word in the string. The first letter of the string and all first -letters after the defined delimiters are returned as a new string. Their case is not changed. If the delimiters -parameter is excluded, then Whitespace is used. Whitespace is defined by unicode.IsSpacea(char). An empty delimiter array returns an empty string. - -Parameters: - str - the string to get initials from - delimiters - set of characters to determine words, exclusion of this parameter means whitespace would be delimeter -Returns: - string of initial letters -*/ -func Initials(str string, delimiters ...rune) string { - if str == "" { - return str - } - if delimiters != nil && len(delimiters) == 0 { - return "" - } - strLen := len(str) - var buf bytes.Buffer - lastWasGap := true - for i := 0; i < strLen; i++ { - ch := rune(str[i]) - - if isDelimiter(ch, delimiters...) { - lastWasGap = true - } else if lastWasGap { - buf.WriteRune(ch) - lastWasGap = false - } - } - return buf.String() -} - -// private function (lower case func name) -func isDelimiter(ch rune, delimiters ...rune) bool { - if delimiters == nil { - return unicode.IsSpace(ch) - } - for _, delimiter := range delimiters { - if ch == delimiter { - return true - } - } - return false -} diff --git a/vendor/github.com/Masterminds/semver/LICENSE.txt b/vendor/github.com/Masterminds/semver/LICENSE.txt deleted file mode 100644 index 0da4aeadb..000000000 --- a/vendor/github.com/Masterminds/semver/LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -The Masterminds -Copyright (C) 2014-2015, 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/collection.go b/vendor/github.com/Masterminds/semver/collection.go deleted file mode 100644 index a78235895..000000000 --- a/vendor/github.com/Masterminds/semver/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/constraints.go b/vendor/github.com/Masterminds/semver/constraints.go deleted file mode 100644 index 4c4fac3b6..000000000 --- a/vendor/github.com/Masterminds/semver/constraints.go +++ /dev/null @@ -1,421 +0,0 @@ -package semver - -import ( - "errors" - "fmt" - "regexp" - "strings" -) - -// Constraints is one or more constraint that a semantic version can be -// checked against. -type Constraints struct { - constraints [][]*constraint -} - -// NewConstraint returns a Constraints instance that a Version instance can -// be checked against. If there is a parse error it will be returned. -func NewConstraint(c string) (*Constraints, error) { - - // Rewrite - ranges into a comparison operation. - c = rewriteRange(c) - - ors := strings.Split(c, "||") - or := make([][]*constraint, len(ors)) - for k, v := range ors { - cs := strings.Split(v, ",") - result := make([]*constraint, len(cs)) - for i, s := range cs { - pc, err := parseConstraint(s) - if err != nil { - return nil, err - } - - result[i] = pc - } - or[k] = result - } - - o := &Constraints{constraints: or} - return o, nil -} - -// Check tests if a version satisfies the constraints. -func (cs Constraints) Check(v *Version) bool { - // loop over the ORs and check the inner ANDs - for _, o := range cs.constraints { - joy := true - for _, c := range o { - if !c.check(v) { - joy = false - break - } - } - - if joy { - return true - } - } - - return false -} - -// Validate checks if a version satisfies a constraint. If not a slice of -// reasons for the failure are returned in addition to a bool. -func (cs Constraints) Validate(v *Version) (bool, []error) { - // loop over the ORs and check the inner ANDs - var e []error - for _, o := range cs.constraints { - joy := true - for _, c := range o { - if !c.check(v) { - em := fmt.Errorf(c.msg, v, c.orig) - e = append(e, em) - joy = false - } - } - - if joy { - return true, []error{} - } - } - - return false, e -} - -var constraintOps map[string]cfunc -var constraintMsg map[string]string -var constraintRegex *regexp.Regexp - -func init() { - constraintOps = map[string]cfunc{ - "": constraintTildeOrEqual, - "=": constraintTildeOrEqual, - "!=": constraintNotEqual, - ">": constraintGreaterThan, - "<": constraintLessThan, - ">=": constraintGreaterThanEqual, - "=>": constraintGreaterThanEqual, - "<=": constraintLessThanEqual, - "=<": constraintLessThanEqual, - "~": constraintTilde, - "~>": constraintTilde, - "^": constraintCaret, - } - - constraintMsg = map[string]string{ - "": "%s is not equal to %s", - "=": "%s is not equal to %s", - "!=": "%s is equal to %s", - ">": "%s is less than or equal to %s", - "<": "%s is greater than or equal to %s", - ">=": "%s is less than %s", - "=>": "%s is less than %s", - "<=": "%s is greater than %s", - "=<": "%s is greater than %s", - "~": "%s does not have same major and minor version as %s", - "~>": "%s does not have same major and minor version as %s", - "^": "%s does not have same major version as %s", - } - - ops := make([]string, 0, len(constraintOps)) - for k := range constraintOps { - ops = append(ops, regexp.QuoteMeta(k)) - } - - constraintRegex = regexp.MustCompile(fmt.Sprintf( - `^\s*(%s)\s*(%s)\s*$`, - strings.Join(ops, "|"), - cvRegex)) - - constraintRangeRegex = regexp.MustCompile(fmt.Sprintf( - `\s*(%s)\s+-\s+(%s)\s*`, - cvRegex, cvRegex)) -} - -// An individual constraint -type constraint struct { - // The callback function for the restraint. It performs the logic for - // the constraint. - function cfunc - - msg string - - // The version used in the constraint check. For example, if a constraint - // is '<= 2.0.0' the con a version instance representing 2.0.0. - con *Version - - // The original parsed version (e.g., 4.x from != 4.x) - orig string - - // When an x is used as part of the version (e.g., 1.x) - minorDirty bool - dirty bool -} - -// Check if a version meets the constraint -func (c *constraint) check(v *Version) bool { - return c.function(v, c) -} - -type cfunc func(v *Version, c *constraint) bool - -func parseConstraint(c string) (*constraint, error) { - m := constraintRegex.FindStringSubmatch(c) - if m == nil { - return nil, fmt.Errorf("improper constraint: %s", c) - } - - ver := m[2] - orig := ver - minorDirty := false - dirty := false - if isX(m[3]) { - ver = "0.0.0" - dirty = true - } else if isX(strings.TrimPrefix(m[4], ".")) { - minorDirty = true - dirty = true - ver = fmt.Sprintf("%s.0.0%s", m[3], m[6]) - } else if isX(strings.TrimPrefix(m[5], ".")) { - dirty = true - ver = fmt.Sprintf("%s%s.0%s", m[3], m[4], m[6]) - } - - con, err := NewVersion(ver) - if err != nil { - - // The constraintRegex should catch any regex parsing errors. So, - // we should never get here. - return nil, errors.New("constraint Parser Error") - } - - cs := &constraint{ - function: constraintOps[m[1]], - msg: constraintMsg[m[1]], - con: con, - orig: orig, - minorDirty: minorDirty, - dirty: dirty, - } - return cs, nil -} - -// Constraint functions -func constraintNotEqual(v *Version, c *constraint) bool { - if c.dirty { - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if c.con.Major() != v.Major() { - return true - } - if c.con.Minor() != v.Minor() && !c.minorDirty { - return true - } else if c.minorDirty { - return false - } - - return false - } - - return !v.Equal(c.con) -} - -func constraintGreaterThan(v *Version, c *constraint) bool { - - // An edge case the constraint is 0.0.0 and the version is 0.0.0-someprerelease - // exists. This that case. - if !isNonZero(c.con) && isNonZero(v) { - return true - } - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - return v.Compare(c.con) == 1 -} - -func constraintLessThan(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if !c.dirty { - return v.Compare(c.con) < 0 - } - - if v.Major() > c.con.Major() { - return false - } else if v.Minor() > c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -func constraintGreaterThanEqual(v *Version, c *constraint) bool { - // An edge case the constraint is 0.0.0 and the version is 0.0.0-someprerelease - // exists. This that case. - if !isNonZero(c.con) && isNonZero(v) { - return true - } - - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - return v.Compare(c.con) >= 0 -} - -func constraintLessThanEqual(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if !c.dirty { - return v.Compare(c.con) <= 0 - } - - if v.Major() > c.con.Major() { - return false - } else if v.Minor() > c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -// ~*, ~>* --> >= 0.0.0 (any) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0, <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0, <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0, <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3, <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0, <1.3.0 -func constraintTilde(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if v.LessThan(c.con) { - return false - } - - // ~0.0.0 is a special case where all constraints are accepted. It's - // equivalent to >= 0.0.0. - if c.con.Major() == 0 && c.con.Minor() == 0 && c.con.Patch() == 0 { - return true - } - - if v.Major() != c.con.Major() { - return false - } - - if v.Minor() != c.con.Minor() && !c.minorDirty { - return false - } - - return true -} - -// When there is a .x (dirty) status it automatically opts in to ~. Otherwise -// it's a straight = -func constraintTildeOrEqual(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if c.dirty { - c.msg = constraintMsg["~"] - return constraintTilde(v, c) - } - - return v.Equal(c.con) -} - -// ^* --> (any) -// ^2, ^2.x, ^2.x.x --> >=2.0.0, <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0, <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0, <2.0.0 -// ^1.2.3 --> >=1.2.3, <2.0.0 -// ^1.2.0 --> >=1.2.0, <2.0.0 -func constraintCaret(v *Version, c *constraint) bool { - // If there is a pre-release on the version but the constraint isn't looking - // for them assume that pre-releases are not compatible. See issue 21 for - // more details. - if v.Prerelease() != "" && c.con.Prerelease() == "" { - return false - } - - if v.LessThan(c.con) { - return false - } - - if v.Major() != c.con.Major() { - return false - } - - return true -} - -var constraintRangeRegex *regexp.Regexp - -const cvRegex string = `v?([0-9|x|X|\*]+)(\.[0-9|x|X|\*]+)?(\.[0-9|x|X|\*]+)?` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + - `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` - -func isX(x string) bool { - switch x { - case "x", "*", "X": - return true - default: - return false - } -} - -func rewriteRange(i string) string { - m := constraintRangeRegex.FindAllStringSubmatch(i, -1) - if m == nil { - return i - } - o := i - for _, v := range m { - t := fmt.Sprintf(">= %s, <= %s", v[1], v[11]) - o = strings.Replace(o, v[0], t, 1) - } - - return o -} - -// Detect if a version is not zero (0.0.0) -func isNonZero(v *Version) bool { - if v.Major() != 0 || v.Minor() != 0 || v.Patch() != 0 || v.Prerelease() != "" { - return true - } - - return false -} diff --git a/vendor/github.com/Masterminds/semver/doc.go b/vendor/github.com/Masterminds/semver/doc.go deleted file mode 100644 index e00f65eb7..000000000 --- a/vendor/github.com/Masterminds/semver/doc.go +++ /dev/null @@ -1,115 +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 - -To parse a semantic version use the `NewVersion` function. For example, - - v, err := semver.NewVersion("1.2.3-beta.1+build345") - -If there is an error the version wasn't parseable. The version object has methods -to get the parts of the version, compare it to other versions, convert the -version back into a string, and get the original string. For more details -please see the documentation at https://godoc.org/github.com/Masterminds/semver. - -Sorting Semantic Versions - -A set of versions can be sorted using the `sort` package from the standard library. -For example, - - raw := []string{"1.2.3", "1.0", "1.3", "2", "0.4.2",} - vs := make([]*semver.Version, len(raw)) - for i, r := range raw { - v, err := semver.NewVersion(r) - if err != nil { - t.Errorf("Error parsing version: %s", err) - } - - vs[i] = v - } - - sort.Sort(semver.Collection(vs)) - -Checking Version Constraints - -Checking a version against version constraints is one of the most featureful -parts of the package. - - c, err := semver.NewConstraint(">= 1.2.3") - if err != nil { - // Handle constraint not being parseable. - } - - v, _ := semver.NewVersion("1.3") - if err != nil { - // Handle version not being parseable. - } - // Check if the version meets the constraints. The a variable will be true. - a := c.Check(v) - -Basic Comparisons - -There are two elements to the comparisons. First, a comparison string is a list -of comma separated and comparisons. These are then separated by || separated or -comparisons. For example, `">= 1.2, < 3.0.0 || >= 4.2.3"` is looking for a -comparison that's greater than or equal to 1.2 and less than 3.0.0 or is -greater than or equal to 4.2.3. - -The basic comparisons are: - - * `=`: equal (aliased to no operator) - * `!=`: not equal - * `>`: greater than - * `<`: less than - * `>=`: greater than or equal to - * `<=`: less than or equal to - -Hyphen Range Comparisons - -There are multiple methods to handle ranges and the first is hyphens ranges. -These look like: - - * `1.2 - 1.4.5` which is equivalent to `>= 1.2, <= 1.4.5` - * `2.3.4 - 4.5` which is equivalent to `>= 2.3.4, <= 4.5` - -Wildcards In Comparisons - -The `x`, `X`, and `*` characters can be used as a wildcard character. This works -for all comparison operators. When used on the `=` operator it falls -back to the pack level comparison (see tilde below). For example, - - * `1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` - * `>= 1.2.x` is equivalent to `>= 1.2.0` - * `<= 2.x` is equivalent to `<= 3` - * `*` is equivalent to `>= 0.0.0` - -Tilde Range Comparisons (Patch) - -The tilde (`~`) comparison operator is for patch level ranges when a minor -version is specified and major level changes when the minor number is missing. -For example, - - * `~1.2.3` is equivalent to `>= 1.2.3, < 1.3.0` - * `~1` is equivalent to `>= 1, < 2` - * `~2.3` is equivalent to `>= 2.3, < 2.4` - * `~1.2.x` is equivalent to `>= 1.2.0, < 1.3.0` - * `~1.x` is equivalent to `>= 1, < 2` - -Caret Range Comparisons (Major) - -The caret (`^`) comparison operator is for major level changes. This is useful -when comparisons of API versions as a major change is API breaking. For example, - - * `^1.2.3` is equivalent to `>= 1.2.3, < 2.0.0` - * `^1.2.x` is equivalent to `>= 1.2.0, < 2.0.0` - * `^2.3` is equivalent to `>= 2.3, < 3` - * `^2.x` is equivalent to `>= 2.0.0, < 3` -*/ -package semver diff --git a/vendor/github.com/Masterminds/semver/version.go b/vendor/github.com/Masterminds/semver/version.go deleted file mode 100644 index 28b26ac29..000000000 --- a/vendor/github.com/Masterminds/semver/version.go +++ /dev/null @@ -1,375 +0,0 @@ -package semver - -import ( - "bytes" - "errors" - "fmt" - "regexp" - "strconv" - "strings" -) - -// The compiled version of the regex created at init() is cached here so it -// only needs to be created once. -var versionRegex *regexp.Regexp -var validPrereleaseRegex *regexp.Regexp - -var ( - // ErrInvalidSemVer is returned a version is found to be invalid when - // being parsed. - ErrInvalidSemVer = errors.New("Invalid Semantic Version") - - // ErrInvalidMetadata is returned when the metadata is an invalid format - ErrInvalidMetadata = errors.New("Invalid Metadata string") - - // ErrInvalidPrerelease is returned when the pre-release is an invalid format - ErrInvalidPrerelease = errors.New("Invalid Prerelease string") -) - -// SemVerRegex is the regular expression used to parse a semantic version. -const SemVerRegex string = `v?([0-9]+)(\.[0-9]+)?(\.[0-9]+)?` + - `(-([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` + - `(\+([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*))?` - -// ValidPrerelease is the regular expression which validates -// both prerelease and metadata values. -const ValidPrerelease string = `^([0-9A-Za-z\-]+(\.[0-9A-Za-z\-]+)*)` - -// Version represents a single semantic version. -type Version struct { - major, minor, patch int64 - pre string - metadata string - original string -} - -func init() { - versionRegex = regexp.MustCompile("^" + SemVerRegex + "$") - validPrereleaseRegex = regexp.MustCompile(ValidPrerelease) -} - -// NewVersion parses a given version and returns an instance of Version or -// an error if unable to parse the version. -func NewVersion(v string) (*Version, error) { - m := versionRegex.FindStringSubmatch(v) - if m == nil { - return nil, ErrInvalidSemVer - } - - sv := &Version{ - metadata: m[8], - pre: m[5], - original: v, - } - - var temp int64 - temp, err := strconv.ParseInt(m[1], 10, 32) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - sv.major = temp - - if m[2] != "" { - temp, err = strconv.ParseInt(strings.TrimPrefix(m[2], "."), 10, 32) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - sv.minor = temp - } else { - sv.minor = 0 - } - - if m[3] != "" { - temp, err = strconv.ParseInt(strings.TrimPrefix(m[3], "."), 10, 32) - if err != nil { - return nil, fmt.Errorf("Error parsing version segment: %s", err) - } - sv.patch = temp - } else { - sv.patch = 0 - } - - return sv, nil -} - -// MustParse parses a given version and panics on error. -func MustParse(v string) *Version { - sv, err := NewVersion(v) - if err != nil { - panic(err) - } - return sv -} - -// String converts a Version object to a string. -// Note, if the original version contained a leading v this version will not. -// See the Original() method to retrieve the original value. Semantic Versions -// don't contain a leading v per the spec. Instead it's optional on -// impelementation. -func (v *Version) String() string { - var buf bytes.Buffer - - fmt.Fprintf(&buf, "%d.%d.%d", v.major, v.minor, v.patch) - if v.pre != "" { - fmt.Fprintf(&buf, "-%s", v.pre) - } - if v.metadata != "" { - fmt.Fprintf(&buf, "+%s", v.metadata) - } - - return buf.String() -} - -// Original returns the original value passed in to be parsed. -func (v *Version) Original() string { - return v.original -} - -// Major returns the major version. -func (v *Version) Major() int64 { - return v.major -} - -// Minor returns the minor version. -func (v *Version) Minor() int64 { - return v.minor -} - -// Patch returns the patch version. -func (v *Version) Patch() int64 { - return v.patch -} - -// Prerelease returns the pre-release version. -func (v *Version) Prerelease() string { - return v.pre -} - -// Metadata returns the metadata on the version. -func (v *Version) Metadata() string { - return v.metadata -} - -// originalVPrefix returns the original 'v' prefix if any. -func (v *Version) originalVPrefix() string { - - // Note, only lowercase v is supported as a prefix by the parser. - if v.original != "" && v.original[:1] == "v" { - return v.original[:1] - } - return "" -} - -// IncPatch produces the next patch version. -// If the current version does not have prerelease/metadata information, -// it unsets metadata and prerelease values, increments patch number. -// If the current version has any of prerelease or metadata information, -// it unsets both values and keeps curent patch value -func (v Version) IncPatch() Version { - vNext := v - // according to http://semver.org/#spec-item-9 - // Pre-release versions have a lower precedence than the associated normal version. - // according to http://semver.org/#spec-item-10 - // Build metadata SHOULD be ignored when determining version precedence. - if v.pre != "" { - vNext.metadata = "" - vNext.pre = "" - } else { - vNext.metadata = "" - vNext.pre = "" - vNext.patch = v.patch + 1 - } - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// IncMinor produces the next minor version. -// Sets patch to 0. -// Increments minor number. -// Unsets metadata. -// Unsets prerelease status. -func (v Version) IncMinor() Version { - vNext := v - vNext.metadata = "" - vNext.pre = "" - vNext.patch = 0 - vNext.minor = v.minor + 1 - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// IncMajor produces the next major version. -// Sets patch to 0. -// Sets minor to 0. -// Increments major number. -// Unsets metadata. -// Unsets prerelease status. -func (v Version) IncMajor() Version { - vNext := v - vNext.metadata = "" - vNext.pre = "" - vNext.patch = 0 - vNext.minor = 0 - vNext.major = v.major + 1 - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext -} - -// SetPrerelease defines the prerelease value. -// Value must not include the required 'hypen' prefix. -func (v Version) SetPrerelease(prerelease string) (Version, error) { - vNext := v - if len(prerelease) > 0 && !validPrereleaseRegex.MatchString(prerelease) { - return vNext, ErrInvalidPrerelease - } - vNext.pre = prerelease - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext, nil -} - -// SetMetadata defines metadata value. -// Value must not include the required 'plus' prefix. -func (v Version) SetMetadata(metadata string) (Version, error) { - vNext := v - if len(metadata) > 0 && !validPrereleaseRegex.MatchString(metadata) { - return vNext, ErrInvalidMetadata - } - vNext.metadata = metadata - vNext.original = v.originalVPrefix() + "" + vNext.String() - return vNext, nil -} - -// LessThan tests if one version is less than another one. -func (v *Version) LessThan(o *Version) bool { - return v.Compare(o) < 0 -} - -// GreaterThan tests if one version is greater than another one. -func (v *Version) GreaterThan(o *Version) bool { - return v.Compare(o) > 0 -} - -// Equal tests if two versions are equal to each other. -// Note, versions can be equal with different metadata since metadata -// is not considered part of the comparable version. -func (v *Version) Equal(o *Version) bool { - return v.Compare(o) == 0 -} - -// Compare compares this version to another one. It returns -1, 0, or 1 if -// the version smaller, equal, or larger than the other version. -// -// Versions are compared by X.Y.Z. Build metadata is ignored. Prerelease is -// lower than the version without a prerelease. -func (v *Version) Compare(o *Version) int { - // Compare the major, minor, and patch version for differences. If a - // difference is found return the comparison. - if d := compareSegment(v.Major(), o.Major()); d != 0 { - return d - } - if d := compareSegment(v.Minor(), o.Minor()); d != 0 { - return d - } - if d := compareSegment(v.Patch(), o.Patch()); d != 0 { - return d - } - - // At this point the major, minor, and patch versions are the same. - ps := v.pre - po := o.Prerelease() - - if ps == "" && po == "" { - return 0 - } - if ps == "" { - return 1 - } - if po == "" { - return -1 - } - - return comparePrerelease(ps, po) -} - -func compareSegment(v, o int64) int { - if v < o { - return -1 - } - if v > o { - return 1 - } - - return 0 -} - -func comparePrerelease(v, o string) int { - - // split the prelease versions by their part. The separator, per the spec, - // is a . - sparts := strings.Split(v, ".") - oparts := strings.Split(o, ".") - - // Find the longer length of the parts to know how many loop iterations to - // go through. - slen := len(sparts) - olen := len(oparts) - - l := slen - if olen > slen { - l = olen - } - - // Iterate over each part of the prereleases to compare the differences. - for i := 0; i < l; i++ { - // Since the lentgh of the parts can be different we need to create - // a placeholder. This is to avoid out of bounds issues. - stemp := "" - if i < slen { - stemp = sparts[i] - } - - otemp := "" - if i < olen { - otemp = oparts[i] - } - - d := comparePrePart(stemp, otemp) - if d != 0 { - return d - } - } - - // Reaching here means two versions are of equal value but have different - // metadata (the part following a +). They are not identical in string form - // but the version comparison finds them to be equal. - return 0 -} - -func comparePrePart(s, o string) int { - // Fastpath if they are equal - if s == o { - return 0 - } - - // When s or o are empty we can use the other in an attempt to determine - // the response. - if o == "" { - _, n := strconv.ParseInt(s, 10, 64) - if n != nil { - return -1 - } - return 1 - } - if s == "" { - _, n := strconv.ParseInt(o, 10, 64) - if n != nil { - return 1 - } - return -1 - } - - if s > o { - return 1 - } - return -1 -} diff --git a/vendor/github.com/Masterminds/sprig/LICENSE.txt b/vendor/github.com/Masterminds/sprig/LICENSE.txt deleted file mode 100644 index 5c95accc2..000000000 --- a/vendor/github.com/Masterminds/sprig/LICENSE.txt +++ /dev/null @@ -1,20 +0,0 @@ -Sprig -Copyright (C) 2013 Masterminds - -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/sprig/crypto.go b/vendor/github.com/Masterminds/sprig/crypto.go deleted file mode 100644 index 7427deb83..000000000 --- a/vendor/github.com/Masterminds/sprig/crypto.go +++ /dev/null @@ -1,441 +0,0 @@ -package sprig - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/hmac" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/base64" - "encoding/binary" - "encoding/hex" - "encoding/pem" - "errors" - "fmt" - "hash/adler32" - "math/big" - "net" - "time" - - "github.com/google/uuid" - "golang.org/x/crypto/scrypt" -) - -func sha256sum(input string) string { - hash := sha256.Sum256([]byte(input)) - return hex.EncodeToString(hash[:]) -} - -func sha1sum(input string) string { - hash := sha1.Sum([]byte(input)) - return hex.EncodeToString(hash[:]) -} - -func adler32sum(input string) string { - hash := adler32.Checksum([]byte(input)) - return fmt.Sprintf("%d", hash) -} - -// uuidv4 provides a safe and secure UUID v4 implementation -func uuidv4() string { - return fmt.Sprintf("%s", uuid.New()) -} - -var master_password_seed = "com.lyndir.masterpassword" - -var password_type_templates = map[string][][]byte{ - "maximum": {[]byte("anoxxxxxxxxxxxxxxxxx"), []byte("axxxxxxxxxxxxxxxxxno")}, - "long": {[]byte("CvcvnoCvcvCvcv"), []byte("CvcvCvcvnoCvcv"), []byte("CvcvCvcvCvcvno"), []byte("CvccnoCvcvCvcv"), []byte("CvccCvcvnoCvcv"), - []byte("CvccCvcvCvcvno"), []byte("CvcvnoCvccCvcv"), []byte("CvcvCvccnoCvcv"), []byte("CvcvCvccCvcvno"), []byte("CvcvnoCvcvCvcc"), - []byte("CvcvCvcvnoCvcc"), []byte("CvcvCvcvCvccno"), []byte("CvccnoCvccCvcv"), []byte("CvccCvccnoCvcv"), []byte("CvccCvccCvcvno"), - []byte("CvcvnoCvccCvcc"), []byte("CvcvCvccnoCvcc"), []byte("CvcvCvccCvccno"), []byte("CvccnoCvcvCvcc"), []byte("CvccCvcvnoCvcc"), - []byte("CvccCvcvCvccno")}, - "medium": {[]byte("CvcnoCvc"), []byte("CvcCvcno")}, - "short": {[]byte("Cvcn")}, - "basic": {[]byte("aaanaaan"), []byte("aannaaan"), []byte("aaannaaa")}, - "pin": {[]byte("nnnn")}, -} - -var template_characters = map[byte]string{ - 'V': "AEIOU", - 'C': "BCDFGHJKLMNPQRSTVWXYZ", - 'v': "aeiou", - 'c': "bcdfghjklmnpqrstvwxyz", - 'A': "AEIOUBCDFGHJKLMNPQRSTVWXYZ", - 'a': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz", - 'n': "0123456789", - 'o': "@&%?,=[]_:-+*$#!'^~;()/.", - 'x': "AEIOUaeiouBCDFGHJKLMNPQRSTVWXYZbcdfghjklmnpqrstvwxyz0123456789!@#$%^&*()", -} - -func derivePassword(counter uint32, password_type, password, user, site string) string { - var templates = password_type_templates[password_type] - if templates == nil { - return fmt.Sprintf("cannot find password template %s", password_type) - } - - var buffer bytes.Buffer - buffer.WriteString(master_password_seed) - binary.Write(&buffer, binary.BigEndian, uint32(len(user))) - buffer.WriteString(user) - - salt := buffer.Bytes() - key, err := scrypt.Key([]byte(password), salt, 32768, 8, 2, 64) - if err != nil { - return fmt.Sprintf("failed to derive password: %s", err) - } - - buffer.Truncate(len(master_password_seed)) - binary.Write(&buffer, binary.BigEndian, uint32(len(site))) - buffer.WriteString(site) - binary.Write(&buffer, binary.BigEndian, counter) - - var hmacv = hmac.New(sha256.New, key) - hmacv.Write(buffer.Bytes()) - var seed = hmacv.Sum(nil) - var temp = templates[int(seed[0])%len(templates)] - - buffer.Truncate(0) - for i, element := range temp { - pass_chars := template_characters[element] - pass_char := pass_chars[int(seed[i+1])%len(pass_chars)] - buffer.WriteByte(pass_char) - } - - return buffer.String() -} - -func generatePrivateKey(typ string) string { - var priv interface{} - var err error - switch typ { - case "", "rsa": - // good enough for government work - priv, err = rsa.GenerateKey(rand.Reader, 4096) - case "dsa": - key := new(dsa.PrivateKey) - // again, good enough for government work - if err = dsa.GenerateParameters(&key.Parameters, rand.Reader, dsa.L2048N256); err != nil { - return fmt.Sprintf("failed to generate dsa params: %s", err) - } - err = dsa.GenerateKey(key, rand.Reader) - priv = key - case "ecdsa": - // again, good enough for government work - priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - default: - return "Unknown type " + typ - } - if err != nil { - return fmt.Sprintf("failed to generate private key: %s", err) - } - - return string(pem.EncodeToMemory(pemBlockForKey(priv))) -} - -type DSAKeyFormat struct { - Version int - P, Q, G, Y, X *big.Int -} - -func pemBlockForKey(priv interface{}) *pem.Block { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} - case *dsa.PrivateKey: - val := DSAKeyFormat{ - P: k.P, Q: k.Q, G: k.G, - Y: k.Y, X: k.X, - } - bytes, _ := asn1.Marshal(val) - return &pem.Block{Type: "DSA PRIVATE KEY", Bytes: bytes} - case *ecdsa.PrivateKey: - b, _ := x509.MarshalECPrivateKey(k) - return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} - default: - return nil - } -} - -type certificate struct { - Cert string - Key string -} - -func buildCustomCertificate(b64cert string, b64key string) (certificate, error) { - crt := certificate{} - - cert, err := base64.StdEncoding.DecodeString(b64cert) - if err != nil { - return crt, errors.New("unable to decode base64 certificate") - } - - key, err := base64.StdEncoding.DecodeString(b64key) - if err != nil { - return crt, errors.New("unable to decode base64 private key") - } - - decodedCert, _ := pem.Decode(cert) - if decodedCert == nil { - return crt, errors.New("unable to decode certificate") - } - _, err = x509.ParseCertificate(decodedCert.Bytes) - if err != nil { - return crt, fmt.Errorf( - "error parsing certificate: decodedCert.Bytes: %s", - err, - ) - } - - decodedKey, _ := pem.Decode(key) - if decodedKey == nil { - return crt, errors.New("unable to decode key") - } - _, err = x509.ParsePKCS1PrivateKey(decodedKey.Bytes) - if err != nil { - return crt, fmt.Errorf( - "error parsing prive key: decodedKey.Bytes: %s", - err, - ) - } - - crt.Cert = string(cert) - crt.Key = string(key) - - return crt, nil -} - -func generateCertificateAuthority( - cn string, - daysValid int, -) (certificate, error) { - ca := certificate{} - - template, err := getBaseCertTemplate(cn, nil, nil, daysValid) - if err != nil { - return ca, err - } - // Override KeyUsage and IsCA - template.KeyUsage = x509.KeyUsageKeyEncipherment | - x509.KeyUsageDigitalSignature | - x509.KeyUsageCertSign - template.IsCA = true - - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return ca, fmt.Errorf("error generating rsa key: %s", err) - } - - ca.Cert, ca.Key, err = getCertAndKey(template, priv, template, priv) - if err != nil { - return ca, err - } - - return ca, nil -} - -func generateSelfSignedCertificate( - cn string, - ips []interface{}, - alternateDNS []interface{}, - daysValid int, -) (certificate, error) { - cert := certificate{} - - template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid) - if err != nil { - return cert, err - } - - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return cert, fmt.Errorf("error generating rsa key: %s", err) - } - - cert.Cert, cert.Key, err = getCertAndKey(template, priv, template, priv) - if err != nil { - return cert, err - } - - return cert, nil -} - -func generateSignedCertificate( - cn string, - ips []interface{}, - alternateDNS []interface{}, - daysValid int, - ca certificate, -) (certificate, error) { - cert := certificate{} - - decodedSignerCert, _ := pem.Decode([]byte(ca.Cert)) - if decodedSignerCert == nil { - return cert, errors.New("unable to decode certificate") - } - signerCert, err := x509.ParseCertificate(decodedSignerCert.Bytes) - if err != nil { - return cert, fmt.Errorf( - "error parsing certificate: decodedSignerCert.Bytes: %s", - err, - ) - } - decodedSignerKey, _ := pem.Decode([]byte(ca.Key)) - if decodedSignerKey == nil { - return cert, errors.New("unable to decode key") - } - signerKey, err := x509.ParsePKCS1PrivateKey(decodedSignerKey.Bytes) - if err != nil { - return cert, fmt.Errorf( - "error parsing prive key: decodedSignerKey.Bytes: %s", - err, - ) - } - - template, err := getBaseCertTemplate(cn, ips, alternateDNS, daysValid) - if err != nil { - return cert, err - } - - priv, err := rsa.GenerateKey(rand.Reader, 2048) - if err != nil { - return cert, fmt.Errorf("error generating rsa key: %s", err) - } - - cert.Cert, cert.Key, err = getCertAndKey( - template, - priv, - signerCert, - signerKey, - ) - if err != nil { - return cert, err - } - - return cert, nil -} - -func getCertAndKey( - template *x509.Certificate, - signeeKey *rsa.PrivateKey, - parent *x509.Certificate, - signingKey *rsa.PrivateKey, -) (string, string, error) { - derBytes, err := x509.CreateCertificate( - rand.Reader, - template, - parent, - &signeeKey.PublicKey, - signingKey, - ) - if err != nil { - return "", "", fmt.Errorf("error creating certificate: %s", err) - } - - certBuffer := bytes.Buffer{} - if err := pem.Encode( - &certBuffer, - &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}, - ); err != nil { - return "", "", fmt.Errorf("error pem-encoding certificate: %s", err) - } - - keyBuffer := bytes.Buffer{} - if err := pem.Encode( - &keyBuffer, - &pem.Block{ - Type: "RSA PRIVATE KEY", - Bytes: x509.MarshalPKCS1PrivateKey(signeeKey), - }, - ); err != nil { - return "", "", fmt.Errorf("error pem-encoding key: %s", err) - } - - return string(certBuffer.Bytes()), string(keyBuffer.Bytes()), nil -} - -func getBaseCertTemplate( - cn string, - ips []interface{}, - alternateDNS []interface{}, - daysValid int, -) (*x509.Certificate, error) { - ipAddresses, err := getNetIPs(ips) - if err != nil { - return nil, err - } - dnsNames, err := getAlternateDNSStrs(alternateDNS) - if err != nil { - return nil, err - } - serialNumberUpperBound := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberUpperBound) - if err != nil { - return nil, err - } - return &x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - CommonName: cn, - }, - IPAddresses: ipAddresses, - DNSNames: dnsNames, - NotBefore: time.Now(), - NotAfter: time.Now().Add(time.Hour * 24 * time.Duration(daysValid)), - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{ - x509.ExtKeyUsageServerAuth, - x509.ExtKeyUsageClientAuth, - }, - BasicConstraintsValid: true, - }, nil -} - -func getNetIPs(ips []interface{}) ([]net.IP, error) { - if ips == nil { - return []net.IP{}, nil - } - var ipStr string - var ok bool - var netIP net.IP - netIPs := make([]net.IP, len(ips)) - for i, ip := range ips { - ipStr, ok = ip.(string) - if !ok { - return nil, fmt.Errorf("error parsing ip: %v is not a string", ip) - } - netIP = net.ParseIP(ipStr) - if netIP == nil { - return nil, fmt.Errorf("error parsing ip: %s", ipStr) - } - netIPs[i] = netIP - } - return netIPs, nil -} - -func getAlternateDNSStrs(alternateDNS []interface{}) ([]string, error) { - if alternateDNS == nil { - return []string{}, nil - } - var dnsStr string - var ok bool - alternateDNSStrs := make([]string, len(alternateDNS)) - for i, dns := range alternateDNS { - dnsStr, ok = dns.(string) - if !ok { - return nil, fmt.Errorf( - "error processing alternate dns name: %v is not a string", - dns, - ) - } - alternateDNSStrs[i] = dnsStr - } - return alternateDNSStrs, nil -} diff --git a/vendor/github.com/Masterminds/sprig/date.go b/vendor/github.com/Masterminds/sprig/date.go deleted file mode 100644 index 1c2c3653c..000000000 --- a/vendor/github.com/Masterminds/sprig/date.go +++ /dev/null @@ -1,76 +0,0 @@ -package sprig - -import ( - "time" -) - -// Given a format and a date, format the date string. -// -// Date can be a `time.Time` or an `int, int32, int64`. -// In the later case, it is treated as seconds since UNIX -// epoch. -func date(fmt string, date interface{}) string { - return dateInZone(fmt, date, "Local") -} - -func htmlDate(date interface{}) string { - return dateInZone("2006-01-02", date, "Local") -} - -func htmlDateInZone(date interface{}, zone string) string { - return dateInZone("2006-01-02", date, zone) -} - -func dateInZone(fmt string, date interface{}, zone string) string { - var t time.Time - switch date := date.(type) { - default: - t = time.Now() - case time.Time: - t = date - case int64: - t = time.Unix(date, 0) - case int: - t = time.Unix(int64(date), 0) - case int32: - t = time.Unix(int64(date), 0) - } - - loc, err := time.LoadLocation(zone) - if err != nil { - loc, _ = time.LoadLocation("UTC") - } - - return t.In(loc).Format(fmt) -} - -func dateModify(fmt string, date time.Time) time.Time { - d, err := time.ParseDuration(fmt) - if err != nil { - return date - } - return date.Add(d) -} - -func dateAgo(date interface{}) string { - var t time.Time - - switch date := date.(type) { - default: - t = time.Now() - case time.Time: - t = date - case int64: - t = time.Unix(date, 0) - case int: - t = time.Unix(int64(date), 0) - } - // Drop resolution to seconds - duration := time.Since(t).Round(time.Second) - return duration.String() -} - -func toDate(fmt, str string) time.Time { - t, _ := time.ParseInLocation(fmt, str, time.Local) - return t -} diff --git a/vendor/github.com/Masterminds/sprig/defaults.go b/vendor/github.com/Masterminds/sprig/defaults.go deleted file mode 100644 index ed6a8ab29..000000000 --- a/vendor/github.com/Masterminds/sprig/defaults.go +++ /dev/null @@ -1,83 +0,0 @@ -package sprig - -import ( - "encoding/json" - "reflect" -) - -// dfault checks whether `given` is set, and returns default if not set. -// -// This returns `d` if `given` appears not to be set, and `given` otherwise. -// -// For numeric types 0 is unset. -// For strings, maps, arrays, and slices, len() = 0 is considered unset. -// For bool, false is unset. -// Structs are never considered unset. -// -// For everything else, including pointers, a nil value is unset. -func dfault(d interface{}, given ...interface{}) interface{} { - - if empty(given) || empty(given[0]) { - return d - } - return given[0] -} - -// empty returns true if the given value has the zero value for its type. -func empty(given interface{}) bool { - g := reflect.ValueOf(given) - if !g.IsValid() { - return true - } - - // Basically adapted from text/template.isTrue - switch g.Kind() { - default: - return g.IsNil() - case reflect.Array, reflect.Slice, reflect.Map, reflect.String: - return g.Len() == 0 - case reflect.Bool: - return g.Bool() == false - case reflect.Complex64, reflect.Complex128: - return g.Complex() == 0 - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return g.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return g.Uint() == 0 - case reflect.Float32, reflect.Float64: - return g.Float() == 0 - case reflect.Struct: - return false - } -} - -// coalesce returns the first non-empty value. -func coalesce(v ...interface{}) interface{} { - for _, val := range v { - if !empty(val) { - return val - } - } - return nil -} - -// toJson encodes an item into a JSON string -func toJson(v interface{}) string { - output, _ := json.Marshal(v) - return string(output) -} - -// toPrettyJson encodes an item into a pretty (indented) JSON string -func toPrettyJson(v interface{}) string { - output, _ := json.MarshalIndent(v, "", " ") - return string(output) -} - -// ternary returns the first value if the last value is true, otherwise returns the second value. -func ternary(vt interface{}, vf interface{}, v bool) interface{} { - if v { - return vt - } - - return vf -} diff --git a/vendor/github.com/Masterminds/sprig/dict.go b/vendor/github.com/Masterminds/sprig/dict.go deleted file mode 100644 index 026eccb73..000000000 --- a/vendor/github.com/Masterminds/sprig/dict.go +++ /dev/null @@ -1,107 +0,0 @@ -package sprig - -import "github.com/imdario/mergo" - -func set(d map[string]interface{}, key string, value interface{}) map[string]interface{} { - d[key] = value - return d -} - -func unset(d map[string]interface{}, key string) map[string]interface{} { - delete(d, key) - return d -} - -func hasKey(d map[string]interface{}, key string) bool { - _, ok := d[key] - return ok -} - -func pluck(key string, d ...map[string]interface{}) []interface{} { - res := []interface{}{} - for _, dict := range d { - if val, ok := dict[key]; ok { - res = append(res, val) - } - } - return res -} - -func keys(dicts ...map[string]interface{}) []string { - k := []string{} - for _, dict := range dicts { - for key := range dict { - k = append(k, key) - } - } - return k -} - -func pick(dict map[string]interface{}, keys ...string) map[string]interface{} { - res := map[string]interface{}{} - for _, k := range keys { - if v, ok := dict[k]; ok { - res[k] = v - } - } - return res -} - -func omit(dict map[string]interface{}, keys ...string) map[string]interface{} { - res := map[string]interface{}{} - - omit := make(map[string]bool, len(keys)) - for _, k := range keys { - omit[k] = true - } - - for k, v := range dict { - if _, ok := omit[k]; !ok { - res[k] = v - } - } - return res -} - -func dict(v ...interface{}) map[string]interface{} { - dict := map[string]interface{}{} - lenv := len(v) - for i := 0; i < lenv; i += 2 { - key := strval(v[i]) - if i+1 >= lenv { - dict[key] = "" - continue - } - dict[key] = v[i+1] - } - return dict -} - -func merge(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} { - for _, src := range srcs { - if err := mergo.Merge(&dst, src); err != nil { - // Swallow errors inside of a template. - return "" - } - } - return dst -} - -func mergeOverwrite(dst map[string]interface{}, srcs ...map[string]interface{}) interface{} { - for _, src := range srcs { - if err := mergo.MergeWithOverwrite(&dst, src); err != nil { - // Swallow errors inside of a template. - return "" - } - } - return dst -} - -func values(dict map[string]interface{}) []interface{} { - values := []interface{}{} - for _, value := range dict { - values = append(values, value) - } - - return values -} diff --git a/vendor/github.com/Masterminds/sprig/doc.go b/vendor/github.com/Masterminds/sprig/doc.go deleted file mode 100644 index 8f8f1d737..000000000 --- a/vendor/github.com/Masterminds/sprig/doc.go +++ /dev/null @@ -1,19 +0,0 @@ -/* -Sprig: Template functions for Go. - -This package contains a number of utility functions for working with data -inside of Go `html/template` and `text/template` files. - -To add these functions, use the `template.Funcs()` method: - - t := templates.New("foo").Funcs(sprig.FuncMap()) - -Note that you should add the function map before you parse any template files. - - In several cases, Sprig reverses the order of arguments from the way they - appear in the standard library. This is to make it easier to pipe - arguments into functions. - -See http://masterminds.github.io/sprig/ for more detailed documentation on each of the available functions. -*/ -package sprig diff --git a/vendor/github.com/Masterminds/sprig/functions.go b/vendor/github.com/Masterminds/sprig/functions.go deleted file mode 100644 index 6397be696..000000000 --- a/vendor/github.com/Masterminds/sprig/functions.go +++ /dev/null @@ -1,288 +0,0 @@ -package sprig - -import ( - "errors" - "html/template" - "os" - "path" - "strconv" - "strings" - ttemplate "text/template" - "time" - - util "github.com/Masterminds/goutils" - "github.com/huandu/xstrings" -) - -// Produce the function map. -// -// Use this to pass the functions into the template engine: -// -// tpl := template.New("foo").Funcs(sprig.FuncMap())) -// -func FuncMap() template.FuncMap { - return HtmlFuncMap() -} - -// HermeticTextFuncMap returns a 'text/template'.FuncMap with only repeatable functions. -func HermeticTxtFuncMap() ttemplate.FuncMap { - r := TxtFuncMap() - for _, name := range nonhermeticFunctions { - delete(r, name) - } - return r -} - -// HermeticHtmlFuncMap returns an 'html/template'.Funcmap with only repeatable functions. -func HermeticHtmlFuncMap() template.FuncMap { - r := HtmlFuncMap() - for _, name := range nonhermeticFunctions { - delete(r, name) - } - return r -} - -// TextFuncMap returns a 'text/template'.FuncMap -func TxtFuncMap() ttemplate.FuncMap { - return ttemplate.FuncMap(GenericFuncMap()) -} - -// HtmlFuncMap returns an 'html/template'.Funcmap -func HtmlFuncMap() template.FuncMap { - return template.FuncMap(GenericFuncMap()) -} - -// GenericFuncMap returns a copy of the basic function map as a map[string]interface{}. -func GenericFuncMap() map[string]interface{} { - gfm := make(map[string]interface{}, len(genericMap)) - for k, v := range genericMap { - gfm[k] = v - } - return gfm -} - -// These functions are not guaranteed to evaluate to the same result for given input, because they -// refer to the environemnt or global state. -var nonhermeticFunctions = []string{ - // Date functions - "date", - "date_in_zone", - "date_modify", - "now", - "htmlDate", - "htmlDateInZone", - "dateInZone", - "dateModify", - - // Strings - "randAlphaNum", - "randAlpha", - "randAscii", - "randNumeric", - "uuidv4", - - // OS - "env", - "expandenv", -} - -var genericMap = map[string]interface{}{ - "hello": func() string { return "Hello!" }, - - // Date functions - "date": date, - "date_in_zone": dateInZone, - "date_modify": dateModify, - "now": func() time.Time { return time.Now() }, - "htmlDate": htmlDate, - "htmlDateInZone": htmlDateInZone, - "dateInZone": dateInZone, - "dateModify": dateModify, - "ago": dateAgo, - "toDate": toDate, - - // Strings - "abbrev": abbrev, - "abbrevboth": abbrevboth, - "trunc": trunc, - "trim": strings.TrimSpace, - "upper": strings.ToUpper, - "lower": strings.ToLower, - "title": strings.Title, - "untitle": untitle, - "substr": substring, - // Switch order so that "foo" | repeat 5 - "repeat": func(count int, str string) string { return strings.Repeat(str, count) }, - // Deprecated: Use trimAll. - "trimall": func(a, b string) string { return strings.Trim(b, a) }, - // Switch order so that "$foo" | trimall "$" - "trimAll": func(a, b string) string { return strings.Trim(b, a) }, - "trimSuffix": func(a, b string) string { return strings.TrimSuffix(b, a) }, - "trimPrefix": func(a, b string) string { return strings.TrimPrefix(b, a) }, - "nospace": util.DeleteWhiteSpace, - "initials": initials, - "randAlphaNum": randAlphaNumeric, - "randAlpha": randAlpha, - "randAscii": randAscii, - "randNumeric": randNumeric, - "swapcase": util.SwapCase, - "shuffle": xstrings.Shuffle, - "snakecase": xstrings.ToSnakeCase, - "camelcase": xstrings.ToCamelCase, - "kebabcase": xstrings.ToKebabCase, - "wrap": func(l int, s string) string { return util.Wrap(s, l) }, - "wrapWith": func(l int, sep, str string) string { return util.WrapCustom(str, l, sep, true) }, - // Switch order so that "foobar" | contains "foo" - "contains": func(substr string, str string) bool { return strings.Contains(str, substr) }, - "hasPrefix": func(substr string, str string) bool { return strings.HasPrefix(str, substr) }, - "hasSuffix": func(substr string, str string) bool { return strings.HasSuffix(str, substr) }, - "quote": quote, - "squote": squote, - "cat": cat, - "indent": indent, - "nindent": nindent, - "replace": replace, - "plural": plural, - "sha1sum": sha1sum, - "sha256sum": sha256sum, - "adler32sum": adler32sum, - "toString": strval, - - // Wrap Atoi to stop errors. - "atoi": func(a string) int { i, _ := strconv.Atoi(a); return i }, - "int64": toInt64, - "int": toInt, - "float64": toFloat64, - - //"gt": func(a, b int) bool {return a > b}, - //"gte": func(a, b int) bool {return a >= b}, - //"lt": func(a, b int) bool {return a < b}, - //"lte": func(a, b int) bool {return a <= b}, - - // split "/" foo/bar returns map[int]string{0: foo, 1: bar} - "split": split, - "splitList": func(sep, orig string) []string { return strings.Split(orig, sep) }, - // splitn "/" foo/bar/fuu returns map[int]string{0: foo, 1: bar/fuu} - "splitn": splitn, - "toStrings": strslice, - - "until": until, - "untilStep": untilStep, - - // VERY basic arithmetic. - "add1": func(i interface{}) int64 { return toInt64(i) + 1 }, - "add": func(i ...interface{}) int64 { - var a int64 = 0 - for _, b := range i { - a += toInt64(b) - } - return a - }, - "sub": func(a, b interface{}) int64 { return toInt64(a) - toInt64(b) }, - "div": func(a, b interface{}) int64 { return toInt64(a) / toInt64(b) }, - "mod": func(a, b interface{}) int64 { return toInt64(a) % toInt64(b) }, - "mul": func(a interface{}, v ...interface{}) int64 { - val := toInt64(a) - for _, b := range v { - val = val * toInt64(b) - } - return val - }, - "biggest": max, - "max": max, - "min": min, - "ceil": ceil, - "floor": floor, - "round": round, - - // string slices. Note that we reverse the order b/c that's better - // for template processing. - "join": join, - "sortAlpha": sortAlpha, - - // Defaults - "default": dfault, - "empty": empty, - "coalesce": coalesce, - "compact": compact, - "toJson": toJson, - "toPrettyJson": toPrettyJson, - "ternary": ternary, - - // Reflection - "typeOf": typeOf, - "typeIs": typeIs, - "typeIsLike": typeIsLike, - "kindOf": kindOf, - "kindIs": kindIs, - - // OS: - "env": func(s string) string { return os.Getenv(s) }, - "expandenv": func(s string) string { return os.ExpandEnv(s) }, - - // File Paths: - "base": path.Base, - "dir": path.Dir, - "clean": path.Clean, - "ext": path.Ext, - "isAbs": path.IsAbs, - - // Encoding: - "b64enc": base64encode, - "b64dec": base64decode, - "b32enc": base32encode, - "b32dec": base32decode, - - // Data Structures: - "tuple": list, // FIXME: with the addition of append/prepend these are no longer immutable. - "list": list, - "dict": dict, - "set": set, - "unset": unset, - "hasKey": hasKey, - "pluck": pluck, - "keys": keys, - "pick": pick, - "omit": omit, - "merge": merge, - "mergeOverwrite": mergeOverwrite, - "values": values, - - "append": push, "push": push, - "prepend": prepend, - "first": first, - "rest": rest, - "last": last, - "initial": initial, - "reverse": reverse, - "uniq": uniq, - "without": without, - "has": has, - "slice": slice, - - // Crypto: - "genPrivateKey": generatePrivateKey, - "derivePassword": derivePassword, - "buildCustomCert": buildCustomCertificate, - "genCA": generateCertificateAuthority, - "genSelfSignedCert": generateSelfSignedCertificate, - "genSignedCert": generateSignedCertificate, - - // UUIDs: - "uuidv4": uuidv4, - - // SemVer: - "semver": semver, - "semverCompare": semverCompare, - - // Flow Control: - "fail": func(msg string) (string, error) { return "", errors.New(msg) }, - - // Regex - "regexMatch": regexMatch, - "regexFindAll": regexFindAll, - "regexFind": regexFind, - "regexReplaceAll": regexReplaceAll, - "regexReplaceAllLiteral": regexReplaceAllLiteral, - "regexSplit": regexSplit, -} diff --git a/vendor/github.com/Masterminds/sprig/list.go b/vendor/github.com/Masterminds/sprig/list.go deleted file mode 100644 index 41e136625..000000000 --- a/vendor/github.com/Masterminds/sprig/list.go +++ /dev/null @@ -1,294 +0,0 @@ -package sprig - -import ( - "fmt" - "reflect" - "sort" -) - -// Reflection is used in these functions so that slices and arrays of strings, -// ints, and other types not implementing []interface{} can be worked with. -// For example, this is useful if you need to work on the output of regexs. - -func list(v ...interface{}) []interface{} { - return v -} - -func push(list interface{}, v interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - nl := make([]interface{}, l) - for i := 0; i < l; i++ { - nl[i] = l2.Index(i).Interface() - } - - return append(nl, v) - - default: - panic(fmt.Sprintf("Cannot push on type %s", tp)) - } -} - -func prepend(list interface{}, v interface{}) []interface{} { - //return append([]interface{}{v}, list...) - - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - nl := make([]interface{}, l) - for i := 0; i < l; i++ { - nl[i] = l2.Index(i).Interface() - } - - return append([]interface{}{v}, nl...) - - default: - panic(fmt.Sprintf("Cannot prepend on type %s", tp)) - } -} - -func last(list interface{}) interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - if l == 0 { - return nil - } - - return l2.Index(l - 1).Interface() - default: - panic(fmt.Sprintf("Cannot find last on type %s", tp)) - } -} - -func first(list interface{}) interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - if l == 0 { - return nil - } - - return l2.Index(0).Interface() - default: - panic(fmt.Sprintf("Cannot find first on type %s", tp)) - } -} - -func rest(list interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - if l == 0 { - return nil - } - - nl := make([]interface{}, l-1) - for i := 1; i < l; i++ { - nl[i-1] = l2.Index(i).Interface() - } - - return nl - default: - panic(fmt.Sprintf("Cannot find rest on type %s", tp)) - } -} - -func initial(list interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - if l == 0 { - return nil - } - - nl := make([]interface{}, l-1) - for i := 0; i < l-1; i++ { - nl[i] = l2.Index(i).Interface() - } - - return nl - default: - panic(fmt.Sprintf("Cannot find initial on type %s", tp)) - } -} - -func sortAlpha(list interface{}) []string { - k := reflect.Indirect(reflect.ValueOf(list)).Kind() - switch k { - case reflect.Slice, reflect.Array: - a := strslice(list) - s := sort.StringSlice(a) - s.Sort() - return s - } - return []string{strval(list)} -} - -func reverse(v interface{}) []interface{} { - tp := reflect.TypeOf(v).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(v) - - l := l2.Len() - // We do not sort in place because the incoming array should not be altered. - nl := make([]interface{}, l) - for i := 0; i < l; i++ { - nl[l-i-1] = l2.Index(i).Interface() - } - - return nl - default: - panic(fmt.Sprintf("Cannot find reverse on type %s", tp)) - } -} - -func compact(list interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - nl := []interface{}{} - var item interface{} - for i := 0; i < l; i++ { - item = l2.Index(i).Interface() - if !empty(item) { - nl = append(nl, item) - } - } - - return nl - default: - panic(fmt.Sprintf("Cannot compact on type %s", tp)) - } -} - -func uniq(list interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - dest := []interface{}{} - var item interface{} - for i := 0; i < l; i++ { - item = l2.Index(i).Interface() - if !inList(dest, item) { - dest = append(dest, item) - } - } - - return dest - default: - panic(fmt.Sprintf("Cannot find uniq on type %s", tp)) - } -} - -func inList(haystack []interface{}, needle interface{}) bool { - for _, h := range haystack { - if reflect.DeepEqual(needle, h) { - return true - } - } - return false -} - -func without(list interface{}, omit ...interface{}) []interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - res := []interface{}{} - var item interface{} - for i := 0; i < l; i++ { - item = l2.Index(i).Interface() - if !inList(omit, item) { - res = append(res, item) - } - } - - return res - default: - panic(fmt.Sprintf("Cannot find without on type %s", tp)) - } -} - -func has(needle interface{}, haystack interface{}) bool { - if haystack == nil { - return false - } - tp := reflect.TypeOf(haystack).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(haystack) - var item interface{} - l := l2.Len() - for i := 0; i < l; i++ { - item = l2.Index(i).Interface() - if reflect.DeepEqual(needle, item) { - return true - } - } - - return false - default: - panic(fmt.Sprintf("Cannot find has on type %s", tp)) - } -} - -// $list := [1, 2, 3, 4, 5] -// slice $list -> list[0:5] = list[:] -// slice $list 0 3 -> list[0:3] = list[:3] -// slice $list 3 5 -> list[3:5] -// slice $list 3 -> list[3:5] = list[3:] -func slice(list interface{}, indices ...interface{}) interface{} { - tp := reflect.TypeOf(list).Kind() - switch tp { - case reflect.Slice, reflect.Array: - l2 := reflect.ValueOf(list) - - l := l2.Len() - if l == 0 { - return nil - } - - var start, end int - if len(indices) > 0 { - start = toInt(indices[0]) - } - if len(indices) < 2 { - end = l - } else { - end = toInt(indices[1]) - } - - return l2.Slice(start, end).Interface() - default: - panic(fmt.Sprintf("list should be type of slice or array but %s", tp)) - } -} diff --git a/vendor/github.com/Masterminds/sprig/numeric.go b/vendor/github.com/Masterminds/sprig/numeric.go deleted file mode 100644 index 4bd89bf7f..000000000 --- a/vendor/github.com/Masterminds/sprig/numeric.go +++ /dev/null @@ -1,159 +0,0 @@ -package sprig - -import ( - "math" - "reflect" - "strconv" -) - -// toFloat64 converts 64-bit floats -func toFloat64(v interface{}) float64 { - if str, ok := v.(string); ok { - iv, err := strconv.ParseFloat(str, 64) - if err != nil { - return 0 - } - return iv - } - - val := reflect.Indirect(reflect.ValueOf(v)) - switch val.Kind() { - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return float64(val.Int()) - case reflect.Uint8, reflect.Uint16, reflect.Uint32: - return float64(val.Uint()) - case reflect.Uint, reflect.Uint64: - return float64(val.Uint()) - case reflect.Float32, reflect.Float64: - return val.Float() - case reflect.Bool: - if val.Bool() == true { - return 1 - } - return 0 - default: - return 0 - } -} - -func toInt(v interface{}) int { - //It's not optimal. Bud I don't want duplicate toInt64 code. - return int(toInt64(v)) -} - -// toInt64 converts integer types to 64-bit integers -func toInt64(v interface{}) int64 { - if str, ok := v.(string); ok { - iv, err := strconv.ParseInt(str, 10, 64) - if err != nil { - return 0 - } - return iv - } - - val := reflect.Indirect(reflect.ValueOf(v)) - switch val.Kind() { - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return val.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32: - return int64(val.Uint()) - case reflect.Uint, reflect.Uint64: - tv := val.Uint() - if tv <= math.MaxInt64 { - return int64(tv) - } - // TODO: What is the sensible thing to do here? - return math.MaxInt64 - case reflect.Float32, reflect.Float64: - return int64(val.Float()) - case reflect.Bool: - if val.Bool() == true { - return 1 - } - return 0 - default: - return 0 - } -} - -func max(a interface{}, i ...interface{}) int64 { - aa := toInt64(a) - for _, b := range i { - bb := toInt64(b) - if bb > aa { - aa = bb - } - } - return aa -} - -func min(a interface{}, i ...interface{}) int64 { - aa := toInt64(a) - for _, b := range i { - bb := toInt64(b) - if bb < aa { - aa = bb - } - } - return aa -} - -func until(count int) []int { - step := 1 - if count < 0 { - step = -1 - } - return untilStep(0, count, step) -} - -func untilStep(start, stop, step int) []int { - v := []int{} - - if stop < start { - if step >= 0 { - return v - } - for i := start; i > stop; i += step { - v = append(v, i) - } - return v - } - - if step <= 0 { - return v - } - for i := start; i < stop; i += step { - v = append(v, i) - } - return v -} - -func floor(a interface{}) float64 { - aa := toFloat64(a) - return math.Floor(aa) -} - -func ceil(a interface{}) float64 { - aa := toFloat64(a) - return math.Ceil(aa) -} - -func round(a interface{}, p int, r_opt ...float64) float64 { - roundOn := .5 - if len(r_opt) > 0 { - roundOn = r_opt[0] - } - val := toFloat64(a) - places := toFloat64(p) - - var round float64 - pow := math.Pow(10, places) - digit := pow * val - _, div := math.Modf(digit) - if div >= roundOn { - round = math.Ceil(digit) - } else { - round = math.Floor(digit) - } - return round / pow -} diff --git a/vendor/github.com/Masterminds/sprig/reflect.go b/vendor/github.com/Masterminds/sprig/reflect.go deleted file mode 100644 index 8a65c132f..000000000 --- a/vendor/github.com/Masterminds/sprig/reflect.go +++ /dev/null @@ -1,28 +0,0 @@ -package sprig - -import ( - "fmt" - "reflect" -) - -// typeIs returns true if the src is the type named in target. -func typeIs(target string, src interface{}) bool { - return target == typeOf(src) -} - -func typeIsLike(target string, src interface{}) bool { - t := typeOf(src) - return target == t || "*"+target == t -} - -func typeOf(src interface{}) string { - return fmt.Sprintf("%T", src) -} - -func kindIs(target string, src interface{}) bool { - return target == kindOf(src) -} - -func kindOf(src interface{}) string { - return reflect.ValueOf(src).Kind().String() -} diff --git a/vendor/github.com/Masterminds/sprig/regex.go b/vendor/github.com/Masterminds/sprig/regex.go deleted file mode 100644 index 2016f6633..000000000 --- a/vendor/github.com/Masterminds/sprig/regex.go +++ /dev/null @@ -1,35 +0,0 @@ -package sprig - -import ( - "regexp" -) - -func regexMatch(regex string, s string) bool { - match, _ := regexp.MatchString(regex, s) - return match -} - -func regexFindAll(regex string, s string, n int) []string { - r := regexp.MustCompile(regex) - return r.FindAllString(s, n) -} - -func regexFind(regex string, s string) string { - r := regexp.MustCompile(regex) - return r.FindString(s) -} - -func regexReplaceAll(regex string, s string, repl string) string { - r := regexp.MustCompile(regex) - return r.ReplaceAllString(s, repl) -} - -func regexReplaceAllLiteral(regex string, s string, repl string) string { - r := regexp.MustCompile(regex) - return r.ReplaceAllLiteralString(s, repl) -} - -func regexSplit(regex string, s string, n int) []string { - r := regexp.MustCompile(regex) - return r.Split(s, n) -} diff --git a/vendor/github.com/Masterminds/sprig/semver.go b/vendor/github.com/Masterminds/sprig/semver.go deleted file mode 100644 index c2bf8a1fd..000000000 --- a/vendor/github.com/Masterminds/sprig/semver.go +++ /dev/null @@ -1,23 +0,0 @@ -package sprig - -import ( - sv2 "github.com/Masterminds/semver" -) - -func semverCompare(constraint, version string) (bool, error) { - c, err := sv2.NewConstraint(constraint) - if err != nil { - return false, err - } - - v, err := sv2.NewVersion(version) - if err != nil { - return false, err - } - - return c.Check(v), nil -} - -func semver(version string) (*sv2.Version, error) { - return sv2.NewVersion(version) -} diff --git a/vendor/github.com/Masterminds/sprig/strings.go b/vendor/github.com/Masterminds/sprig/strings.go deleted file mode 100644 index 943fa3e8a..000000000 --- a/vendor/github.com/Masterminds/sprig/strings.go +++ /dev/null @@ -1,233 +0,0 @@ -package sprig - -import ( - "encoding/base32" - "encoding/base64" - "fmt" - "reflect" - "strconv" - "strings" - - util "github.com/Masterminds/goutils" -) - -func base64encode(v string) string { - return base64.StdEncoding.EncodeToString([]byte(v)) -} - -func base64decode(v string) string { - data, err := base64.StdEncoding.DecodeString(v) - if err != nil { - return err.Error() - } - return string(data) -} - -func base32encode(v string) string { - return base32.StdEncoding.EncodeToString([]byte(v)) -} - -func base32decode(v string) string { - data, err := base32.StdEncoding.DecodeString(v) - if err != nil { - return err.Error() - } - return string(data) -} - -func abbrev(width int, s string) string { - if width < 4 { - return s - } - r, _ := util.Abbreviate(s, width) - return r -} - -func abbrevboth(left, right int, s string) string { - if right < 4 || left > 0 && right < 7 { - return s - } - r, _ := util.AbbreviateFull(s, left, right) - return r -} -func initials(s string) string { - // Wrap this just to eliminate the var args, which templates don't do well. - return util.Initials(s) -} - -func randAlphaNumeric(count int) string { - // It is not possible, it appears, to actually generate an error here. - r, _ := util.CryptoRandomAlphaNumeric(count) - return r -} - -func randAlpha(count int) string { - r, _ := util.CryptoRandomAlphabetic(count) - return r -} - -func randAscii(count int) string { - r, _ := util.CryptoRandomAscii(count) - return r -} - -func randNumeric(count int) string { - r, _ := util.CryptoRandomNumeric(count) - return r -} - -func untitle(str string) string { - return util.Uncapitalize(str) -} - -func quote(str ...interface{}) string { - out := make([]string, 0, len(str)) - for _, s := range str { - if s != nil { - out = append(out, fmt.Sprintf("%q", strval(s))) - } - } - return strings.Join(out, " ") -} - -func squote(str ...interface{}) string { - out := make([]string, 0, len(str)) - for _, s := range str { - if s != nil { - out = append(out, fmt.Sprintf("'%v'", s)) - } - } - return strings.Join(out, " ") -} - -func cat(v ...interface{}) string { - v = removeNilElements(v) - r := strings.TrimSpace(strings.Repeat("%v ", len(v))) - return fmt.Sprintf(r, v...) -} - -func indent(spaces int, v string) string { - pad := strings.Repeat(" ", spaces) - return pad + strings.Replace(v, "\n", "\n"+pad, -1) -} - -func nindent(spaces int, v string) string { - return "\n" + indent(spaces, v) -} - -func replace(old, new, src string) string { - return strings.Replace(src, old, new, -1) -} - -func plural(one, many string, count int) string { - if count == 1 { - return one - } - return many -} - -func strslice(v interface{}) []string { - switch v := v.(type) { - case []string: - return v - case []interface{}: - b := make([]string, 0, len(v)) - for _, s := range v { - if s != nil { - b = append(b, strval(s)) - } - } - return b - default: - val := reflect.ValueOf(v) - switch val.Kind() { - case reflect.Array, reflect.Slice: - l := val.Len() - b := make([]string, 0, l) - for i := 0; i < l; i++ { - value := val.Index(i).Interface() - if value != nil { - b = append(b, strval(value)) - } - } - return b - default: - if v == nil { - return []string{} - } else { - return []string{strval(v)} - } - } - } -} - -func removeNilElements(v []interface{}) []interface{} { - newSlice := make([]interface{}, 0, len(v)) - for _, i := range v { - if i != nil { - newSlice = append(newSlice, i) - } - } - return newSlice -} - -func strval(v interface{}) string { - switch v := v.(type) { - case string: - return v - case []byte: - return string(v) - case error: - return v.Error() - case fmt.Stringer: - return v.String() - default: - return fmt.Sprintf("%v", v) - } -} - -func trunc(c int, s string) string { - if len(s) <= c { - return s - } - return s[0:c] -} - -func join(sep string, v interface{}) string { - return strings.Join(strslice(v), sep) -} - -func split(sep, orig string) map[string]string { - parts := strings.Split(orig, sep) - res := make(map[string]string, len(parts)) - for i, v := range parts { - res["_"+strconv.Itoa(i)] = v - } - return res -} - -func splitn(sep string, n int, orig string) map[string]string { - parts := strings.SplitN(orig, sep, n) - res := make(map[string]string, len(parts)) - for i, v := range parts { - res["_"+strconv.Itoa(i)] = v - } - return res -} - -// substring creates a substring of the given string. -// -// If start is < 0, this calls string[:end]. -// -// If start is >= 0 and end < 0 or end bigger than s length, this calls string[start:] -// -// Otherwise, this calls string[start, end]. -func substring(start, end int, s string) string { - if start < 0 { - return s[:end] - } - if end < 0 || end > len(s) { - return s[start:] - } - return s[start:end] -} 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/archive/tar/LICENSE b/vendor/github.com/Microsoft/go-winio/archive/tar/LICENSE deleted file mode 100644 index 744875676..000000000 --- a/vendor/github.com/Microsoft/go-winio/archive/tar/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/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go deleted file mode 100644 index 27d6ace0c..000000000 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ /dev/null @@ -1,270 +0,0 @@ -// +build windows - -package winio - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "runtime" - "syscall" - "unicode/utf16" -) - -//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 - BackupReparseData - BackupSparseBlock - BackupTxfsData -) - -const ( - StreamSparseAttributes = uint32(8) -) - -const ( - WRITE_DAC = 0x40000 - WRITE_OWNER = 0x80000 - ACCESS_SYSTEM_SECURITY = 0x1000000 -) - -// BackupHeader represents a backup stream of a file. -type BackupHeader struct { - 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 Write(). It skips the remainder of the current stream if -// it was not completely read. -func (r *BackupStreamReader) Next() (*BackupHeader, error) { - if r.bytesLeft > 0 { - if _, err := io.Copy(ioutil.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{"BackupRead", r.f.Name(), 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 -} - -// NewBackupFileWrtier 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{"BackupWrite", w.f.Name(), 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/file.go b/vendor/github.com/Microsoft/go-winio/file.go deleted file mode 100644 index 613f31b52..000000000 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ /dev/null @@ -1,295 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "runtime" - "sync" - "sync/atomic" - "syscall" - "time" -) - -//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 timeBeginPeriod(period uint32) (n int32) = winmm.timeBeginPeriod - -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) } - -const ( - cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 1 - cFILE_SKIP_SET_EVENT_ON_HANDLE = 2 -) - -var ( - ErrFileClosed = errors.New("file has already been closed") - ErrTimeout = &timeoutError{} -) - -type timeoutError struct{} - -func (e *timeoutError) Error() string { return "i/o timeout" } -func (e *timeoutError) Timeout() bool { return true } -func (e *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 - closing 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, cFILE_SKIP_COMPLETION_PORT_ON_SUCCESS|cFILE_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) { - return makeWin32File(h) -} - -// closeHandle closes the resources associated with a Win32 handle -func (f *win32File) closeHandle() { - if !f.closing { - // cancel all IO and wait for it to complete - f.closing = true - cancelIoEx(f.handle, nil) - f.wg.Wait() - // at this point, no new IO can start - syscall.Close(f.handle) - f.handle = 0 - } -} - -// Close closes a win32File. -func (f *win32File) Close() error { - f.closeHandle() - return nil -} - -// 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.wg.Add(1) - if f.closing { - return nil, ErrFileClosed - } - c := &ioOperation{} - c.ch = make(chan ioResult) - return c, nil -} - -// ioCompletionProcessor processes completed async IOs forever -func ioCompletionProcessor(h syscall.Handle) { - // Set the timer resolution to 1. This fixes a performance regression in golang 1.6. - timeBeginPeriod(1) - 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} - } -} - -// 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 { - return int(bytes), err - } - - if f.closing { - 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 { - if f.closing { - err = ErrFileClosed - } - } - case <-timeout: - cancelIoEx(f.handle, &c.o) - r = <-c.ch - err = r.err - if err == syscall.ERROR_OPERATION_ABORTED { - 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. - 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 { - 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 (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 b1d60abb8..000000000 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ /dev/null @@ -1,60 +0,0 @@ -// +build windows - -package winio - -import ( - "os" - "runtime" - "syscall" - "unsafe" -) - -//sys getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = GetFileInformationByHandleEx -//sys setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) = SetFileInformationByHandle - -const ( - fileBasicInfo = 0 - fileIDInfo = 0x12 -) - -// FileBasicInfo contains file access time and file attributes information. -type FileBasicInfo struct { - CreationTime, LastAccessTime, LastWriteTime, ChangeTime syscall.Filetime - FileAttributes uintptr // includes padding -} - -// GetFileBasicInfo retrieves times and attributes for a file. -func GetFileBasicInfo(f *os.File) (*FileBasicInfo, error) { - bi := &FileBasicInfo{} - if err := getFileInformationByHandleEx(syscall.Handle(f.Fd()), 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 := setFileInformationByHandle(syscall.Handle(f.Fd()), 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 -} - -// 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 := getFileInformationByHandleEx(syscall.Handle(f.Fd()), 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/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go deleted file mode 100644 index da706cc8a..000000000 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ /dev/null @@ -1,404 +0,0 @@ -// +build windows - -package winio - -import ( - "errors" - "io" - "net" - "os" - "syscall" - "time" - "unsafe" -) - -//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 createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.Handle, err error) [failretval==syscall.InvalidHandle] = CreateFileW -//sys waitNamedPipe(name string, timeout uint32) (err error) = WaitNamedPipeW -//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 - -const ( - cERROR_PIPE_BUSY = syscall.Errno(231) - cERROR_PIPE_CONNECTED = syscall.Errno(535) - cERROR_SEM_TIMEOUT = syscall.Errno(121) - - cPIPE_ACCESS_DUPLEX = 0x3 - cFILE_FLAG_FIRST_PIPE_INSTANCE = 0x80000 - cSECURITY_SQOS_PRESENT = 0x100000 - cSECURITY_ANONYMOUS = 0 - - cPIPE_REJECT_REMOTE_CLIENTS = 0x8 - - cPIPE_UNLIMITED_INSTANCES = 255 - - cNMPWAIT_USE_DEFAULT_WAIT = 0 - cNMPWAIT_NOWAIT = 1 - - cPIPE_TYPE_MESSAGE = 4 - - cPIPE_READMODE_MESSAGE = 2 -) - -var ( - // ErrPipeListenerClosed is returned for pipe operations on listeners that have been closed. - // This error should match net.errClosing since docker takes a dependency on its text. - ErrPipeListenerClosed = errors.New("use of closed network connection") - - 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 { - f.SetReadDeadline(t) - f.SetWriteDeadline(t) - return nil -} - -// 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 { - // 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 - } - return n, err -} - -func (s pipeAddress) Network() string { - return "pipe" -} - -func (s pipeAddress) String() string { - return string(s) -} - -// DialPipe connects to a named pipe by path, timing out if the connection -// takes longer than the specified duration. If timeout is nil, then the timeout -// is the default timeout established by the pipe server. -func DialPipe(path string, timeout *time.Duration) (net.Conn, error) { - var absTimeout time.Time - if timeout != nil { - absTimeout = time.Now().Add(*timeout) - } - var err error - var h syscall.Handle - for { - h, err = createFile(path, syscall.GENERIC_READ|syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_OVERLAPPED|cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err != cERROR_PIPE_BUSY { - break - } - now := time.Now() - var ms uint32 - if absTimeout.IsZero() { - ms = cNMPWAIT_USE_DEFAULT_WAIT - } else if now.After(absTimeout) { - ms = cNMPWAIT_NOWAIT - } else { - ms = uint32(absTimeout.Sub(now).Nanoseconds() / 1000 / 1000) - } - err = waitNamedPipe(path, ms) - if err != nil { - if err == cERROR_SEM_TIMEOUT { - return nil, ErrTimeout - } - break - } - } - if err != nil { - return nil, &os.PathError{Op: "open", Path: path, Err: err} - } - - var flags uint32 - err = getNamedPipeInfo(h, &flags, nil, nil, nil) - if err != nil { - return nil, err - } - - var state uint32 - err = getNamedPipeHandleState(h, &state, nil, nil, nil, nil, 0) - if err != nil { - return nil, err - } - - if state&cPIPE_READMODE_MESSAGE != 0 { - return nil, &os.PathError{Op: "open", Path: path, Err: errors.New("message readmode pipes not supported")} - } - - 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&cPIPE_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 - securityDescriptor []byte - config PipeConfig - acceptCh chan (chan acceptResponse) - closeCh chan int - doneCh chan int -} - -func makeServerPipeHandle(path string, securityDescriptor []byte, c *PipeConfig, first bool) (syscall.Handle, error) { - var flags uint32 = cPIPE_ACCESS_DUPLEX | syscall.FILE_FLAG_OVERLAPPED - if first { - flags |= cFILE_FLAG_FIRST_PIPE_INSTANCE - } - - var mode uint32 = cPIPE_REJECT_REMOTE_CLIENTS - if c.MessageMode { - mode |= cPIPE_TYPE_MESSAGE - } - - sa := &syscall.SecurityAttributes{} - sa.Length = uint32(unsafe.Sizeof(*sa)) - if securityDescriptor != nil { - len := uint32(len(securityDescriptor)) - sa.SecurityDescriptor = localAlloc(0, len) - defer localFree(sa.SecurityDescriptor) - copy((*[0xffff]byte)(unsafe.Pointer(sa.SecurityDescriptor))[:], securityDescriptor) - } - h, err := createNamedPipe(path, flags, mode, cPIPE_UNLIMITED_INSTANCES, uint32(c.OutputBufferSize), uint32(c.InputBufferSize), 0, sa) - if err != nil { - return 0, &os.PathError{Op: "open", Path: path, Err: err} - } - return h, nil -} - -func (l *win32PipeListener) makeServerPipe() (*win32File, error) { - h, err := makeServerPipeHandle(l.path, l.securityDescriptor, &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) listenerRoutine() { - closed := false - for !closed { - select { - case <-l.closeCh: - closed = true - case responseCh := <-l.acceptCh: - p, err := l.makeServerPipe() - if err == nil { - // Wait for the client to connect. - ch := make(chan error) - go func() { - ch <- connectPipe(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 { - err = ErrPipeListenerClosed - } - closed = true - } - } - responseCh <- acceptResponse{p, err} - } - } - 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 the input buffer, in bytes. - InputBufferSize int32 - - // OutputBufferSize specifies the size the input 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 - } - // Immediately open and then close a client handle so that the named pipe is - // created but not currently accepting connections. - h2, err := createFile(path, 0, 0, nil, syscall.OPEN_EXISTING, cSECURITY_SQOS_PRESENT|cSECURITY_ANONYMOUS, 0) - if err != nil { - syscall.Close(h) - return nil, err - } - syscall.Close(h2) - l := &win32PipeListener{ - firstHandle: h, - path: path, - securityDescriptor: sd, - 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 != cERROR_PIPE_CONNECTED { - 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/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go deleted file mode 100644 index 9c83d36fe..000000000 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ /dev/null @@ -1,202 +0,0 @@ -// +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 ( - SE_PRIVILEGE_ENABLED = 2 - - ERROR_NOT_ALL_ASSIGNED syscall.Errno = 1300 - - SeBackupPrivilege = "SeBackupPrivilege" - SeRestorePrivilege = "SeRestorePrivilege" -) - -const ( - securityAnonymous = iota - securityIdentification - securityImpersonation - securityDelegation -) - -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 := "" - if len(e.privileges) > 1 { - s = "Could not enable privileges " - } else { - s = "Could not enable privilege " - } - 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) { - var privileges []uint64 - 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.GetCurrentProcess() - 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 { - 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(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 fc1ee4d3a..000000000 --- a/vendor/github.com/Microsoft/go-winio/reparse.go +++ /dev/null @@ -1,128 +0,0 @@ -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 db1b370a1..000000000 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ /dev/null @@ -1,98 +0,0 @@ -// +build windows - -package winio - -import ( - "syscall" - "unsafe" -) - -//sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW -//sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW -//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 - -const ( - cERROR_NONE_MAPPED = syscall.Errno(1332) -) - -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 e.Err { - case cERROR_NONE_MAPPED: - s = "not found" - default: - s = e.Err.Error() - } - return "lookup account " + e.Name + ": " + s -} - -type SddlConversionError struct { - Sddl string - Err error -} - -func (e *SddlConversionError) Error() string { - return "convert " + e.Sddl + ": " + e.Err.Error() -} - -// LookupSidByName looks up the SID of an account by name -func LookupSidByName(name string) (sid string, err error) { - if name == "" { - return "", &AccountLookupError{name, cERROR_NONE_MAPPED} - } - - var sidSize, sidNameUse, refDomainSize uint32 - err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) - if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { - 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 -} - -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 including an aribtrary 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 20d64cf41..000000000 --- a/vendor/github.com/Microsoft/go-winio/syscall.go +++ /dev/null @@ -1,3 +0,0 @@ -package winio - -//go:generate go run $GOROOT/src/syscall/mksyscall_windows.go -output zsyscall_windows.go file.go pipe.go sd.go fileinfo.go privilege.go backup.go 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 4f7a52eeb..000000000 --- a/vendor/github.com/Microsoft/go-winio/zsyscall_windows.go +++ /dev/null @@ -1,528 +0,0 @@ -// MACHINE GENERATED BY 'go generate' COMMAND; 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) -) - -// errnoErr returns common boxed Errno values, to prevent -// allocations at runtime. -func errnoErr(e syscall.Errno) error { - switch e { - case 0: - return nil - 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") - modwinmm = windows.NewLazySystemDLL("winmm.dll") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - - procCancelIoEx = modkernel32.NewProc("CancelIoEx") - procCreateIoCompletionPort = modkernel32.NewProc("CreateIoCompletionPort") - procGetQueuedCompletionStatus = modkernel32.NewProc("GetQueuedCompletionStatus") - procSetFileCompletionNotificationModes = modkernel32.NewProc("SetFileCompletionNotificationModes") - proctimeBeginPeriod = modwinmm.NewProc("timeBeginPeriod") - procConnectNamedPipe = modkernel32.NewProc("ConnectNamedPipe") - procCreateNamedPipeW = modkernel32.NewProc("CreateNamedPipeW") - procCreateFileW = modkernel32.NewProc("CreateFileW") - procWaitNamedPipeW = modkernel32.NewProc("WaitNamedPipeW") - procGetNamedPipeInfo = modkernel32.NewProc("GetNamedPipeInfo") - procGetNamedPipeHandleStateW = modkernel32.NewProc("GetNamedPipeHandleStateW") - procLocalAlloc = modkernel32.NewProc("LocalAlloc") - procLookupAccountNameW = modadvapi32.NewProc("LookupAccountNameW") - procConvertSidToStringSidW = modadvapi32.NewProc("ConvertSidToStringSidW") - procConvertStringSecurityDescriptorToSecurityDescriptorW = modadvapi32.NewProc("ConvertStringSecurityDescriptorToSecurityDescriptorW") - procConvertSecurityDescriptorToStringSecurityDescriptorW = modadvapi32.NewProc("ConvertSecurityDescriptorToStringSecurityDescriptorW") - procLocalFree = modkernel32.NewProc("LocalFree") - procGetSecurityDescriptorLength = modadvapi32.NewProc("GetSecurityDescriptorLength") - procGetFileInformationByHandleEx = modkernel32.NewProc("GetFileInformationByHandleEx") - procSetFileInformationByHandle = modkernel32.NewProc("SetFileInformationByHandle") - procAdjustTokenPrivileges = modadvapi32.NewProc("AdjustTokenPrivileges") - procImpersonateSelf = modadvapi32.NewProc("ImpersonateSelf") - procRevertToSelf = modadvapi32.NewProc("RevertToSelf") - procOpenThreadToken = modadvapi32.NewProc("OpenThreadToken") - procGetCurrentThread = modkernel32.NewProc("GetCurrentThread") - procLookupPrivilegeValueW = modadvapi32.NewProc("LookupPrivilegeValueW") - procLookupPrivilegeNameW = modadvapi32.NewProc("LookupPrivilegeNameW") - procLookupPrivilegeDisplayNameW = modadvapi32.NewProc("LookupPrivilegeDisplayNameW") - procBackupRead = modkernel32.NewProc("BackupRead") - procBackupWrite = modkernel32.NewProc("BackupWrite") -) - -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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func timeBeginPeriod(period uint32) (n int32) { - r0, _, _ := syscall.Syscall(proctimeBeginPeriod.Addr(), 1, uintptr(period), 0, 0) - n = int32(r0) - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func createFile(name string, access uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.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 uint32, mode uint32, sa *syscall.SecurityAttributes, createmode uint32, attrs uint32, templatefile syscall.Handle) (handle syscall.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 = syscall.Handle(r0) - if handle == syscall.InvalidHandle { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func waitNamedPipe(name string, timeout uint32) (err error) { - var _p0 *uint16 - _p0, err = syscall.UTF16PtrFromString(name) - if err != nil { - return - } - return _waitNamedPipe(_p0, timeout) -} - -func _waitNamedPipe(name *uint16, timeout uint32) (err error) { - r1, _, e1 := syscall.Syscall(procWaitNamedPipeW.Addr(), 2, uintptr(unsafe.Pointer(name)), uintptr(timeout), 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func localFree(mem uintptr) { - syscall.Syscall(procLocalFree.Addr(), 1, uintptr(mem), 0, 0) - return -} - -func getSecurityDescriptorLength(sd uintptr) (len uint32) { - r0, _, _ := syscall.Syscall(procGetSecurityDescriptorLength.Addr(), 1, uintptr(sd), 0, 0) - len = uint32(r0) - return -} - -func getFileInformationByHandleEx(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procGetFileInformationByHandleEx.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func setFileInformationByHandle(h syscall.Handle, class uint32, buffer *byte, size uint32) (err error) { - r1, _, e1 := syscall.Syscall6(procSetFileInformationByHandle.Addr(), 4, uintptr(h), uintptr(class), uintptr(unsafe.Pointer(buffer)), uintptr(size), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -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 - } else { - _p0 = 0 - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func impersonateSelf(level uint32) (err error) { - r1, _, e1 := syscall.Syscall(procImpersonateSelf.Addr(), 1, uintptr(level), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func revertToSelf() (err error) { - r1, _, e1 := syscall.Syscall(procRevertToSelf.Addr(), 0, 0, 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func openThreadToken(thread syscall.Handle, accessMask uint32, openAsSelf bool, token *windows.Token) (err error) { - var _p0 uint32 - if openAsSelf { - _p0 = 1 - } else { - _p0 = 0 - } - r1, _, e1 := syscall.Syscall6(procOpenThreadToken.Addr(), 4, uintptr(thread), uintptr(accessMask), uintptr(_p0), uintptr(unsafe.Pointer(token)), 0, 0) - if r1 == 0 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - return -} - -func getCurrentThread() (h syscall.Handle) { - r0, _, _ := syscall.Syscall(procGetCurrentThread.Addr(), 0, 0, 0, 0) - h = syscall.Handle(r0) - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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 - } else { - _p1 = 0 - } - var _p2 uint32 - if processSecurity { - _p2 = 1 - } else { - _p2 = 0 - } - 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 { - if e1 != 0 { - err = errnoErr(e1) - } else { - err = syscall.EINVAL - } - } - 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/cmd/runhcs/LICENSE b/vendor/github.com/Microsoft/hcsshim/cmd/runhcs/LICENSE deleted file mode 100644 index 27448585a..000000000 --- a/vendor/github.com/Microsoft/hcsshim/cmd/runhcs/LICENSE +++ /dev/null @@ -1,191 +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 - - Copyright 2014 Docker, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/Microsoft/hcsshim/cmd/runhcs/NOTICE b/vendor/github.com/Microsoft/hcsshim/cmd/runhcs/NOTICE deleted file mode 100644 index e40e44207..000000000 --- a/vendor/github.com/Microsoft/hcsshim/cmd/runhcs/NOTICE +++ /dev/null @@ -1,22 +0,0 @@ -runhcs is a fork of runc. - -The following is runc's legal notice. - ---- - -runc - -Copyright 2012-2015 Docker, Inc. - -This product includes software developed at Docker, Inc. (http://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 http://www.bis.doc.gov - -See also http://www.apache.org/dev/crypto.html and/or seek legal counsel. \ No newline at end of file diff --git a/vendor/github.com/Microsoft/hcsshim/osversion/osversion.go b/vendor/github.com/Microsoft/hcsshim/osversion/osversion.go deleted file mode 100644 index 916950c02..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/osversion.go +++ /dev/null @@ -1,51 +0,0 @@ -package osversion - -import ( - "fmt" - - "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 -} - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx -type osVersionInfoEx struct { - OSVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformID uint32 - CSDVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - Reserve byte -} - -// Get gets the operating system version on Windows. -// The calling application must be manifested to get the correct version information. -func Get() OSVersion { - 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 -} - -func (osv OSVersion) ToString() string { - return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.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 2d9567f6f..000000000 --- a/vendor/github.com/Microsoft/hcsshim/osversion/windowsbuilds.go +++ /dev/null @@ -1,10 +0,0 @@ -package osversion - -const ( - - // RS2 was a client-only release in case you're asking why it's not in the list. - RS1 = 14393 - RS3 = 16299 - RS4 = 17134 - RS5 = 17763 -) diff --git a/vendor/github.com/Microsoft/hcsshim/pkg/go-runhcs/LICENSE b/vendor/github.com/Microsoft/hcsshim/pkg/go-runhcs/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/Microsoft/hcsshim/pkg/go-runhcs/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/Microsoft/hcsshim/pkg/go-runhcs/NOTICE b/vendor/github.com/Microsoft/hcsshim/pkg/go-runhcs/NOTICE deleted file mode 100644 index 5f9d59f13..000000000 --- a/vendor/github.com/Microsoft/hcsshim/pkg/go-runhcs/NOTICE +++ /dev/null @@ -1,22 +0,0 @@ -go-runhcs is a fork of go-runc - -The following is runc's legal notice. - ---- - -runc - -Copyright 2012-2015 Docker, Inc. - -This product includes software developed at Docker, Inc. (http://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 http://www.bis.doc.gov - -See also http://www.apache.org/dev/crypto.html and/or seek legal counsel. \ No newline at end of file diff --git a/vendor/github.com/NYTimes/gziphandler/LICENSE b/vendor/github.com/NYTimes/gziphandler/LICENSE deleted file mode 100644 index df6192d36..000000000 --- a/vendor/github.com/NYTimes/gziphandler/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 2016-2017 The New York Times Company - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/NYTimes/gziphandler/gzip.go b/vendor/github.com/NYTimes/gziphandler/gzip.go deleted file mode 100644 index ae1ebe4bf..000000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip.go +++ /dev/null @@ -1,428 +0,0 @@ -package gziphandler - -import ( - "bufio" - "compress/gzip" - "fmt" - "io" - "net" - "net/http" - "strconv" - "strings" - "sync" -) - -const ( - vary = "Vary" - acceptEncoding = "Accept-Encoding" - contentEncoding = "Content-Encoding" - contentType = "Content-Type" - contentLength = "Content-Length" -) - -type codings map[string]float64 - -const ( - // DefaultQValue is the default qvalue to assign to an encoding if no explicit qvalue is set. - // This is actually kind of ambiguous in RFC 2616, so hopefully it's correct. - // The examples seem to indicate that it is. - DefaultQValue = 1.0 - - // DefaultMinSize defines the minimum size to reach to enable compression. - // It's 512 bytes. - DefaultMinSize = 512 -) - -// gzipWriterPools stores a sync.Pool for each compression level for reuse of -// gzip.Writers. Use poolIndex to covert a compression level to an index into -// gzipWriterPools. -var gzipWriterPools [gzip.BestCompression - gzip.BestSpeed + 2]*sync.Pool - -func init() { - for i := gzip.BestSpeed; i <= gzip.BestCompression; i++ { - addLevelPool(i) - } - addLevelPool(gzip.DefaultCompression) -} - -// poolIndex maps a compression level to its index into gzipWriterPools. It -// assumes that level is a valid gzip compression level. -func poolIndex(level int) int { - // gzip.DefaultCompression == -1, so we need to treat it special. - if level == gzip.DefaultCompression { - return gzip.BestCompression - gzip.BestSpeed + 1 - } - return level - gzip.BestSpeed -} - -func addLevelPool(level int) { - gzipWriterPools[poolIndex(level)] = &sync.Pool{ - New: func() interface{} { - // NewWriterLevel only returns error on a bad level, we are guaranteeing - // that this will be a valid level so it is okay to ignore the returned - // error. - w, _ := gzip.NewWriterLevel(nil, level) - return w - }, - } -} - -// GzipResponseWriter provides an http.ResponseWriter interface, which gzips -// bytes before writing them to the underlying response. This doesn't close the -// writers, so don't forget to do that. -// It can be configured to skip response smaller than minSize. -type GzipResponseWriter struct { - http.ResponseWriter - index int // Index for gzipWriterPools. - gw *gzip.Writer - - code int // Saves the WriteHeader value. - - minSize int // Specifed the minimum response size to gzip. If the response length is bigger than this value, it is compressed. - buf []byte // Holds the first part of the write before reaching the minSize or the end of the write. - - contentTypes []string // Only compress if the response is one of these content-types. All are accepted if empty. -} - -type GzipResponseWriterWithCloseNotify struct { - *GzipResponseWriter -} - -func (w GzipResponseWriterWithCloseNotify) CloseNotify() <-chan bool { - return w.ResponseWriter.(http.CloseNotifier).CloseNotify() -} - -// Write appends data to the gzip writer. -func (w *GzipResponseWriter) Write(b []byte) (int, error) { - // If content type is not set. - if _, ok := w.Header()[contentType]; !ok { - // It infer it from the uncompressed body. - w.Header().Set(contentType, http.DetectContentType(b)) - } - - // GZIP responseWriter is initialized. Use the GZIP responseWriter. - if w.gw != nil { - n, err := w.gw.Write(b) - return n, err - } - - // Save the write into a buffer for later use in GZIP responseWriter (if content is long enough) or at close with regular responseWriter. - // On the first write, w.buf changes from nil to a valid slice - w.buf = append(w.buf, b...) - - // If the global writes are bigger than the minSize and we're about to write - // a response containing a content type we want to handle, enable - // compression. - if len(w.buf) >= w.minSize && handleContentType(w.contentTypes, w) && w.Header().Get(contentEncoding) == "" { - err := w.startGzip() - if err != nil { - return 0, err - } - } - - return len(b), nil -} - -// startGzip initialize any GZIP specific informations. -func (w *GzipResponseWriter) startGzip() error { - - // Set the GZIP header. - w.Header().Set(contentEncoding, "gzip") - - // if the Content-Length is already set, then calls to Write on gzip - // will fail to set the Content-Length header since its already set - // See: https://github.com/golang/go/issues/14975. - w.Header().Del(contentLength) - - // Write the header to gzip response. - if w.code != 0 { - w.ResponseWriter.WriteHeader(w.code) - } - - // Initialize the GZIP response. - w.init() - - // Flush the buffer into the gzip response. - n, err := w.gw.Write(w.buf) - - // This should never happen (per io.Writer docs), but if the write didn't - // accept the entire buffer but returned no specific error, we have no clue - // what's going on, so abort just to be safe. - if err == nil && n < len(w.buf) { - return io.ErrShortWrite - } - - w.buf = nil - return err -} - -// WriteHeader just saves the response code until close or GZIP effective writes. -func (w *GzipResponseWriter) WriteHeader(code int) { - if w.code == 0 { - w.code = code - } -} - -// init graps a new gzip writer from the gzipWriterPool and writes the correct -// content encoding header. -func (w *GzipResponseWriter) init() { - // Bytes written during ServeHTTP are redirected to this gzip writer - // before being written to the underlying response. - gzw := gzipWriterPools[w.index].Get().(*gzip.Writer) - gzw.Reset(w.ResponseWriter) - w.gw = gzw -} - -// Close will close the gzip.Writer and will put it back in the gzipWriterPool. -func (w *GzipResponseWriter) Close() error { - if w.gw == nil { - // Gzip not trigged yet, write out regular response. - if w.code != 0 { - w.ResponseWriter.WriteHeader(w.code) - } - if w.buf != nil { - _, writeErr := w.ResponseWriter.Write(w.buf) - // Returns the error if any at write. - if writeErr != nil { - return fmt.Errorf("gziphandler: write to regular responseWriter at close gets error: %q", writeErr.Error()) - } - } - return nil - } - - err := w.gw.Close() - gzipWriterPools[w.index].Put(w.gw) - w.gw = nil - return err -} - -// Flush flushes the underlying *gzip.Writer and then the underlying -// http.ResponseWriter if it is an http.Flusher. This makes GzipResponseWriter -// an http.Flusher. -func (w *GzipResponseWriter) Flush() { - if w.gw == nil { - // Only flush once startGzip has been called. - // - // Flush is thus a no-op until the written body - // exceeds minSize. - return - } - - w.gw.Flush() - - if fw, ok := w.ResponseWriter.(http.Flusher); ok { - fw.Flush() - } -} - -// Hijack implements http.Hijacker. If the underlying ResponseWriter is a -// Hijacker, its Hijack method is returned. Otherwise an error is returned. -func (w *GzipResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - if hj, ok := w.ResponseWriter.(http.Hijacker); ok { - return hj.Hijack() - } - return nil, nil, fmt.Errorf("http.Hijacker interface is not supported") -} - -// verify Hijacker interface implementation -var _ http.Hijacker = &GzipResponseWriter{} - -// MustNewGzipLevelHandler behaves just like NewGzipLevelHandler except that in -// an error case it panics rather than returning an error. -func MustNewGzipLevelHandler(level int) func(http.Handler) http.Handler { - wrap, err := NewGzipLevelHandler(level) - if err != nil { - panic(err) - } - return wrap -} - -// NewGzipLevelHandler returns a wrapper function (often known as middleware) -// which can be used to wrap an HTTP handler to transparently gzip the response -// body if the client supports it (via the Accept-Encoding header). Responses will -// be encoded at the given gzip compression level. An error will be returned only -// if an invalid gzip compression level is given, so if one can ensure the level -// is valid, the returned error can be safely ignored. -func NewGzipLevelHandler(level int) (func(http.Handler) http.Handler, error) { - return NewGzipLevelAndMinSize(level, DefaultMinSize) -} - -// NewGzipLevelAndMinSize behave as NewGzipLevelHandler except it let the caller -// specify the minimum size before compression. -func NewGzipLevelAndMinSize(level, minSize int) (func(http.Handler) http.Handler, error) { - return GzipHandlerWithOpts(CompressionLevel(level), MinSize(minSize)) -} - -func GzipHandlerWithOpts(opts ...option) (func(http.Handler) http.Handler, error) { - c := &config{ - level: gzip.DefaultCompression, - minSize: DefaultMinSize, - } - - for _, o := range opts { - o(c) - } - - if err := c.validate(); err != nil { - return nil, err - } - - return func(h http.Handler) http.Handler { - index := poolIndex(c.level) - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Add(vary, acceptEncoding) - if acceptsGzip(r) { - gw := &GzipResponseWriter{ - ResponseWriter: w, - index: index, - minSize: c.minSize, - contentTypes: c.contentTypes, - } - defer gw.Close() - - if _, ok := w.(http.CloseNotifier); ok { - gwcn := GzipResponseWriterWithCloseNotify{gw} - h.ServeHTTP(gwcn, r) - } else { - h.ServeHTTP(gw, r) - } - - } else { - h.ServeHTTP(w, r) - } - }) - }, nil -} - -// Used for functional configuration. -type config struct { - minSize int - level int - contentTypes []string -} - -func (c *config) validate() error { - if c.level != gzip.DefaultCompression && (c.level < gzip.BestSpeed || c.level > gzip.BestCompression) { - return fmt.Errorf("invalid compression level requested: %d", c.level) - } - - if c.minSize < 0 { - return fmt.Errorf("minimum size must be more than zero") - } - - return nil -} - -type option func(c *config) - -func MinSize(size int) option { - return func(c *config) { - c.minSize = size - } -} - -func CompressionLevel(level int) option { - return func(c *config) { - c.level = level - } -} - -func ContentTypes(types []string) option { - return func(c *config) { - c.contentTypes = []string{} - for _, v := range types { - c.contentTypes = append(c.contentTypes, strings.ToLower(v)) - } - } -} - -// GzipHandler wraps an HTTP handler, to transparently gzip the response body if -// the client supports it (via the Accept-Encoding header). This will compress at -// the default compression level. -func GzipHandler(h http.Handler) http.Handler { - wrapper, _ := NewGzipLevelHandler(gzip.DefaultCompression) - return wrapper(h) -} - -// acceptsGzip returns true if the given HTTP request indicates that it will -// accept a gzipped response. -func acceptsGzip(r *http.Request) bool { - acceptedEncodings, _ := parseEncodings(r.Header.Get(acceptEncoding)) - return acceptedEncodings["gzip"] > 0.0 -} - -// returns true if we've been configured to compress the specific content type. -func handleContentType(contentTypes []string, w http.ResponseWriter) bool { - // If contentTypes is empty we handle all content types. - if len(contentTypes) == 0 { - return true - } - - ct := strings.ToLower(w.Header().Get(contentType)) - for _, c := range contentTypes { - if c == ct { - return true - } - } - - return false -} - -// parseEncodings attempts to parse a list of codings, per RFC 2616, as might -// appear in an Accept-Encoding header. It returns a map of content-codings to -// quality values, and an error containing the errors encountered. It's probably -// safe to ignore those, because silently ignoring errors is how the internet -// works. -// -// See: http://tools.ietf.org/html/rfc2616#section-14.3. -func parseEncodings(s string) (codings, error) { - c := make(codings) - var e []string - - for _, ss := range strings.Split(s, ",") { - coding, qvalue, err := parseCoding(ss) - - if err != nil { - e = append(e, err.Error()) - } else { - c[coding] = qvalue - } - } - - // TODO (adammck): Use a proper multi-error struct, so the individual errors - // can be extracted if anyone cares. - if len(e) > 0 { - return c, fmt.Errorf("errors while parsing encodings: %s", strings.Join(e, ", ")) - } - - return c, nil -} - -// parseCoding parses a single conding (content-coding with an optional qvalue), -// as might appear in an Accept-Encoding header. It attempts to forgive minor -// formatting errors. -func parseCoding(s string) (coding string, qvalue float64, err error) { - for n, part := range strings.Split(s, ";") { - part = strings.TrimSpace(part) - qvalue = DefaultQValue - - if n == 0 { - coding = strings.ToLower(part) - } else if strings.HasPrefix(part, "q=") { - qvalue, err = strconv.ParseFloat(strings.TrimPrefix(part, "q="), 64) - - if qvalue < 0.0 { - qvalue = 0.0 - } else if qvalue > 1.0 { - qvalue = 1.0 - } - } - } - - if coding == "" { - err = fmt.Errorf("empty content-coding") - } - - return -} diff --git a/vendor/github.com/NYTimes/gziphandler/gzip_go18.go b/vendor/github.com/NYTimes/gziphandler/gzip_go18.go deleted file mode 100644 index fa9665b7e..000000000 --- a/vendor/github.com/NYTimes/gziphandler/gzip_go18.go +++ /dev/null @@ -1,43 +0,0 @@ -// +build go1.8 - -package gziphandler - -import "net/http" - -// Push initiates an HTTP/2 server push. -// Push returns ErrNotSupported if the client has disabled push or if push -// is not supported on the underlying connection. -func (w *GzipResponseWriter) Push(target string, opts *http.PushOptions) error { - pusher, ok := w.ResponseWriter.(http.Pusher) - if ok && pusher != nil { - return pusher.Push(target, setAcceptEncodingForPushOptions(opts)) - } - return http.ErrNotSupported -} - -// setAcceptEncodingForPushOptions sets "Accept-Encoding" : "gzip" for PushOptions without overriding existing headers. -func setAcceptEncodingForPushOptions(opts *http.PushOptions) *http.PushOptions { - - if opts == nil { - opts = &http.PushOptions{ - Header: http.Header{ - acceptEncoding: []string{"gzip"}, - }, - } - return opts - } - - if opts.Header == nil { - opts.Header = http.Header{ - acceptEncoding: []string{"gzip"}, - } - return opts - } - - if encoding := opts.Header.Get(acceptEncoding); encoding == "" { - opts.Header.Add(acceptEncoding, "gzip") - return opts - } - - return opts -} diff --git a/vendor/github.com/OpenDNS/vegadns2client/LICENSE b/vendor/github.com/OpenDNS/vegadns2client/LICENSE deleted file mode 100644 index f9361e31c..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/LICENSE +++ /dev/null @@ -1,13 +0,0 @@ -Copyright 2018, Cisco Systems, Inc. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/vendor/github.com/OpenDNS/vegadns2client/client.go b/vendor/github.com/OpenDNS/vegadns2client/client.go deleted file mode 100644 index 21096568a..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/client.go +++ /dev/null @@ -1,71 +0,0 @@ -package vegadns2client - -import ( - "fmt" - "net/http" - "net/url" - "strings" -) - -// VegaDNSClient - Struct for holding VegaDNSClient specific attributes -type VegaDNSClient struct { - client http.Client - baseurl string - version string - User string - Pass string - APIKey string - APISecret string - token Token -} - -// Send - Central place for sending requests -// Input: method, endpoint, params -// Output: *http.Response -func (vega *VegaDNSClient) Send(method string, endpoint string, params map[string]string) (*http.Response, error) { - vegaURL := vega.getURL(endpoint) - - p := url.Values{} - for k, v := range params { - p.Set(k, v) - } - - var err error - var req *http.Request - - if (method == "GET") || (method == "DELETE") { - vegaURL = fmt.Sprintf("%s?%s", vegaURL, p.Encode()) - req, err = http.NewRequest(method, vegaURL, nil) - } else { - req, err = http.NewRequest(method, vegaURL, strings.NewReader(p.Encode())) - } - - if err != nil { - return nil, fmt.Errorf("Error preparing request: %s", err) - } - - if vega.User != "" && vega.Pass != "" { - // Basic Auth - req.SetBasicAuth(vega.User, vega.Pass) - } else if vega.APIKey != "" && vega.APISecret != "" { - // OAuth - vega.getAuthToken() - err = vega.token.valid() - if err != nil { - return nil, err - } - req.Header.Set("Authorization", vega.getBearer()) - } - - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - return vega.client.Do(req) -} - -func (vega *VegaDNSClient) getURL(endpoint string) string { - return fmt.Sprintf("%s/%s/%s", vega.baseurl, vega.version, endpoint) -} - -func (vega *VegaDNSClient) stillAuthorized() error { - return vega.token.valid() -} diff --git a/vendor/github.com/OpenDNS/vegadns2client/domains.go b/vendor/github.com/OpenDNS/vegadns2client/domains.go deleted file mode 100644 index b9713f4ed..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/domains.go +++ /dev/null @@ -1,80 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "log" - "net/http" - "strings" -) - -// Domain - struct containing a domain object -type Domain struct { - Status string `json:"status"` - Domain string `json:"domain"` - DomainID int `json:"domain_id"` - OwnerID int `json:"owner_id"` -} - -// DomainResponse - api response of a domain list -type DomainResponse struct { - Status string `json:"status"` - Total int `json:"total_domains"` - Domains []Domain `json:"domains"` -} - -// GetDomainID - returns the id for a domain -// Input: domain -// Output: int, err -func (vega *VegaDNSClient) GetDomainID(domain string) (int, error) { - params := make(map[string]string) - params["search"] = domain - - resp, err := vega.Send("GET", "domains", params) - - if err != nil { - return -1, fmt.Errorf("Error sending GET to GetDomainID: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return -1, fmt.Errorf("Error reading response from GET to GetDomainID: %s", err) - } - if resp.StatusCode != http.StatusOK { - return -1, fmt.Errorf("Got bad answer from VegaDNS on GetDomainID. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - answer := DomainResponse{} - if err := json.Unmarshal(body, &answer); err != nil { - return -1, fmt.Errorf("Error unmarshalling body from GetDomainID: %s", err) - } - log.Println(answer) - for _, d := range answer.Domains { - if d.Domain == domain { - return d.DomainID, nil - } - } - - return -1, fmt.Errorf("Didnt find domain %s", domain) - -} - -// GetAuthZone retrieves the closest match to a given -// domain. Example: Given an argument "a.b.c.d.e", and a VegaDNS -// hosted domain of "c.d.e", GetClosestMatchingDomain will return -// "c.d.e". -func (vega *VegaDNSClient) GetAuthZone(fqdn string) (string, int, error) { - fqdn = strings.TrimSuffix(fqdn, ".") - numComponents := len(strings.Split(fqdn, ".")) - for i := 1; i < numComponents; i++ { - tmpHostname := strings.SplitN(fqdn, ".", i)[i-1] - log.Printf("tmpHostname for i = %d: %s\n", i, tmpHostname) - if domainID, err := vega.GetDomainID(tmpHostname); err == nil { - log.Printf("Found zone: %s\n\tShortened to %s\n", tmpHostname, strings.TrimSuffix(tmpHostname, ".")) - return strings.TrimSuffix(tmpHostname, "."), domainID, nil - } - } - log.Println("Unable to find hosted zone in vegadns") - return "", -1, fmt.Errorf("Unable to find auth zone for fqdn %s", fqdn) -} diff --git a/vendor/github.com/OpenDNS/vegadns2client/main.go b/vendor/github.com/OpenDNS/vegadns2client/main.go deleted file mode 100644 index 0d3e79a61..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/main.go +++ /dev/null @@ -1,19 +0,0 @@ -package vegadns2client - -import ( - "net/http" - "time" -) - -// NewVegaDNSClient - helper to instantiate a client -// Input: url string -// Output: VegaDNSClient -func NewVegaDNSClient(url string) VegaDNSClient { - httpClient := http.Client{Timeout: 15 * time.Second} - return VegaDNSClient{ - client: httpClient, - baseurl: url, - version: "1.0", - token: Token{}, - } -} diff --git a/vendor/github.com/OpenDNS/vegadns2client/records.go b/vendor/github.com/OpenDNS/vegadns2client/records.go deleted file mode 100644 index 36bd8d906..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/records.go +++ /dev/null @@ -1,113 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -// Record - struct representing a Record object -type Record struct { - Name string `json:"name"` - Value string `json:"value"` - RecordType string `json:"record_type"` - TTL int `json:"ttl"` - RecordID int `json:"record_id"` - LocationID string `json:"location_id"` - DomainID int `json:"domain_id"` -} - -// RecordsResponse - api response list of records -type RecordsResponse struct { - Status string `json:"status"` - Total int `json:"total_records"` - Domain Domain `json:"domain"` - Records []Record `json:"records"` -} - -// GetRecordID - helper to get the id of a record -// Input: domainID, record, recordType -// Output: int -func (vega *VegaDNSClient) GetRecordID(domainID int, record string, recordType string) (int, error) { - params := make(map[string]string) - params["domain_id"] = fmt.Sprintf("%d", domainID) - - resp, err := vega.Send("GET", "records", params) - - if err != nil { - return -1, fmt.Errorf("Error sending GET to GetRecordID: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return -1, fmt.Errorf("Error reading response from GetRecordID: %s", err) - } - if resp.StatusCode != http.StatusOK { - return -1, fmt.Errorf("Got bad answer from VegaDNS on GetRecordID. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - answer := RecordsResponse{} - if err := json.Unmarshal(body, &answer); err != nil { - return -1, fmt.Errorf("Error unmarshalling body from GetRecordID: %s", err) - } - - for _, r := range answer.Records { - if r.Name == record && r.RecordType == recordType { - return r.RecordID, nil - } - } - - return -1, errors.New("Couldnt find record") -} - -// CreateTXT - Creates a TXT record -// Input: domainID, fqdn, value, ttl -// Output: nil or error -func (vega *VegaDNSClient) CreateTXT(domainID int, fqdn string, value string, ttl int) error { - params := make(map[string]string) - - params["record_type"] = "TXT" - params["ttl"] = fmt.Sprintf("%d", ttl) - params["domain_id"] = fmt.Sprintf("%d", domainID) - params["name"] = strings.TrimSuffix(fqdn, ".") - params["value"] = value - - resp, err := vega.Send("POST", "records", params) - - if err != nil { - return fmt.Errorf("Send POST error in CreateTXT: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("Error reading POST response in CreateTXT: %s", err) - } - if resp.StatusCode != http.StatusCreated { - return fmt.Errorf("Got bad answer from VegaDNS on CreateTXT. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - return nil -} - -// DeleteRecord - deletes a record by id -// Input: recordID -// Output: nil or error -func (vega *VegaDNSClient) DeleteRecord(recordID int) error { - resp, err := vega.Send("DELETE", fmt.Sprintf("records/%d", recordID), nil) - if err != nil { - return fmt.Errorf("Send DELETE error in DeleteTXT: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("Error reading DELETE response in DeleteTXT: %s", err) - } - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("Got bad answer from VegaDNS on DeleteTXT. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - - return nil -} diff --git a/vendor/github.com/OpenDNS/vegadns2client/tokens.go b/vendor/github.com/OpenDNS/vegadns2client/tokens.go deleted file mode 100644 index 9e7706b09..000000000 --- a/vendor/github.com/OpenDNS/vegadns2client/tokens.go +++ /dev/null @@ -1,74 +0,0 @@ -package vegadns2client - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/url" - "strings" - "time" -) - -// Token - struct to hold token information -type Token struct { - Token string `json:"access_token"` - TokenType string `json:"token_type"` - ExpiresIn int `json:"expires_in"` - ExpiresAt time.Time -} - -func (t Token) valid() error { - if time.Now().UTC().After(t.ExpiresAt) { - return errors.New("Token Expired") - } - return nil -} - -func (vega *VegaDNSClient) getBearer() string { - if vega.token.valid() != nil { - vega.getAuthToken() - } - return vega.token.formatBearer() -} - -func (t Token) formatBearer() string { - return fmt.Sprintf("Bearer %s", t.Token) -} - -func (vega *VegaDNSClient) getAuthToken() { - tokenEndpoint := vega.getURL("token") - v := url.Values{} - v.Set("grant_type", "client_credentials") - - req, err := http.NewRequest("POST", tokenEndpoint, strings.NewReader(v.Encode())) - if err != nil { - log.Fatalf("Error forming POST to getAuthToken: %s", err) - } - req.SetBasicAuth(vega.APIKey, vega.APISecret) - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - issueTime := time.Now().UTC() - resp, err := vega.client.Do(req) - if err != nil { - log.Fatalf("Error sending POST to getAuthToken: %s", err) - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - log.Fatalf("Error reading response from POST to getAuthToken: %s", err) - } - if resp.StatusCode != http.StatusOK { - log.Fatalf("Got bad answer from VegaDNS on getAuthToken. Code: %d. Message: %s", resp.StatusCode, string(body)) - } - if err := json.Unmarshal(body, &vega.token); err != nil { - log.Fatalf("Error unmarshalling body of POST to getAuthToken: %s", err) - } - - if vega.token.TokenType != "bearer" { - log.Fatal("We don't support anything except bearer tokens") - } - vega.token.ExpiresAt = issueTime.Add(time.Duration(vega.token.ExpiresIn) * time.Second) -} diff --git a/vendor/github.com/Shopify/sarama/LICENSE b/vendor/github.com/Shopify/sarama/LICENSE deleted file mode 100644 index 8121b63b1..000000000 --- a/vendor/github.com/Shopify/sarama/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2013 Evan Huus - -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/Shopify/sarama/api_versions_request.go b/vendor/github.com/Shopify/sarama/api_versions_request.go deleted file mode 100644 index ab65f01cc..000000000 --- a/vendor/github.com/Shopify/sarama/api_versions_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package sarama - -type ApiVersionsRequest struct { -} - -func (r *ApiVersionsRequest) encode(pe packetEncoder) error { - return nil -} - -func (r *ApiVersionsRequest) decode(pd packetDecoder, version int16) (err error) { - return nil -} - -func (r *ApiVersionsRequest) key() int16 { - return 18 -} - -func (r *ApiVersionsRequest) version() int16 { - return 0 -} - -func (r *ApiVersionsRequest) requiredVersion() KafkaVersion { - return V0_10_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/api_versions_response.go b/vendor/github.com/Shopify/sarama/api_versions_response.go deleted file mode 100644 index 23bc326e1..000000000 --- a/vendor/github.com/Shopify/sarama/api_versions_response.go +++ /dev/null @@ -1,87 +0,0 @@ -package sarama - -type ApiVersionsResponseBlock struct { - ApiKey int16 - MinVersion int16 - MaxVersion int16 -} - -func (b *ApiVersionsResponseBlock) encode(pe packetEncoder) error { - pe.putInt16(b.ApiKey) - pe.putInt16(b.MinVersion) - pe.putInt16(b.MaxVersion) - return nil -} - -func (b *ApiVersionsResponseBlock) decode(pd packetDecoder) error { - var err error - - if b.ApiKey, err = pd.getInt16(); err != nil { - return err - } - - if b.MinVersion, err = pd.getInt16(); err != nil { - return err - } - - if b.MaxVersion, err = pd.getInt16(); err != nil { - return err - } - - return nil -} - -type ApiVersionsResponse struct { - Err KError - ApiVersions []*ApiVersionsResponseBlock -} - -func (r *ApiVersionsResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - if err := pe.putArrayLength(len(r.ApiVersions)); err != nil { - return err - } - for _, apiVersion := range r.ApiVersions { - if err := apiVersion.encode(pe); err != nil { - return err - } - } - return nil -} - -func (r *ApiVersionsResponse) decode(pd packetDecoder, version int16) error { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - r.Err = KError(kerr) - - numBlocks, err := pd.getArrayLength() - if err != nil { - return err - } - - r.ApiVersions = make([]*ApiVersionsResponseBlock, numBlocks) - for i := 0; i < numBlocks; i++ { - block := new(ApiVersionsResponseBlock) - if err := block.decode(pd); err != nil { - return err - } - r.ApiVersions[i] = block - } - - return nil -} - -func (r *ApiVersionsResponse) key() int16 { - return 18 -} - -func (r *ApiVersionsResponse) version() int16 { - return 0 -} - -func (r *ApiVersionsResponse) requiredVersion() KafkaVersion { - return V0_10_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/async_producer.go b/vendor/github.com/Shopify/sarama/async_producer.go deleted file mode 100644 index 6d71a6d8f..000000000 --- a/vendor/github.com/Shopify/sarama/async_producer.go +++ /dev/null @@ -1,904 +0,0 @@ -package sarama - -import ( - "fmt" - "sync" - "time" - - "github.com/eapache/go-resiliency/breaker" - "github.com/eapache/queue" -) - -// AsyncProducer publishes Kafka messages using a non-blocking API. It routes messages -// to the correct broker for the provided topic-partition, refreshing metadata as appropriate, -// and parses responses for errors. You must read from the Errors() channel or the -// producer will deadlock. You must call Close() or AsyncClose() on a producer to avoid -// leaks: it will not be garbage-collected automatically when it passes out of -// scope. -type AsyncProducer interface { - - // AsyncClose triggers a shutdown of the producer. The shutdown has completed - // when both the Errors and Successes channels have been closed. When calling - // AsyncClose, you *must* continue to read from those channels in order to - // drain the results of any messages in flight. - AsyncClose() - - // Close shuts down the producer and waits for any buffered messages to be - // flushed. You must call this function before a producer object passes out of - // scope, as it may otherwise leak memory. You must call this before calling - // Close on the underlying client. - Close() error - - // Input is the input channel for the user to write messages to that they - // wish to send. - Input() chan<- *ProducerMessage - - // Successes is the success output channel back to the user when Return.Successes is - // enabled. If Return.Successes is true, you MUST read from this channel or the - // Producer will deadlock. It is suggested that you send and read messages - // together in a single select statement. - Successes() <-chan *ProducerMessage - - // Errors is the error output channel back to the user. You MUST read from this - // channel or the Producer will deadlock when the channel is full. Alternatively, - // you can set Producer.Return.Errors in your config to false, which prevents - // errors to be returned. - Errors() <-chan *ProducerError -} - -type asyncProducer struct { - client Client - conf *Config - ownClient bool - - errors chan *ProducerError - input, successes, retries chan *ProducerMessage - inFlight sync.WaitGroup - - brokers map[*Broker]chan<- *ProducerMessage - brokerRefs map[chan<- *ProducerMessage]int - brokerLock sync.Mutex -} - -// NewAsyncProducer creates a new AsyncProducer using the given broker addresses and configuration. -func NewAsyncProducer(addrs []string, conf *Config) (AsyncProducer, error) { - client, err := NewClient(addrs, conf) - if err != nil { - return nil, err - } - - p, err := NewAsyncProducerFromClient(client) - if err != nil { - return nil, err - } - p.(*asyncProducer).ownClient = true - return p, nil -} - -// NewAsyncProducerFromClient creates a new Producer using the given client. It is still -// necessary to call Close() on the underlying client when shutting down this producer. -func NewAsyncProducerFromClient(client Client) (AsyncProducer, error) { - // Check that we are not dealing with a closed Client before processing any other arguments - if client.Closed() { - return nil, ErrClosedClient - } - - p := &asyncProducer{ - client: client, - conf: client.Config(), - errors: make(chan *ProducerError), - input: make(chan *ProducerMessage), - successes: make(chan *ProducerMessage), - retries: make(chan *ProducerMessage), - brokers: make(map[*Broker]chan<- *ProducerMessage), - brokerRefs: make(map[chan<- *ProducerMessage]int), - } - - // launch our singleton dispatchers - go withRecover(p.dispatcher) - go withRecover(p.retryHandler) - - return p, nil -} - -type flagSet int8 - -const ( - syn flagSet = 1 << iota // first message from partitionProducer to brokerProducer - fin // final message from partitionProducer to brokerProducer and back - shutdown // start the shutdown process -) - -// ProducerMessage is the collection of elements passed to the Producer in order to send a message. -type ProducerMessage struct { - Topic string // The Kafka topic for this message. - // The partitioning key for this message. Pre-existing Encoders include - // StringEncoder and ByteEncoder. - Key Encoder - // The actual message to store in Kafka. Pre-existing Encoders include - // StringEncoder and ByteEncoder. - Value Encoder - - // This field is used to hold arbitrary data you wish to include so it - // will be available when receiving on the Successes and Errors channels. - // Sarama completely ignores this field and is only to be used for - // pass-through data. - Metadata interface{} - - // Below this point are filled in by the producer as the message is processed - - // Offset is the offset of the message stored on the broker. This is only - // guaranteed to be defined if the message was successfully delivered and - // RequiredAcks is not NoResponse. - Offset int64 - // Partition is the partition that the message was sent to. This is only - // guaranteed to be defined if the message was successfully delivered. - Partition int32 - // Timestamp is the timestamp assigned to the message by the broker. This - // is only guaranteed to be defined if the message was successfully - // delivered, RequiredAcks is not NoResponse, and the Kafka broker is at - // least version 0.10.0. - Timestamp time.Time - - retries int - flags flagSet -} - -const producerMessageOverhead = 26 // the metadata overhead of CRC, flags, etc. - -func (m *ProducerMessage) byteSize() int { - size := producerMessageOverhead - if m.Key != nil { - size += m.Key.Length() - } - if m.Value != nil { - size += m.Value.Length() - } - return size -} - -func (m *ProducerMessage) clear() { - m.flags = 0 - m.retries = 0 -} - -// ProducerError is the type of error generated when the producer fails to deliver a message. -// It contains the original ProducerMessage as well as the actual error value. -type ProducerError struct { - Msg *ProducerMessage - Err error -} - -func (pe ProducerError) Error() string { - return fmt.Sprintf("kafka: Failed to produce message to topic %s: %s", pe.Msg.Topic, pe.Err) -} - -// ProducerErrors is a type that wraps a batch of "ProducerError"s and implements the Error interface. -// It can be returned from the Producer's Close method to avoid the need to manually drain the Errors channel -// when closing a producer. -type ProducerErrors []*ProducerError - -func (pe ProducerErrors) Error() string { - return fmt.Sprintf("kafka: Failed to deliver %d messages.", len(pe)) -} - -func (p *asyncProducer) Errors() <-chan *ProducerError { - return p.errors -} - -func (p *asyncProducer) Successes() <-chan *ProducerMessage { - return p.successes -} - -func (p *asyncProducer) Input() chan<- *ProducerMessage { - return p.input -} - -func (p *asyncProducer) Close() error { - p.AsyncClose() - - if p.conf.Producer.Return.Successes { - go withRecover(func() { - for range p.successes { - } - }) - } - - var errors ProducerErrors - if p.conf.Producer.Return.Errors { - for event := range p.errors { - errors = append(errors, event) - } - } else { - <-p.errors - } - - if len(errors) > 0 { - return errors - } - return nil -} - -func (p *asyncProducer) AsyncClose() { - go withRecover(p.shutdown) -} - -// singleton -// dispatches messages by topic -func (p *asyncProducer) dispatcher() { - handlers := make(map[string]chan<- *ProducerMessage) - shuttingDown := false - - for msg := range p.input { - if msg == nil { - Logger.Println("Something tried to send a nil message, it was ignored.") - continue - } - - if msg.flags&shutdown != 0 { - shuttingDown = true - p.inFlight.Done() - continue - } else if msg.retries == 0 { - if shuttingDown { - // we can't just call returnError here because that decrements the wait group, - // which hasn't been incremented yet for this message, and shouldn't be - pErr := &ProducerError{Msg: msg, Err: ErrShuttingDown} - if p.conf.Producer.Return.Errors { - p.errors <- pErr - } else { - Logger.Println(pErr) - } - continue - } - p.inFlight.Add(1) - } - - if msg.byteSize() > p.conf.Producer.MaxMessageBytes { - p.returnError(msg, ErrMessageSizeTooLarge) - continue - } - - handler := handlers[msg.Topic] - if handler == nil { - handler = p.newTopicProducer(msg.Topic) - handlers[msg.Topic] = handler - } - - handler <- msg - } - - for _, handler := range handlers { - close(handler) - } -} - -// one per topic -// partitions messages, then dispatches them by partition -type topicProducer struct { - parent *asyncProducer - topic string - input <-chan *ProducerMessage - - breaker *breaker.Breaker - handlers map[int32]chan<- *ProducerMessage - partitioner Partitioner -} - -func (p *asyncProducer) newTopicProducer(topic string) chan<- *ProducerMessage { - input := make(chan *ProducerMessage, p.conf.ChannelBufferSize) - tp := &topicProducer{ - parent: p, - topic: topic, - input: input, - breaker: breaker.New(3, 1, 10*time.Second), - handlers: make(map[int32]chan<- *ProducerMessage), - partitioner: p.conf.Producer.Partitioner(topic), - } - go withRecover(tp.dispatch) - return input -} - -func (tp *topicProducer) dispatch() { - for msg := range tp.input { - if msg.retries == 0 { - if err := tp.partitionMessage(msg); err != nil { - tp.parent.returnError(msg, err) - continue - } - } - - handler := tp.handlers[msg.Partition] - if handler == nil { - handler = tp.parent.newPartitionProducer(msg.Topic, msg.Partition) - tp.handlers[msg.Partition] = handler - } - - handler <- msg - } - - for _, handler := range tp.handlers { - close(handler) - } -} - -func (tp *topicProducer) partitionMessage(msg *ProducerMessage) error { - var partitions []int32 - - err := tp.breaker.Run(func() (err error) { - if tp.partitioner.RequiresConsistency() { - partitions, err = tp.parent.client.Partitions(msg.Topic) - } else { - partitions, err = tp.parent.client.WritablePartitions(msg.Topic) - } - return - }) - - if err != nil { - return err - } - - numPartitions := int32(len(partitions)) - - if numPartitions == 0 { - return ErrLeaderNotAvailable - } - - choice, err := tp.partitioner.Partition(msg, numPartitions) - - if err != nil { - return err - } else if choice < 0 || choice >= numPartitions { - return ErrInvalidPartition - } - - msg.Partition = partitions[choice] - - return nil -} - -// one per partition per topic -// dispatches messages to the appropriate broker -// also responsible for maintaining message order during retries -type partitionProducer struct { - parent *asyncProducer - topic string - partition int32 - input <-chan *ProducerMessage - - leader *Broker - breaker *breaker.Breaker - output chan<- *ProducerMessage - - // highWatermark tracks the "current" retry level, which is the only one where we actually let messages through, - // all other messages get buffered in retryState[msg.retries].buf to preserve ordering - // retryState[msg.retries].expectChaser simply tracks whether we've seen a fin message for a given level (and - // therefore whether our buffer is complete and safe to flush) - highWatermark int - retryState []partitionRetryState -} - -type partitionRetryState struct { - buf []*ProducerMessage - expectChaser bool -} - -func (p *asyncProducer) newPartitionProducer(topic string, partition int32) chan<- *ProducerMessage { - input := make(chan *ProducerMessage, p.conf.ChannelBufferSize) - pp := &partitionProducer{ - parent: p, - topic: topic, - partition: partition, - input: input, - - breaker: breaker.New(3, 1, 10*time.Second), - retryState: make([]partitionRetryState, p.conf.Producer.Retry.Max+1), - } - go withRecover(pp.dispatch) - return input -} - -func (pp *partitionProducer) dispatch() { - // try to prefetch the leader; if this doesn't work, we'll do a proper call to `updateLeader` - // on the first message - pp.leader, _ = pp.parent.client.Leader(pp.topic, pp.partition) - if pp.leader != nil { - pp.output = pp.parent.getBrokerProducer(pp.leader) - pp.parent.inFlight.Add(1) // we're generating a syn message; track it so we don't shut down while it's still inflight - pp.output <- &ProducerMessage{Topic: pp.topic, Partition: pp.partition, flags: syn} - } - - for msg := range pp.input { - if msg.retries > pp.highWatermark { - // a new, higher, retry level; handle it and then back off - pp.newHighWatermark(msg.retries) - time.Sleep(pp.parent.conf.Producer.Retry.Backoff) - } else if pp.highWatermark > 0 { - // we are retrying something (else highWatermark would be 0) but this message is not a *new* retry level - if msg.retries < pp.highWatermark { - // in fact this message is not even the current retry level, so buffer it for now (unless it's a just a fin) - if msg.flags&fin == fin { - pp.retryState[msg.retries].expectChaser = false - pp.parent.inFlight.Done() // this fin is now handled and will be garbage collected - } else { - pp.retryState[msg.retries].buf = append(pp.retryState[msg.retries].buf, msg) - } - continue - } else if msg.flags&fin == fin { - // this message is of the current retry level (msg.retries == highWatermark) and the fin flag is set, - // meaning this retry level is done and we can go down (at least) one level and flush that - pp.retryState[pp.highWatermark].expectChaser = false - pp.flushRetryBuffers() - pp.parent.inFlight.Done() // this fin is now handled and will be garbage collected - continue - } - } - - // if we made it this far then the current msg contains real data, and can be sent to the next goroutine - // without breaking any of our ordering guarantees - - if pp.output == nil { - if err := pp.updateLeader(); err != nil { - pp.parent.returnError(msg, err) - time.Sleep(pp.parent.conf.Producer.Retry.Backoff) - continue - } - Logger.Printf("producer/leader/%s/%d selected broker %d\n", pp.topic, pp.partition, pp.leader.ID()) - } - - pp.output <- msg - } - - if pp.output != nil { - pp.parent.unrefBrokerProducer(pp.leader, pp.output) - } -} - -func (pp *partitionProducer) newHighWatermark(hwm int) { - Logger.Printf("producer/leader/%s/%d state change to [retrying-%d]\n", pp.topic, pp.partition, hwm) - pp.highWatermark = hwm - - // send off a fin so that we know when everything "in between" has made it - // back to us and we can safely flush the backlog (otherwise we risk re-ordering messages) - pp.retryState[pp.highWatermark].expectChaser = true - pp.parent.inFlight.Add(1) // we're generating a fin message; track it so we don't shut down while it's still inflight - pp.output <- &ProducerMessage{Topic: pp.topic, Partition: pp.partition, flags: fin, retries: pp.highWatermark - 1} - - // a new HWM means that our current broker selection is out of date - Logger.Printf("producer/leader/%s/%d abandoning broker %d\n", pp.topic, pp.partition, pp.leader.ID()) - pp.parent.unrefBrokerProducer(pp.leader, pp.output) - pp.output = nil -} - -func (pp *partitionProducer) flushRetryBuffers() { - Logger.Printf("producer/leader/%s/%d state change to [flushing-%d]\n", pp.topic, pp.partition, pp.highWatermark) - for { - pp.highWatermark-- - - if pp.output == nil { - if err := pp.updateLeader(); err != nil { - pp.parent.returnErrors(pp.retryState[pp.highWatermark].buf, err) - goto flushDone - } - Logger.Printf("producer/leader/%s/%d selected broker %d\n", pp.topic, pp.partition, pp.leader.ID()) - } - - for _, msg := range pp.retryState[pp.highWatermark].buf { - pp.output <- msg - } - - flushDone: - pp.retryState[pp.highWatermark].buf = nil - if pp.retryState[pp.highWatermark].expectChaser { - Logger.Printf("producer/leader/%s/%d state change to [retrying-%d]\n", pp.topic, pp.partition, pp.highWatermark) - break - } else if pp.highWatermark == 0 { - Logger.Printf("producer/leader/%s/%d state change to [normal]\n", pp.topic, pp.partition) - break - } - } -} - -func (pp *partitionProducer) updateLeader() error { - return pp.breaker.Run(func() (err error) { - if err = pp.parent.client.RefreshMetadata(pp.topic); err != nil { - return err - } - - if pp.leader, err = pp.parent.client.Leader(pp.topic, pp.partition); err != nil { - return err - } - - pp.output = pp.parent.getBrokerProducer(pp.leader) - pp.parent.inFlight.Add(1) // we're generating a syn message; track it so we don't shut down while it's still inflight - pp.output <- &ProducerMessage{Topic: pp.topic, Partition: pp.partition, flags: syn} - - return nil - }) -} - -// one per broker; also constructs an associated flusher -func (p *asyncProducer) newBrokerProducer(broker *Broker) chan<- *ProducerMessage { - var ( - input = make(chan *ProducerMessage) - bridge = make(chan *produceSet) - responses = make(chan *brokerProducerResponse) - ) - - bp := &brokerProducer{ - parent: p, - broker: broker, - input: input, - output: bridge, - responses: responses, - buffer: newProduceSet(p), - currentRetries: make(map[string]map[int32]error), - } - go withRecover(bp.run) - - // minimal bridge to make the network response `select`able - go withRecover(func() { - for set := range bridge { - request := set.buildRequest() - - response, err := broker.Produce(request) - - responses <- &brokerProducerResponse{ - set: set, - err: err, - res: response, - } - } - close(responses) - }) - - return input -} - -type brokerProducerResponse struct { - set *produceSet - err error - res *ProduceResponse -} - -// groups messages together into appropriately-sized batches for sending to the broker -// handles state related to retries etc -type brokerProducer struct { - parent *asyncProducer - broker *Broker - - input <-chan *ProducerMessage - output chan<- *produceSet - responses <-chan *brokerProducerResponse - - buffer *produceSet - timer <-chan time.Time - timerFired bool - - closing error - currentRetries map[string]map[int32]error -} - -func (bp *brokerProducer) run() { - var output chan<- *produceSet - Logger.Printf("producer/broker/%d starting up\n", bp.broker.ID()) - - for { - select { - case msg := <-bp.input: - if msg == nil { - bp.shutdown() - return - } - - if msg.flags&syn == syn { - Logger.Printf("producer/broker/%d state change to [open] on %s/%d\n", - bp.broker.ID(), msg.Topic, msg.Partition) - if bp.currentRetries[msg.Topic] == nil { - bp.currentRetries[msg.Topic] = make(map[int32]error) - } - bp.currentRetries[msg.Topic][msg.Partition] = nil - bp.parent.inFlight.Done() - continue - } - - if reason := bp.needsRetry(msg); reason != nil { - bp.parent.retryMessage(msg, reason) - - if bp.closing == nil && msg.flags&fin == fin { - // we were retrying this partition but we can start processing again - delete(bp.currentRetries[msg.Topic], msg.Partition) - Logger.Printf("producer/broker/%d state change to [closed] on %s/%d\n", - bp.broker.ID(), msg.Topic, msg.Partition) - } - - continue - } - - if bp.buffer.wouldOverflow(msg) { - if err := bp.waitForSpace(msg); err != nil { - bp.parent.retryMessage(msg, err) - continue - } - } - - if err := bp.buffer.add(msg); err != nil { - bp.parent.returnError(msg, err) - continue - } - - if bp.parent.conf.Producer.Flush.Frequency > 0 && bp.timer == nil { - bp.timer = time.After(bp.parent.conf.Producer.Flush.Frequency) - } - case <-bp.timer: - bp.timerFired = true - case output <- bp.buffer: - bp.rollOver() - case response := <-bp.responses: - bp.handleResponse(response) - } - - if bp.timerFired || bp.buffer.readyToFlush() { - output = bp.output - } else { - output = nil - } - } -} - -func (bp *brokerProducer) shutdown() { - for !bp.buffer.empty() { - select { - case response := <-bp.responses: - bp.handleResponse(response) - case bp.output <- bp.buffer: - bp.rollOver() - } - } - close(bp.output) - for response := range bp.responses { - bp.handleResponse(response) - } - - Logger.Printf("producer/broker/%d shut down\n", bp.broker.ID()) -} - -func (bp *brokerProducer) needsRetry(msg *ProducerMessage) error { - if bp.closing != nil { - return bp.closing - } - - return bp.currentRetries[msg.Topic][msg.Partition] -} - -func (bp *brokerProducer) waitForSpace(msg *ProducerMessage) error { - Logger.Printf("producer/broker/%d maximum request accumulated, waiting for space\n", bp.broker.ID()) - - for { - select { - case response := <-bp.responses: - bp.handleResponse(response) - // handling a response can change our state, so re-check some things - if reason := bp.needsRetry(msg); reason != nil { - return reason - } else if !bp.buffer.wouldOverflow(msg) { - return nil - } - case bp.output <- bp.buffer: - bp.rollOver() - return nil - } - } -} - -func (bp *brokerProducer) rollOver() { - bp.timer = nil - bp.timerFired = false - bp.buffer = newProduceSet(bp.parent) -} - -func (bp *brokerProducer) handleResponse(response *brokerProducerResponse) { - if response.err != nil { - bp.handleError(response.set, response.err) - } else { - bp.handleSuccess(response.set, response.res) - } - - if bp.buffer.empty() { - bp.rollOver() // this can happen if the response invalidated our buffer - } -} - -func (bp *brokerProducer) handleSuccess(sent *produceSet, response *ProduceResponse) { - // we iterate through the blocks in the request set, not the response, so that we notice - // if the response is missing a block completely - sent.eachPartition(func(topic string, partition int32, msgs []*ProducerMessage) { - if response == nil { - // this only happens when RequiredAcks is NoResponse, so we have to assume success - bp.parent.returnSuccesses(msgs) - return - } - - block := response.GetBlock(topic, partition) - if block == nil { - bp.parent.returnErrors(msgs, ErrIncompleteResponse) - return - } - - switch block.Err { - // Success - case ErrNoError: - if bp.parent.conf.Version.IsAtLeast(V0_10_0_0) && !block.Timestamp.IsZero() { - for _, msg := range msgs { - msg.Timestamp = block.Timestamp - } - } - for i, msg := range msgs { - msg.Offset = block.Offset + int64(i) - } - bp.parent.returnSuccesses(msgs) - // Retriable errors - case ErrInvalidMessage, ErrUnknownTopicOrPartition, ErrLeaderNotAvailable, ErrNotLeaderForPartition, - ErrRequestTimedOut, ErrNotEnoughReplicas, ErrNotEnoughReplicasAfterAppend: - Logger.Printf("producer/broker/%d state change to [retrying] on %s/%d because %v\n", - bp.broker.ID(), topic, partition, block.Err) - bp.currentRetries[topic][partition] = block.Err - bp.parent.retryMessages(msgs, block.Err) - bp.parent.retryMessages(bp.buffer.dropPartition(topic, partition), block.Err) - // Other non-retriable errors - default: - bp.parent.returnErrors(msgs, block.Err) - } - }) -} - -func (bp *brokerProducer) handleError(sent *produceSet, err error) { - switch err.(type) { - case PacketEncodingError: - sent.eachPartition(func(topic string, partition int32, msgs []*ProducerMessage) { - bp.parent.returnErrors(msgs, err) - }) - default: - Logger.Printf("producer/broker/%d state change to [closing] because %s\n", bp.broker.ID(), err) - bp.parent.abandonBrokerConnection(bp.broker) - _ = bp.broker.Close() - bp.closing = err - sent.eachPartition(func(topic string, partition int32, msgs []*ProducerMessage) { - bp.parent.retryMessages(msgs, err) - }) - bp.buffer.eachPartition(func(topic string, partition int32, msgs []*ProducerMessage) { - bp.parent.retryMessages(msgs, err) - }) - bp.rollOver() - } -} - -// singleton -// effectively a "bridge" between the flushers and the dispatcher in order to avoid deadlock -// based on https://godoc.org/github.com/eapache/channels#InfiniteChannel -func (p *asyncProducer) retryHandler() { - var msg *ProducerMessage - buf := queue.New() - - for { - if buf.Length() == 0 { - msg = <-p.retries - } else { - select { - case msg = <-p.retries: - case p.input <- buf.Peek().(*ProducerMessage): - buf.Remove() - continue - } - } - - if msg == nil { - return - } - - buf.Add(msg) - } -} - -// utility functions - -func (p *asyncProducer) shutdown() { - Logger.Println("Producer shutting down.") - p.inFlight.Add(1) - p.input <- &ProducerMessage{flags: shutdown} - - p.inFlight.Wait() - - if p.ownClient { - err := p.client.Close() - if err != nil { - Logger.Println("producer/shutdown failed to close the embedded client:", err) - } - } - - close(p.input) - close(p.retries) - close(p.errors) - close(p.successes) -} - -func (p *asyncProducer) returnError(msg *ProducerMessage, err error) { - msg.clear() - pErr := &ProducerError{Msg: msg, Err: err} - if p.conf.Producer.Return.Errors { - p.errors <- pErr - } else { - Logger.Println(pErr) - } - p.inFlight.Done() -} - -func (p *asyncProducer) returnErrors(batch []*ProducerMessage, err error) { - for _, msg := range batch { - p.returnError(msg, err) - } -} - -func (p *asyncProducer) returnSuccesses(batch []*ProducerMessage) { - for _, msg := range batch { - if p.conf.Producer.Return.Successes { - msg.clear() - p.successes <- msg - } - p.inFlight.Done() - } -} - -func (p *asyncProducer) retryMessage(msg *ProducerMessage, err error) { - if msg.retries >= p.conf.Producer.Retry.Max { - p.returnError(msg, err) - } else { - msg.retries++ - p.retries <- msg - } -} - -func (p *asyncProducer) retryMessages(batch []*ProducerMessage, err error) { - for _, msg := range batch { - p.retryMessage(msg, err) - } -} - -func (p *asyncProducer) getBrokerProducer(broker *Broker) chan<- *ProducerMessage { - p.brokerLock.Lock() - defer p.brokerLock.Unlock() - - bp := p.brokers[broker] - - if bp == nil { - bp = p.newBrokerProducer(broker) - p.brokers[broker] = bp - p.brokerRefs[bp] = 0 - } - - p.brokerRefs[bp]++ - - return bp -} - -func (p *asyncProducer) unrefBrokerProducer(broker *Broker, bp chan<- *ProducerMessage) { - p.brokerLock.Lock() - defer p.brokerLock.Unlock() - - p.brokerRefs[bp]-- - if p.brokerRefs[bp] == 0 { - close(bp) - delete(p.brokerRefs, bp) - - if p.brokers[broker] == bp { - delete(p.brokers, broker) - } - } -} - -func (p *asyncProducer) abandonBrokerConnection(broker *Broker) { - p.brokerLock.Lock() - defer p.brokerLock.Unlock() - - delete(p.brokers, broker) -} diff --git a/vendor/github.com/Shopify/sarama/broker.go b/vendor/github.com/Shopify/sarama/broker.go deleted file mode 100644 index f57a69094..000000000 --- a/vendor/github.com/Shopify/sarama/broker.go +++ /dev/null @@ -1,685 +0,0 @@ -package sarama - -import ( - "crypto/tls" - "encoding/binary" - "fmt" - "io" - "net" - "strconv" - "sync" - "sync/atomic" - "time" - - "github.com/rcrowley/go-metrics" -) - -// Broker represents a single Kafka broker connection. All operations on this object are entirely concurrency-safe. -type Broker struct { - id int32 - addr string - - conf *Config - correlationID int32 - conn net.Conn - connErr error - lock sync.Mutex - opened int32 - - responses chan responsePromise - done chan bool - - incomingByteRate metrics.Meter - requestRate metrics.Meter - requestSize metrics.Histogram - requestLatency metrics.Histogram - outgoingByteRate metrics.Meter - responseRate metrics.Meter - responseSize metrics.Histogram - brokerIncomingByteRate metrics.Meter - brokerRequestRate metrics.Meter - brokerRequestSize metrics.Histogram - brokerRequestLatency metrics.Histogram - brokerOutgoingByteRate metrics.Meter - brokerResponseRate metrics.Meter - brokerResponseSize metrics.Histogram -} - -type responsePromise struct { - requestTime time.Time - correlationID int32 - packets chan []byte - errors chan error -} - -// NewBroker creates and returns a Broker targeting the given host:port address. -// This does not attempt to actually connect, you have to call Open() for that. -func NewBroker(addr string) *Broker { - return &Broker{id: -1, addr: addr} -} - -// Open tries to connect to the Broker if it is not already connected or connecting, but does not block -// waiting for the connection to complete. This means that any subsequent operations on the broker will -// block waiting for the connection to succeed or fail. To get the effect of a fully synchronous Open call, -// follow it by a call to Connected(). The only errors Open will return directly are ConfigurationError or -// AlreadyConnected. If conf is nil, the result of NewConfig() is used. -func (b *Broker) Open(conf *Config) error { - if !atomic.CompareAndSwapInt32(&b.opened, 0, 1) { - return ErrAlreadyConnected - } - - if conf == nil { - conf = NewConfig() - } - - err := conf.Validate() - if err != nil { - return err - } - - b.lock.Lock() - - go withRecover(func() { - defer b.lock.Unlock() - - dialer := net.Dialer{ - Timeout: conf.Net.DialTimeout, - KeepAlive: conf.Net.KeepAlive, - } - - if conf.Net.TLS.Enable { - b.conn, b.connErr = tls.DialWithDialer(&dialer, "tcp", b.addr, conf.Net.TLS.Config) - } else { - b.conn, b.connErr = dialer.Dial("tcp", b.addr) - } - if b.connErr != nil { - Logger.Printf("Failed to connect to broker %s: %s\n", b.addr, b.connErr) - b.conn = nil - atomic.StoreInt32(&b.opened, 0) - return - } - b.conn = newBufConn(b.conn) - - b.conf = conf - - // Create or reuse the global metrics shared between brokers - b.incomingByteRate = metrics.GetOrRegisterMeter("incoming-byte-rate", conf.MetricRegistry) - b.requestRate = metrics.GetOrRegisterMeter("request-rate", conf.MetricRegistry) - b.requestSize = getOrRegisterHistogram("request-size", conf.MetricRegistry) - b.requestLatency = getOrRegisterHistogram("request-latency-in-ms", conf.MetricRegistry) - b.outgoingByteRate = metrics.GetOrRegisterMeter("outgoing-byte-rate", conf.MetricRegistry) - b.responseRate = metrics.GetOrRegisterMeter("response-rate", conf.MetricRegistry) - b.responseSize = getOrRegisterHistogram("response-size", conf.MetricRegistry) - // Do not gather metrics for seeded broker (only used during bootstrap) because they share - // the same id (-1) and are already exposed through the global metrics above - if b.id >= 0 { - b.brokerIncomingByteRate = getOrRegisterBrokerMeter("incoming-byte-rate", b, conf.MetricRegistry) - b.brokerRequestRate = getOrRegisterBrokerMeter("request-rate", b, conf.MetricRegistry) - b.brokerRequestSize = getOrRegisterBrokerHistogram("request-size", b, conf.MetricRegistry) - b.brokerRequestLatency = getOrRegisterBrokerHistogram("request-latency-in-ms", b, conf.MetricRegistry) - b.brokerOutgoingByteRate = getOrRegisterBrokerMeter("outgoing-byte-rate", b, conf.MetricRegistry) - b.brokerResponseRate = getOrRegisterBrokerMeter("response-rate", b, conf.MetricRegistry) - b.brokerResponseSize = getOrRegisterBrokerHistogram("response-size", b, conf.MetricRegistry) - } - - if conf.Net.SASL.Enable { - b.connErr = b.sendAndReceiveSASLPlainAuth() - if b.connErr != nil { - err = b.conn.Close() - if err == nil { - Logger.Printf("Closed connection to broker %s\n", b.addr) - } else { - Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err) - } - b.conn = nil - atomic.StoreInt32(&b.opened, 0) - return - } - } - - b.done = make(chan bool) - b.responses = make(chan responsePromise, b.conf.Net.MaxOpenRequests-1) - - if b.id >= 0 { - Logger.Printf("Connected to broker at %s (registered as #%d)\n", b.addr, b.id) - } else { - Logger.Printf("Connected to broker at %s (unregistered)\n", b.addr) - } - go withRecover(b.responseReceiver) - }) - - return nil -} - -// Connected returns true if the broker is connected and false otherwise. If the broker is not -// connected but it had tried to connect, the error from that connection attempt is also returned. -func (b *Broker) Connected() (bool, error) { - b.lock.Lock() - defer b.lock.Unlock() - - return b.conn != nil, b.connErr -} - -func (b *Broker) Close() error { - b.lock.Lock() - defer b.lock.Unlock() - - if b.conn == nil { - return ErrNotConnected - } - - close(b.responses) - <-b.done - - err := b.conn.Close() - - b.conn = nil - b.connErr = nil - b.done = nil - b.responses = nil - - if err == nil { - Logger.Printf("Closed connection to broker %s\n", b.addr) - } else { - Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err) - } - - atomic.StoreInt32(&b.opened, 0) - - return err -} - -// ID returns the broker ID retrieved from Kafka's metadata, or -1 if that is not known. -func (b *Broker) ID() int32 { - return b.id -} - -// Addr returns the broker address as either retrieved from Kafka's metadata or passed to NewBroker. -func (b *Broker) Addr() string { - return b.addr -} - -func (b *Broker) GetMetadata(request *MetadataRequest) (*MetadataResponse, error) { - response := new(MetadataResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) GetConsumerMetadata(request *ConsumerMetadataRequest) (*ConsumerMetadataResponse, error) { - response := new(ConsumerMetadataResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) GetAvailableOffsets(request *OffsetRequest) (*OffsetResponse, error) { - response := new(OffsetResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) Produce(request *ProduceRequest) (*ProduceResponse, error) { - var response *ProduceResponse - var err error - - if request.RequiredAcks == NoResponse { - err = b.sendAndReceive(request, nil) - } else { - response = new(ProduceResponse) - err = b.sendAndReceive(request, response) - } - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) Fetch(request *FetchRequest) (*FetchResponse, error) { - response := new(FetchResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) CommitOffset(request *OffsetCommitRequest) (*OffsetCommitResponse, error) { - response := new(OffsetCommitResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) FetchOffset(request *OffsetFetchRequest) (*OffsetFetchResponse, error) { - response := new(OffsetFetchResponse) - - err := b.sendAndReceive(request, response) - - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) JoinGroup(request *JoinGroupRequest) (*JoinGroupResponse, error) { - response := new(JoinGroupResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) SyncGroup(request *SyncGroupRequest) (*SyncGroupResponse, error) { - response := new(SyncGroupResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) LeaveGroup(request *LeaveGroupRequest) (*LeaveGroupResponse, error) { - response := new(LeaveGroupResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) Heartbeat(request *HeartbeatRequest) (*HeartbeatResponse, error) { - response := new(HeartbeatResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) ListGroups(request *ListGroupsRequest) (*ListGroupsResponse, error) { - response := new(ListGroupsResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) DescribeGroups(request *DescribeGroupsRequest) (*DescribeGroupsResponse, error) { - response := new(DescribeGroupsResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) ApiVersions(request *ApiVersionsRequest) (*ApiVersionsResponse, error) { - response := new(ApiVersionsResponse) - - err := b.sendAndReceive(request, response) - if err != nil { - return nil, err - } - - return response, nil -} - -func (b *Broker) send(rb protocolBody, promiseResponse bool) (*responsePromise, error) { - b.lock.Lock() - defer b.lock.Unlock() - - if b.conn == nil { - if b.connErr != nil { - return nil, b.connErr - } - return nil, ErrNotConnected - } - - if !b.conf.Version.IsAtLeast(rb.requiredVersion()) { - return nil, ErrUnsupportedVersion - } - - req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb} - buf, err := encode(req, b.conf.MetricRegistry) - if err != nil { - return nil, err - } - - err = b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout)) - if err != nil { - return nil, err - } - - requestTime := time.Now() - bytes, err := b.conn.Write(buf) - b.updateOutgoingCommunicationMetrics(bytes) - if err != nil { - return nil, err - } - b.correlationID++ - - if !promiseResponse { - // Record request latency without the response - b.updateRequestLatencyMetrics(time.Since(requestTime)) - return nil, nil - } - - promise := responsePromise{requestTime, req.correlationID, make(chan []byte), make(chan error)} - b.responses <- promise - - return &promise, nil -} - -func (b *Broker) sendAndReceive(req protocolBody, res versionedDecoder) error { - promise, err := b.send(req, res != nil) - - if err != nil { - return err - } - - if promise == nil { - return nil - } - - select { - case buf := <-promise.packets: - return versionedDecode(buf, res, req.version()) - case err = <-promise.errors: - return err - } -} - -func (b *Broker) decode(pd packetDecoder) (err error) { - b.id, err = pd.getInt32() - if err != nil { - return err - } - - host, err := pd.getString() - if err != nil { - return err - } - - port, err := pd.getInt32() - if err != nil { - return err - } - - b.addr = net.JoinHostPort(host, fmt.Sprint(port)) - if _, _, err := net.SplitHostPort(b.addr); err != nil { - return err - } - - return nil -} - -func (b *Broker) encode(pe packetEncoder) (err error) { - - host, portstr, err := net.SplitHostPort(b.addr) - if err != nil { - return err - } - port, err := strconv.Atoi(portstr) - if err != nil { - return err - } - - pe.putInt32(b.id) - - err = pe.putString(host) - if err != nil { - return err - } - - pe.putInt32(int32(port)) - - return nil -} - -func (b *Broker) responseReceiver() { - var dead error - header := make([]byte, 8) - for response := range b.responses { - if dead != nil { - response.errors <- dead - continue - } - - err := b.conn.SetReadDeadline(time.Now().Add(b.conf.Net.ReadTimeout)) - if err != nil { - dead = err - response.errors <- err - continue - } - - bytesReadHeader, err := io.ReadFull(b.conn, header) - requestLatency := time.Since(response.requestTime) - if err != nil { - b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency) - dead = err - response.errors <- err - continue - } - - decodedHeader := responseHeader{} - err = decode(header, &decodedHeader) - if err != nil { - b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency) - dead = err - response.errors <- err - continue - } - if decodedHeader.correlationID != response.correlationID { - b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency) - // TODO if decoded ID < cur ID, discard until we catch up - // TODO if decoded ID > cur ID, save it so when cur ID catches up we have a response - dead = PacketDecodingError{fmt.Sprintf("correlation ID didn't match, wanted %d, got %d", response.correlationID, decodedHeader.correlationID)} - response.errors <- dead - continue - } - - buf := make([]byte, decodedHeader.length-4) - bytesReadBody, err := io.ReadFull(b.conn, buf) - b.updateIncomingCommunicationMetrics(bytesReadHeader+bytesReadBody, requestLatency) - if err != nil { - dead = err - response.errors <- err - continue - } - - response.packets <- buf - } - close(b.done) -} - -func (b *Broker) sendAndReceiveSASLPlainHandshake() error { - rb := &SaslHandshakeRequest{"PLAIN"} - req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb} - buf, err := encode(req, b.conf.MetricRegistry) - if err != nil { - return err - } - - err = b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout)) - if err != nil { - return err - } - - requestTime := time.Now() - bytes, err := b.conn.Write(buf) - b.updateOutgoingCommunicationMetrics(bytes) - if err != nil { - Logger.Printf("Failed to send SASL handshake %s: %s\n", b.addr, err.Error()) - return err - } - b.correlationID++ - //wait for the response - header := make([]byte, 8) // response header - _, err = io.ReadFull(b.conn, header) - if err != nil { - Logger.Printf("Failed to read SASL handshake header : %s\n", err.Error()) - return err - } - length := binary.BigEndian.Uint32(header[:4]) - payload := make([]byte, length-4) - n, err := io.ReadFull(b.conn, payload) - if err != nil { - Logger.Printf("Failed to read SASL handshake payload : %s\n", err.Error()) - return err - } - b.updateIncomingCommunicationMetrics(n+8, time.Since(requestTime)) - res := &SaslHandshakeResponse{} - err = versionedDecode(payload, res, 0) - if err != nil { - Logger.Printf("Failed to parse SASL handshake : %s\n", err.Error()) - return err - } - if res.Err != ErrNoError { - Logger.Printf("Invalid SASL Mechanism : %s\n", res.Err.Error()) - return res.Err - } - Logger.Print("Successful SASL handshake") - return nil -} - -// Kafka 0.10.0 plans to support SASL Plain and Kerberos as per PR #812 (KIP-43)/(JIRA KAFKA-3149) -// Some hosted kafka services such as IBM Message Hub already offer SASL/PLAIN auth with Kafka 0.9 -// -// In SASL Plain, Kafka expects the auth header to be in the following format -// Message format (from https://tools.ietf.org/html/rfc4616): -// -// message = [authzid] UTF8NUL authcid UTF8NUL passwd -// authcid = 1*SAFE ; MUST accept up to 255 octets -// authzid = 1*SAFE ; MUST accept up to 255 octets -// passwd = 1*SAFE ; MUST accept up to 255 octets -// UTF8NUL = %x00 ; UTF-8 encoded NUL character -// -// SAFE = UTF1 / UTF2 / UTF3 / UTF4 -// ;; any UTF-8 encoded Unicode character except NUL -// -// When credentials are valid, Kafka returns a 4 byte array of null characters. -// When credentials are invalid, Kafka closes the connection. This does not seem to be the ideal way -// of responding to bad credentials but thats how its being done today. -func (b *Broker) sendAndReceiveSASLPlainAuth() error { - if b.conf.Net.SASL.Handshake { - handshakeErr := b.sendAndReceiveSASLPlainHandshake() - if handshakeErr != nil { - Logger.Printf("Error while performing SASL handshake %s\n", b.addr) - return handshakeErr - } - } - length := 1 + len(b.conf.Net.SASL.User) + 1 + len(b.conf.Net.SASL.Password) - authBytes := make([]byte, length+4) //4 byte length header + auth data - binary.BigEndian.PutUint32(authBytes, uint32(length)) - copy(authBytes[4:], []byte("\x00"+b.conf.Net.SASL.User+"\x00"+b.conf.Net.SASL.Password)) - - err := b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout)) - if err != nil { - Logger.Printf("Failed to set write deadline when doing SASL auth with broker %s: %s\n", b.addr, err.Error()) - return err - } - - requestTime := time.Now() - bytesWritten, err := b.conn.Write(authBytes) - b.updateOutgoingCommunicationMetrics(bytesWritten) - if err != nil { - Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error()) - return err - } - - header := make([]byte, 4) - n, err := io.ReadFull(b.conn, header) - b.updateIncomingCommunicationMetrics(n, time.Since(requestTime)) - // If the credentials are valid, we would get a 4 byte response filled with null characters. - // Otherwise, the broker closes the connection and we get an EOF - if err != nil { - Logger.Printf("Failed to read response while authenticating with SASL to broker %s: %s\n", b.addr, err.Error()) - return err - } - - Logger.Printf("SASL authentication successful with broker %s:%v - %v\n", b.addr, n, header) - return nil -} - -func (b *Broker) updateIncomingCommunicationMetrics(bytes int, requestLatency time.Duration) { - b.updateRequestLatencyMetrics(requestLatency) - b.responseRate.Mark(1) - if b.brokerResponseRate != nil { - b.brokerResponseRate.Mark(1) - } - responseSize := int64(bytes) - b.incomingByteRate.Mark(responseSize) - if b.brokerIncomingByteRate != nil { - b.brokerIncomingByteRate.Mark(responseSize) - } - b.responseSize.Update(responseSize) - if b.brokerResponseSize != nil { - b.brokerResponseSize.Update(responseSize) - } -} - -func (b *Broker) updateRequestLatencyMetrics(requestLatency time.Duration) { - requestLatencyInMs := int64(requestLatency / time.Millisecond) - b.requestLatency.Update(requestLatencyInMs) - if b.brokerRequestLatency != nil { - b.brokerRequestLatency.Update(requestLatencyInMs) - } -} - -func (b *Broker) updateOutgoingCommunicationMetrics(bytes int) { - b.requestRate.Mark(1) - if b.brokerRequestRate != nil { - b.brokerRequestRate.Mark(1) - } - requestSize := int64(bytes) - b.outgoingByteRate.Mark(requestSize) - if b.brokerOutgoingByteRate != nil { - b.brokerOutgoingByteRate.Mark(requestSize) - } - b.requestSize.Update(requestSize) - if b.brokerRequestSize != nil { - b.brokerRequestSize.Update(requestSize) - } -} diff --git a/vendor/github.com/Shopify/sarama/client.go b/vendor/github.com/Shopify/sarama/client.go deleted file mode 100644 index 570f7f3f3..000000000 --- a/vendor/github.com/Shopify/sarama/client.go +++ /dev/null @@ -1,794 +0,0 @@ -package sarama - -import ( - "math/rand" - "sort" - "sync" - "time" -) - -// Client is a generic Kafka client. It manages connections to one or more Kafka brokers. -// You MUST call Close() on a client to avoid leaks, it will not be garbage-collected -// automatically when it passes out of scope. It is safe to share a client amongst many -// users, however Kafka will process requests from a single client strictly in serial, -// so it is generally more efficient to use the default one client per producer/consumer. -type Client interface { - // Config returns the Config struct of the client. This struct should not be - // altered after it has been created. - Config() *Config - - // Brokers returns the current set of active brokers as retrieved from cluster metadata. - Brokers() []*Broker - - // Topics returns the set of available topics as retrieved from cluster metadata. - Topics() ([]string, error) - - // Partitions returns the sorted list of all partition IDs for the given topic. - Partitions(topic string) ([]int32, error) - - // WritablePartitions returns the sorted list of all writable partition IDs for - // the given topic, where "writable" means "having a valid leader accepting - // writes". - WritablePartitions(topic string) ([]int32, error) - - // Leader returns the broker object that is the leader of the current - // topic/partition, as determined by querying the cluster metadata. - Leader(topic string, partitionID int32) (*Broker, error) - - // Replicas returns the set of all replica IDs for the given partition. - Replicas(topic string, partitionID int32) ([]int32, error) - - // InSyncReplicas returns the set of all in-sync replica IDs for the given - // partition. In-sync replicas are replicas which are fully caught up with - // the partition leader. - InSyncReplicas(topic string, partitionID int32) ([]int32, error) - - // RefreshMetadata takes a list of topics and queries the cluster to refresh the - // available metadata for those topics. If no topics are provided, it will refresh - // metadata for all topics. - RefreshMetadata(topics ...string) error - - // GetOffset queries the cluster to get the most recent available offset at the - // given time on the topic/partition combination. Time should be OffsetOldest for - // the earliest available offset, OffsetNewest for the offset of the message that - // will be produced next, or a time. - GetOffset(topic string, partitionID int32, time int64) (int64, error) - - // Coordinator returns the coordinating broker for a consumer group. It will - // return a locally cached value if it's available. You can call - // RefreshCoordinator to update the cached value. This function only works on - // Kafka 0.8.2 and higher. - Coordinator(consumerGroup string) (*Broker, error) - - // RefreshCoordinator retrieves the coordinator for a consumer group and stores it - // in local cache. This function only works on Kafka 0.8.2 and higher. - RefreshCoordinator(consumerGroup string) error - - // Close shuts down all broker connections managed by this client. It is required - // to call this function before a client object passes out of scope, as it will - // otherwise leak memory. You must close any Producers or Consumers using a client - // before you close the client. - Close() error - - // Closed returns true if the client has already had Close called on it - Closed() bool -} - -const ( - // OffsetNewest stands for the log head offset, i.e. the offset that will be - // assigned to the next message that will be produced to the partition. You - // can send this to a client's GetOffset method to get this offset, or when - // calling ConsumePartition to start consuming new messages. - OffsetNewest int64 = -1 - // OffsetOldest stands for the oldest offset available on the broker for a - // partition. You can send this to a client's GetOffset method to get this - // offset, or when calling ConsumePartition to start consuming from the - // oldest offset that is still available on the broker. - OffsetOldest int64 = -2 -) - -type client struct { - conf *Config - closer, closed chan none // for shutting down background metadata updater - - // the broker addresses given to us through the constructor are not guaranteed to be returned in - // the cluster metadata (I *think* it only returns brokers who are currently leading partitions?) - // so we store them separately - seedBrokers []*Broker - deadSeeds []*Broker - - brokers map[int32]*Broker // maps broker ids to brokers - metadata map[string]map[int32]*PartitionMetadata // maps topics to partition ids to metadata - coordinators map[string]int32 // Maps consumer group names to coordinating broker IDs - - // If the number of partitions is large, we can get some churn calling cachedPartitions, - // so the result is cached. It is important to update this value whenever metadata is changed - cachedPartitionsResults map[string][maxPartitionIndex][]int32 - - lock sync.RWMutex // protects access to the maps that hold cluster state. -} - -// NewClient creates a new Client. It connects to one of the given broker addresses -// and uses that broker to automatically fetch metadata on the rest of the kafka cluster. If metadata cannot -// be retrieved from any of the given broker addresses, the client is not created. -func NewClient(addrs []string, conf *Config) (Client, error) { - Logger.Println("Initializing new client") - - if conf == nil { - conf = NewConfig() - } - - if err := conf.Validate(); err != nil { - return nil, err - } - - if len(addrs) < 1 { - return nil, ConfigurationError("You must provide at least one broker address") - } - - client := &client{ - conf: conf, - closer: make(chan none), - closed: make(chan none), - brokers: make(map[int32]*Broker), - metadata: make(map[string]map[int32]*PartitionMetadata), - cachedPartitionsResults: make(map[string][maxPartitionIndex][]int32), - coordinators: make(map[string]int32), - } - - random := rand.New(rand.NewSource(time.Now().UnixNano())) - for _, index := range random.Perm(len(addrs)) { - client.seedBrokers = append(client.seedBrokers, NewBroker(addrs[index])) - } - - if conf.Metadata.Full { - // do an initial fetch of all cluster metadata by specifying an empty list of topics - err := client.RefreshMetadata() - switch err { - case nil: - break - case ErrLeaderNotAvailable, ErrReplicaNotAvailable, ErrTopicAuthorizationFailed, ErrClusterAuthorizationFailed: - // indicates that maybe part of the cluster is down, but is not fatal to creating the client - Logger.Println(err) - default: - close(client.closed) // we haven't started the background updater yet, so we have to do this manually - _ = client.Close() - return nil, err - } - } - go withRecover(client.backgroundMetadataUpdater) - - Logger.Println("Successfully initialized new client") - - return client, nil -} - -func (client *client) Config() *Config { - return client.conf -} - -func (client *client) Brokers() []*Broker { - client.lock.RLock() - defer client.lock.RUnlock() - brokers := make([]*Broker, 0) - for _, broker := range client.brokers { - brokers = append(brokers, broker) - } - return brokers -} - -func (client *client) Close() error { - if client.Closed() { - // Chances are this is being called from a defer() and the error will go unobserved - // so we go ahead and log the event in this case. - Logger.Printf("Close() called on already closed client") - return ErrClosedClient - } - - // shutdown and wait for the background thread before we take the lock, to avoid races - close(client.closer) - <-client.closed - - client.lock.Lock() - defer client.lock.Unlock() - Logger.Println("Closing Client") - - for _, broker := range client.brokers { - safeAsyncClose(broker) - } - - for _, broker := range client.seedBrokers { - safeAsyncClose(broker) - } - - client.brokers = nil - client.metadata = nil - - return nil -} - -func (client *client) Closed() bool { - return client.brokers == nil -} - -func (client *client) Topics() ([]string, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - client.lock.RLock() - defer client.lock.RUnlock() - - ret := make([]string, 0, len(client.metadata)) - for topic := range client.metadata { - ret = append(ret, topic) - } - - return ret, nil -} - -func (client *client) Partitions(topic string) ([]int32, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - partitions := client.cachedPartitions(topic, allPartitions) - - if len(partitions) == 0 { - err := client.RefreshMetadata(topic) - if err != nil { - return nil, err - } - partitions = client.cachedPartitions(topic, allPartitions) - } - - if partitions == nil { - return nil, ErrUnknownTopicOrPartition - } - - return partitions, nil -} - -func (client *client) WritablePartitions(topic string) ([]int32, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - partitions := client.cachedPartitions(topic, writablePartitions) - - // len==0 catches when it's nil (no such topic) and the odd case when every single - // partition is undergoing leader election simultaneously. Callers have to be able to handle - // this function returning an empty slice (which is a valid return value) but catching it - // here the first time (note we *don't* catch it below where we return ErrUnknownTopicOrPartition) triggers - // a metadata refresh as a nicety so callers can just try again and don't have to manually - // trigger a refresh (otherwise they'd just keep getting a stale cached copy). - if len(partitions) == 0 { - err := client.RefreshMetadata(topic) - if err != nil { - return nil, err - } - partitions = client.cachedPartitions(topic, writablePartitions) - } - - if partitions == nil { - return nil, ErrUnknownTopicOrPartition - } - - return partitions, nil -} - -func (client *client) Replicas(topic string, partitionID int32) ([]int32, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - metadata := client.cachedMetadata(topic, partitionID) - - if metadata == nil { - err := client.RefreshMetadata(topic) - if err != nil { - return nil, err - } - metadata = client.cachedMetadata(topic, partitionID) - } - - if metadata == nil { - return nil, ErrUnknownTopicOrPartition - } - - if metadata.Err == ErrReplicaNotAvailable { - return nil, metadata.Err - } - return dupInt32Slice(metadata.Replicas), nil -} - -func (client *client) InSyncReplicas(topic string, partitionID int32) ([]int32, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - metadata := client.cachedMetadata(topic, partitionID) - - if metadata == nil { - err := client.RefreshMetadata(topic) - if err != nil { - return nil, err - } - metadata = client.cachedMetadata(topic, partitionID) - } - - if metadata == nil { - return nil, ErrUnknownTopicOrPartition - } - - if metadata.Err == ErrReplicaNotAvailable { - return nil, metadata.Err - } - return dupInt32Slice(metadata.Isr), nil -} - -func (client *client) Leader(topic string, partitionID int32) (*Broker, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - leader, err := client.cachedLeader(topic, partitionID) - - if leader == nil { - err = client.RefreshMetadata(topic) - if err != nil { - return nil, err - } - leader, err = client.cachedLeader(topic, partitionID) - } - - return leader, err -} - -func (client *client) RefreshMetadata(topics ...string) error { - if client.Closed() { - return ErrClosedClient - } - - // Prior to 0.8.2, Kafka will throw exceptions on an empty topic and not return a proper - // error. This handles the case by returning an error instead of sending it - // off to Kafka. See: https://github.com/Shopify/sarama/pull/38#issuecomment-26362310 - for _, topic := range topics { - if len(topic) == 0 { - return ErrInvalidTopic // this is the error that 0.8.2 and later correctly return - } - } - - return client.tryRefreshMetadata(topics, client.conf.Metadata.Retry.Max) -} - -func (client *client) GetOffset(topic string, partitionID int32, time int64) (int64, error) { - if client.Closed() { - return -1, ErrClosedClient - } - - offset, err := client.getOffset(topic, partitionID, time) - - if err != nil { - if err := client.RefreshMetadata(topic); err != nil { - return -1, err - } - return client.getOffset(topic, partitionID, time) - } - - return offset, err -} - -func (client *client) Coordinator(consumerGroup string) (*Broker, error) { - if client.Closed() { - return nil, ErrClosedClient - } - - coordinator := client.cachedCoordinator(consumerGroup) - - if coordinator == nil { - if err := client.RefreshCoordinator(consumerGroup); err != nil { - return nil, err - } - coordinator = client.cachedCoordinator(consumerGroup) - } - - if coordinator == nil { - return nil, ErrConsumerCoordinatorNotAvailable - } - - _ = coordinator.Open(client.conf) - return coordinator, nil -} - -func (client *client) RefreshCoordinator(consumerGroup string) error { - if client.Closed() { - return ErrClosedClient - } - - response, err := client.getConsumerMetadata(consumerGroup, client.conf.Metadata.Retry.Max) - if err != nil { - return err - } - - client.lock.Lock() - defer client.lock.Unlock() - client.registerBroker(response.Coordinator) - client.coordinators[consumerGroup] = response.Coordinator.ID() - return nil -} - -// private broker management helpers - -// registerBroker makes sure a broker received by a Metadata or Coordinator request is registered -// in the brokers map. It returns the broker that is registered, which may be the provided broker, -// or a previously registered Broker instance. You must hold the write lock before calling this function. -func (client *client) registerBroker(broker *Broker) { - if client.brokers[broker.ID()] == nil { - client.brokers[broker.ID()] = broker - Logger.Printf("client/brokers registered new broker #%d at %s", broker.ID(), broker.Addr()) - } else if broker.Addr() != client.brokers[broker.ID()].Addr() { - safeAsyncClose(client.brokers[broker.ID()]) - client.brokers[broker.ID()] = broker - Logger.Printf("client/brokers replaced registered broker #%d with %s", broker.ID(), broker.Addr()) - } -} - -// deregisterBroker removes a broker from the seedsBroker list, and if it's -// not the seedbroker, removes it from brokers map completely. -func (client *client) deregisterBroker(broker *Broker) { - client.lock.Lock() - defer client.lock.Unlock() - - if len(client.seedBrokers) > 0 && broker == client.seedBrokers[0] { - client.deadSeeds = append(client.deadSeeds, broker) - client.seedBrokers = client.seedBrokers[1:] - } else { - // we do this so that our loop in `tryRefreshMetadata` doesn't go on forever, - // but we really shouldn't have to; once that loop is made better this case can be - // removed, and the function generally can be renamed from `deregisterBroker` to - // `nextSeedBroker` or something - Logger.Printf("client/brokers deregistered broker #%d at %s", broker.ID(), broker.Addr()) - delete(client.brokers, broker.ID()) - } -} - -func (client *client) resurrectDeadBrokers() { - client.lock.Lock() - defer client.lock.Unlock() - - Logger.Printf("client/brokers resurrecting %d dead seed brokers", len(client.deadSeeds)) - client.seedBrokers = append(client.seedBrokers, client.deadSeeds...) - client.deadSeeds = nil -} - -func (client *client) any() *Broker { - client.lock.RLock() - defer client.lock.RUnlock() - - if len(client.seedBrokers) > 0 { - _ = client.seedBrokers[0].Open(client.conf) - return client.seedBrokers[0] - } - - // not guaranteed to be random *or* deterministic - for _, broker := range client.brokers { - _ = broker.Open(client.conf) - return broker - } - - return nil -} - -// private caching/lazy metadata helpers - -type partitionType int - -const ( - allPartitions partitionType = iota - writablePartitions - // If you add any more types, update the partition cache in update() - - // Ensure this is the last partition type value - maxPartitionIndex -) - -func (client *client) cachedMetadata(topic string, partitionID int32) *PartitionMetadata { - client.lock.RLock() - defer client.lock.RUnlock() - - partitions := client.metadata[topic] - if partitions != nil { - return partitions[partitionID] - } - - return nil -} - -func (client *client) cachedPartitions(topic string, partitionSet partitionType) []int32 { - client.lock.RLock() - defer client.lock.RUnlock() - - partitions, exists := client.cachedPartitionsResults[topic] - - if !exists { - return nil - } - return partitions[partitionSet] -} - -func (client *client) setPartitionCache(topic string, partitionSet partitionType) []int32 { - partitions := client.metadata[topic] - - if partitions == nil { - return nil - } - - ret := make([]int32, 0, len(partitions)) - for _, partition := range partitions { - if partitionSet == writablePartitions && partition.Err == ErrLeaderNotAvailable { - continue - } - ret = append(ret, partition.ID) - } - - sort.Sort(int32Slice(ret)) - return ret -} - -func (client *client) cachedLeader(topic string, partitionID int32) (*Broker, error) { - client.lock.RLock() - defer client.lock.RUnlock() - - partitions := client.metadata[topic] - if partitions != nil { - metadata, ok := partitions[partitionID] - if ok { - if metadata.Err == ErrLeaderNotAvailable { - return nil, ErrLeaderNotAvailable - } - b := client.brokers[metadata.Leader] - if b == nil { - return nil, ErrLeaderNotAvailable - } - _ = b.Open(client.conf) - return b, nil - } - } - - return nil, ErrUnknownTopicOrPartition -} - -func (client *client) getOffset(topic string, partitionID int32, time int64) (int64, error) { - broker, err := client.Leader(topic, partitionID) - if err != nil { - return -1, err - } - - request := &OffsetRequest{} - if client.conf.Version.IsAtLeast(V0_10_1_0) { - request.Version = 1 - } - request.AddBlock(topic, partitionID, time, 1) - - response, err := broker.GetAvailableOffsets(request) - if err != nil { - _ = broker.Close() - return -1, err - } - - block := response.GetBlock(topic, partitionID) - if block == nil { - _ = broker.Close() - return -1, ErrIncompleteResponse - } - if block.Err != ErrNoError { - return -1, block.Err - } - if len(block.Offsets) != 1 { - return -1, ErrOffsetOutOfRange - } - - return block.Offsets[0], nil -} - -// core metadata update logic - -func (client *client) backgroundMetadataUpdater() { - defer close(client.closed) - - if client.conf.Metadata.RefreshFrequency == time.Duration(0) { - return - } - - ticker := time.NewTicker(client.conf.Metadata.RefreshFrequency) - defer ticker.Stop() - - for { - select { - case <-ticker.C: - topics := []string{} - if !client.conf.Metadata.Full { - if specificTopics, err := client.Topics(); err != nil { - Logger.Println("Client background metadata topic load:", err) - break - } else if len(specificTopics) == 0 { - Logger.Println("Client background metadata update: no specific topics to update") - break - } else { - topics = specificTopics - } - } - - if err := client.RefreshMetadata(topics...); err != nil { - Logger.Println("Client background metadata update:", err) - } - case <-client.closer: - return - } - } -} - -func (client *client) tryRefreshMetadata(topics []string, attemptsRemaining int) error { - retry := func(err error) error { - if attemptsRemaining > 0 { - Logger.Printf("client/metadata retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining) - time.Sleep(client.conf.Metadata.Retry.Backoff) - return client.tryRefreshMetadata(topics, attemptsRemaining-1) - } - return err - } - - for broker := client.any(); broker != nil; broker = client.any() { - if len(topics) > 0 { - Logger.Printf("client/metadata fetching metadata for %v from broker %s\n", topics, broker.addr) - } else { - Logger.Printf("client/metadata fetching metadata for all topics from broker %s\n", broker.addr) - } - response, err := broker.GetMetadata(&MetadataRequest{Topics: topics}) - - switch err.(type) { - case nil: - // valid response, use it - shouldRetry, err := client.updateMetadata(response) - if shouldRetry { - Logger.Println("client/metadata found some partitions to be leaderless") - return retry(err) // note: err can be nil - } - return err - - case PacketEncodingError: - // didn't even send, return the error - return err - default: - // some other error, remove that broker and try again - Logger.Println("client/metadata got error from broker while fetching metadata:", err) - _ = broker.Close() - client.deregisterBroker(broker) - } - } - - Logger.Println("client/metadata no available broker to send metadata request to") - client.resurrectDeadBrokers() - return retry(ErrOutOfBrokers) -} - -// if no fatal error, returns a list of topics that need retrying due to ErrLeaderNotAvailable -func (client *client) updateMetadata(data *MetadataResponse) (retry bool, err error) { - client.lock.Lock() - defer client.lock.Unlock() - - // For all the brokers we received: - // - if it is a new ID, save it - // - if it is an existing ID, but the address we have is stale, discard the old one and save it - // - otherwise ignore it, replacing our existing one would just bounce the connection - for _, broker := range data.Brokers { - client.registerBroker(broker) - } - - for _, topic := range data.Topics { - delete(client.metadata, topic.Name) - delete(client.cachedPartitionsResults, topic.Name) - - switch topic.Err { - case ErrNoError: - break - case ErrInvalidTopic, ErrTopicAuthorizationFailed: // don't retry, don't store partial results - err = topic.Err - continue - case ErrUnknownTopicOrPartition: // retry, do not store partial partition results - err = topic.Err - retry = true - continue - case ErrLeaderNotAvailable: // retry, but store partial partition results - retry = true - break - default: // don't retry, don't store partial results - Logger.Printf("Unexpected topic-level metadata error: %s", topic.Err) - err = topic.Err - continue - } - - client.metadata[topic.Name] = make(map[int32]*PartitionMetadata, len(topic.Partitions)) - for _, partition := range topic.Partitions { - client.metadata[topic.Name][partition.ID] = partition - if partition.Err == ErrLeaderNotAvailable { - retry = true - } - } - - var partitionCache [maxPartitionIndex][]int32 - partitionCache[allPartitions] = client.setPartitionCache(topic.Name, allPartitions) - partitionCache[writablePartitions] = client.setPartitionCache(topic.Name, writablePartitions) - client.cachedPartitionsResults[topic.Name] = partitionCache - } - - return -} - -func (client *client) cachedCoordinator(consumerGroup string) *Broker { - client.lock.RLock() - defer client.lock.RUnlock() - if coordinatorID, ok := client.coordinators[consumerGroup]; ok { - return client.brokers[coordinatorID] - } - return nil -} - -func (client *client) getConsumerMetadata(consumerGroup string, attemptsRemaining int) (*ConsumerMetadataResponse, error) { - retry := func(err error) (*ConsumerMetadataResponse, error) { - if attemptsRemaining > 0 { - Logger.Printf("client/coordinator retrying after %dms... (%d attempts remaining)\n", client.conf.Metadata.Retry.Backoff/time.Millisecond, attemptsRemaining) - time.Sleep(client.conf.Metadata.Retry.Backoff) - return client.getConsumerMetadata(consumerGroup, attemptsRemaining-1) - } - return nil, err - } - - for broker := client.any(); broker != nil; broker = client.any() { - Logger.Printf("client/coordinator requesting coordinator for consumergroup %s from %s\n", consumerGroup, broker.Addr()) - - request := new(ConsumerMetadataRequest) - request.ConsumerGroup = consumerGroup - - response, err := broker.GetConsumerMetadata(request) - - if err != nil { - Logger.Printf("client/coordinator request to broker %s failed: %s\n", broker.Addr(), err) - - switch err.(type) { - case PacketEncodingError: - return nil, err - default: - _ = broker.Close() - client.deregisterBroker(broker) - continue - } - } - - switch response.Err { - case ErrNoError: - Logger.Printf("client/coordinator coordinator for consumergroup %s is #%d (%s)\n", consumerGroup, response.Coordinator.ID(), response.Coordinator.Addr()) - return response, nil - - case ErrConsumerCoordinatorNotAvailable: - Logger.Printf("client/coordinator coordinator for consumer group %s is not available\n", consumerGroup) - - // This is very ugly, but this scenario will only happen once per cluster. - // The __consumer_offsets topic only has to be created one time. - // The number of partitions not configurable, but partition 0 should always exist. - if _, err := client.Leader("__consumer_offsets", 0); err != nil { - Logger.Printf("client/coordinator the __consumer_offsets topic is not initialized completely yet. Waiting 2 seconds...\n") - time.Sleep(2 * time.Second) - } - - return retry(ErrConsumerCoordinatorNotAvailable) - default: - return nil, response.Err - } - } - - Logger.Println("client/coordinator no available broker to send consumer metadata request to") - client.resurrectDeadBrokers() - return retry(ErrOutOfBrokers) -} diff --git a/vendor/github.com/Shopify/sarama/config.go b/vendor/github.com/Shopify/sarama/config.go deleted file mode 100644 index e4ff680f2..000000000 --- a/vendor/github.com/Shopify/sarama/config.go +++ /dev/null @@ -1,442 +0,0 @@ -package sarama - -import ( - "crypto/tls" - "regexp" - "time" - - "github.com/rcrowley/go-metrics" -) - -const defaultClientID = "sarama" - -var validID = regexp.MustCompile(`\A[A-Za-z0-9._-]+\z`) - -// Config is used to pass multiple configuration options to Sarama's constructors. -type Config struct { - // Net is the namespace for network-level properties used by the Broker, and - // shared by the Client/Producer/Consumer. - Net struct { - // How many outstanding requests a connection is allowed to have before - // sending on it blocks (default 5). - MaxOpenRequests int - - // All three of the below configurations are similar to the - // `socket.timeout.ms` setting in JVM kafka. All of them default - // to 30 seconds. - DialTimeout time.Duration // How long to wait for the initial connection. - ReadTimeout time.Duration // How long to wait for a response. - WriteTimeout time.Duration // How long to wait for a transmit. - - TLS struct { - // Whether or not to use TLS when connecting to the broker - // (defaults to false). - Enable bool - // The TLS configuration to use for secure connections if - // enabled (defaults to nil). - Config *tls.Config - } - - // SASL based authentication with broker. While there are multiple SASL authentication methods - // the current implementation is limited to plaintext (SASL/PLAIN) authentication - SASL struct { - // Whether or not to use SASL authentication when connecting to the broker - // (defaults to false). - Enable bool - // Whether or not to send the Kafka SASL handshake first if enabled - // (defaults to true). You should only set this to false if you're using - // a non-Kafka SASL proxy. - Handshake bool - //username and password for SASL/PLAIN authentication - User string - Password string - } - - // KeepAlive specifies the keep-alive period for an active network connection. - // If zero, keep-alives are disabled. (default is 0: disabled). - KeepAlive time.Duration - } - - // Metadata is the namespace for metadata management properties used by the - // Client, and shared by the Producer/Consumer. - Metadata struct { - Retry struct { - // The total number of times to retry a metadata request when the - // cluster is in the middle of a leader election (default 3). - Max int - // How long to wait for leader election to occur before retrying - // (default 250ms). Similar to the JVM's `retry.backoff.ms`. - Backoff time.Duration - } - // How frequently to refresh the cluster metadata in the background. - // Defaults to 10 minutes. Set to 0 to disable. Similar to - // `topic.metadata.refresh.interval.ms` in the JVM version. - RefreshFrequency time.Duration - - // Whether to maintain a full set of metadata for all topics, or just - // the minimal set that has been necessary so far. The full set is simpler - // and usually more convenient, but can take up a substantial amount of - // memory if you have many topics and partitions. Defaults to true. - Full bool - } - - // Producer is the namespace for configuration related to producing messages, - // used by the Producer. - Producer struct { - // The maximum permitted size of a message (defaults to 1000000). Should be - // set equal to or smaller than the broker's `message.max.bytes`. - MaxMessageBytes int - // The level of acknowledgement reliability needed from the broker (defaults - // to WaitForLocal). Equivalent to the `request.required.acks` setting of the - // JVM producer. - RequiredAcks RequiredAcks - // The maximum duration the broker will wait the receipt of the number of - // RequiredAcks (defaults to 10 seconds). This is only relevant when - // RequiredAcks is set to WaitForAll or a number > 1. Only supports - // millisecond resolution, nanoseconds will be truncated. Equivalent to - // the JVM producer's `request.timeout.ms` setting. - Timeout time.Duration - // The type of compression to use on messages (defaults to no compression). - // Similar to `compression.codec` setting of the JVM producer. - Compression CompressionCodec - // Generates partitioners for choosing the partition to send messages to - // (defaults to hashing the message key). Similar to the `partitioner.class` - // setting for the JVM producer. - Partitioner PartitionerConstructor - - // Return specifies what channels will be populated. If they are set to true, - // you must read from the respective channels to prevent deadlock. If, - // however, this config is used to create a `SyncProducer`, both must be set - // to true and you shall not read from the channels since the producer does - // this internally. - Return struct { - // If enabled, successfully delivered messages will be returned on the - // Successes channel (default disabled). - Successes bool - - // If enabled, messages that failed to deliver will be returned on the - // Errors channel, including error (default enabled). - Errors bool - } - - // The following config options control how often messages are batched up and - // sent to the broker. By default, messages are sent as fast as possible, and - // all messages received while the current batch is in-flight are placed - // into the subsequent batch. - Flush struct { - // The best-effort number of bytes needed to trigger a flush. Use the - // global sarama.MaxRequestSize to set a hard upper limit. - Bytes int - // The best-effort number of messages needed to trigger a flush. Use - // `MaxMessages` to set a hard upper limit. - Messages int - // The best-effort frequency of flushes. Equivalent to - // `queue.buffering.max.ms` setting of JVM producer. - Frequency time.Duration - // The maximum number of messages the producer will send in a single - // broker request. Defaults to 0 for unlimited. Similar to - // `queue.buffering.max.messages` in the JVM producer. - MaxMessages int - } - - Retry struct { - // The total number of times to retry sending a message (default 3). - // Similar to the `message.send.max.retries` setting of the JVM producer. - Max int - // How long to wait for the cluster to settle between retries - // (default 100ms). Similar to the `retry.backoff.ms` setting of the - // JVM producer. - Backoff time.Duration - } - } - - // Consumer is the namespace for configuration related to consuming messages, - // used by the Consumer. - // - // Note that Sarama's Consumer type does not currently support automatic - // consumer-group rebalancing and offset tracking. For Zookeeper-based - // tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka - // library builds on Sarama to add this support. For Kafka-based tracking - // (Kafka 0.9 and later), the https://github.com/bsm/sarama-cluster library - // builds on Sarama to add this support. - Consumer struct { - Retry struct { - // How long to wait after a failing to read from a partition before - // trying again (default 2s). - Backoff time.Duration - } - - // Fetch is the namespace for controlling how many bytes are retrieved by any - // given request. - Fetch struct { - // The minimum number of message bytes to fetch in a request - the broker - // will wait until at least this many are available. The default is 1, - // as 0 causes the consumer to spin when no messages are available. - // Equivalent to the JVM's `fetch.min.bytes`. - Min int32 - // The default number of message bytes to fetch from the broker in each - // request (default 32768). This should be larger than the majority of - // your messages, or else the consumer will spend a lot of time - // negotiating sizes and not actually consuming. Similar to the JVM's - // `fetch.message.max.bytes`. - Default int32 - // The maximum number of message bytes to fetch from the broker in a - // single request. Messages larger than this will return - // ErrMessageTooLarge and will not be consumable, so you must be sure - // this is at least as large as your largest message. Defaults to 0 - // (no limit). Similar to the JVM's `fetch.message.max.bytes`. The - // global `sarama.MaxResponseSize` still applies. - Max int32 - } - // The maximum amount of time the broker will wait for Consumer.Fetch.Min - // bytes to become available before it returns fewer than that anyways. The - // default is 250ms, since 0 causes the consumer to spin when no events are - // available. 100-500ms is a reasonable range for most cases. Kafka only - // supports precision up to milliseconds; nanoseconds will be truncated. - // Equivalent to the JVM's `fetch.wait.max.ms`. - MaxWaitTime time.Duration - - // The maximum amount of time the consumer expects a message takes to - // process for the user. If writing to the Messages channel takes longer - // than this, that partition will stop fetching more messages until it - // can proceed again. - // Note that, since the Messages channel is buffered, the actual grace time is - // (MaxProcessingTime * ChanneBufferSize). Defaults to 100ms. - // If a message is not written to the Messages channel between two ticks - // of the expiryTicker then a timeout is detected. - // Using a ticker instead of a timer to detect timeouts should typically - // result in many fewer calls to Timer functions which may result in a - // significant performance improvement if many messages are being sent - // and timeouts are infrequent. - // The disadvantage of using a ticker instead of a timer is that - // timeouts will be less accurate. That is, the effective timeout could - // be between `MaxProcessingTime` and `2 * MaxProcessingTime`. For - // example, if `MaxProcessingTime` is 100ms then a delay of 180ms - // between two messages being sent may not be recognized as a timeout. - MaxProcessingTime time.Duration - - // Return specifies what channels will be populated. If they are set to true, - // you must read from them to prevent deadlock. - Return struct { - // If enabled, any errors that occurred while consuming are returned on - // the Errors channel (default disabled). - Errors bool - } - - // Offsets specifies configuration for how and when to commit consumed - // offsets. This currently requires the manual use of an OffsetManager - // but will eventually be automated. - Offsets struct { - // How frequently to commit updated offsets. Defaults to 1s. - CommitInterval time.Duration - - // The initial offset to use if no offset was previously committed. - // Should be OffsetNewest or OffsetOldest. Defaults to OffsetNewest. - Initial int64 - - // The retention duration for committed offsets. If zero, disabled - // (in which case the `offsets.retention.minutes` option on the - // broker will be used). Kafka only supports precision up to - // milliseconds; nanoseconds will be truncated. Requires Kafka - // broker version 0.9.0 or later. - // (default is 0: disabled). - Retention time.Duration - } - } - - // A user-provided string sent with every request to the brokers for logging, - // debugging, and auditing purposes. Defaults to "sarama", but you should - // probably set it to something specific to your application. - ClientID string - // The number of events to buffer in internal and external channels. This - // permits the producer and consumer to continue processing some messages - // in the background while user code is working, greatly improving throughput. - // Defaults to 256. - ChannelBufferSize int - // The version of Kafka that Sarama will assume it is running against. - // Defaults to the oldest supported stable version. Since Kafka provides - // backwards-compatibility, setting it to a version older than you have - // will not break anything, although it may prevent you from using the - // latest features. Setting it to a version greater than you are actually - // running may lead to random breakage. - Version KafkaVersion - // The registry to define metrics into. - // Defaults to a local registry. - // If you want to disable metrics gathering, set "metrics.UseNilMetrics" to "true" - // prior to starting Sarama. - // See Examples on how to use the metrics registry - MetricRegistry metrics.Registry -} - -// NewConfig returns a new configuration instance with sane defaults. -func NewConfig() *Config { - c := &Config{} - - c.Net.MaxOpenRequests = 5 - c.Net.DialTimeout = 30 * time.Second - c.Net.ReadTimeout = 30 * time.Second - c.Net.WriteTimeout = 30 * time.Second - c.Net.SASL.Handshake = true - - c.Metadata.Retry.Max = 3 - c.Metadata.Retry.Backoff = 250 * time.Millisecond - c.Metadata.RefreshFrequency = 10 * time.Minute - c.Metadata.Full = true - - c.Producer.MaxMessageBytes = 1000000 - c.Producer.RequiredAcks = WaitForLocal - c.Producer.Timeout = 10 * time.Second - c.Producer.Partitioner = NewHashPartitioner - c.Producer.Retry.Max = 3 - c.Producer.Retry.Backoff = 100 * time.Millisecond - c.Producer.Return.Errors = true - - c.Consumer.Fetch.Min = 1 - c.Consumer.Fetch.Default = 32768 - c.Consumer.Retry.Backoff = 2 * time.Second - c.Consumer.MaxWaitTime = 250 * time.Millisecond - c.Consumer.MaxProcessingTime = 100 * time.Millisecond - c.Consumer.Return.Errors = false - c.Consumer.Offsets.CommitInterval = 1 * time.Second - c.Consumer.Offsets.Initial = OffsetNewest - - c.ClientID = defaultClientID - c.ChannelBufferSize = 256 - c.Version = minVersion - c.MetricRegistry = metrics.NewRegistry() - - return c -} - -// Validate checks a Config instance. It will return a -// ConfigurationError if the specified values don't make sense. -func (c *Config) Validate() error { - // some configuration values should be warned on but not fail completely, do those first - if c.Net.TLS.Enable == false && c.Net.TLS.Config != nil { - Logger.Println("Net.TLS is disabled but a non-nil configuration was provided.") - } - if c.Net.SASL.Enable == false { - if c.Net.SASL.User != "" { - Logger.Println("Net.SASL is disabled but a non-empty username was provided.") - } - if c.Net.SASL.Password != "" { - Logger.Println("Net.SASL is disabled but a non-empty password was provided.") - } - } - if c.Producer.RequiredAcks > 1 { - Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.") - } - if c.Producer.MaxMessageBytes >= int(MaxRequestSize) { - Logger.Println("Producer.MaxMessageBytes must be smaller than MaxRequestSize; it will be ignored.") - } - if c.Producer.Flush.Bytes >= int(MaxRequestSize) { - Logger.Println("Producer.Flush.Bytes must be smaller than MaxRequestSize; it will be ignored.") - } - if (c.Producer.Flush.Bytes > 0 || c.Producer.Flush.Messages > 0) && c.Producer.Flush.Frequency == 0 { - Logger.Println("Producer.Flush: Bytes or Messages are set, but Frequency is not; messages may not get flushed.") - } - if c.Producer.Timeout%time.Millisecond != 0 { - Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.") - } - if c.Consumer.MaxWaitTime < 100*time.Millisecond { - Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.") - } - if c.Consumer.MaxWaitTime%time.Millisecond != 0 { - Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.") - } - if c.Consumer.Offsets.Retention%time.Millisecond != 0 { - Logger.Println("Consumer.Offsets.Retention only supports millisecond precision; nanoseconds will be truncated.") - } - if c.ClientID == defaultClientID { - Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.") - } - - // validate Net values - switch { - case c.Net.MaxOpenRequests <= 0: - return ConfigurationError("Net.MaxOpenRequests must be > 0") - case c.Net.DialTimeout <= 0: - return ConfigurationError("Net.DialTimeout must be > 0") - case c.Net.ReadTimeout <= 0: - return ConfigurationError("Net.ReadTimeout must be > 0") - case c.Net.WriteTimeout <= 0: - return ConfigurationError("Net.WriteTimeout must be > 0") - case c.Net.KeepAlive < 0: - return ConfigurationError("Net.KeepAlive must be >= 0") - case c.Net.SASL.Enable == true && c.Net.SASL.User == "": - return ConfigurationError("Net.SASL.User must not be empty when SASL is enabled") - case c.Net.SASL.Enable == true && c.Net.SASL.Password == "": - return ConfigurationError("Net.SASL.Password must not be empty when SASL is enabled") - } - - // validate the Metadata values - switch { - case c.Metadata.Retry.Max < 0: - return ConfigurationError("Metadata.Retry.Max must be >= 0") - case c.Metadata.Retry.Backoff < 0: - return ConfigurationError("Metadata.Retry.Backoff must be >= 0") - case c.Metadata.RefreshFrequency < 0: - return ConfigurationError("Metadata.RefreshFrequency must be >= 0") - } - - // validate the Producer values - switch { - case c.Producer.MaxMessageBytes <= 0: - return ConfigurationError("Producer.MaxMessageBytes must be > 0") - case c.Producer.RequiredAcks < -1: - return ConfigurationError("Producer.RequiredAcks must be >= -1") - case c.Producer.Timeout <= 0: - return ConfigurationError("Producer.Timeout must be > 0") - case c.Producer.Partitioner == nil: - return ConfigurationError("Producer.Partitioner must not be nil") - case c.Producer.Flush.Bytes < 0: - return ConfigurationError("Producer.Flush.Bytes must be >= 0") - case c.Producer.Flush.Messages < 0: - return ConfigurationError("Producer.Flush.Messages must be >= 0") - case c.Producer.Flush.Frequency < 0: - return ConfigurationError("Producer.Flush.Frequency must be >= 0") - case c.Producer.Flush.MaxMessages < 0: - return ConfigurationError("Producer.Flush.MaxMessages must be >= 0") - case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages: - return ConfigurationError("Producer.Flush.MaxMessages must be >= Producer.Flush.Messages when set") - case c.Producer.Retry.Max < 0: - return ConfigurationError("Producer.Retry.Max must be >= 0") - case c.Producer.Retry.Backoff < 0: - return ConfigurationError("Producer.Retry.Backoff must be >= 0") - } - - if c.Producer.Compression == CompressionLZ4 && !c.Version.IsAtLeast(V0_10_0_0) { - return ConfigurationError("lz4 compression requires Version >= V0_10_0_0") - } - - // validate the Consumer values - switch { - case c.Consumer.Fetch.Min <= 0: - return ConfigurationError("Consumer.Fetch.Min must be > 0") - case c.Consumer.Fetch.Default <= 0: - return ConfigurationError("Consumer.Fetch.Default must be > 0") - case c.Consumer.Fetch.Max < 0: - return ConfigurationError("Consumer.Fetch.Max must be >= 0") - case c.Consumer.MaxWaitTime < 1*time.Millisecond: - return ConfigurationError("Consumer.MaxWaitTime must be >= 1ms") - case c.Consumer.MaxProcessingTime <= 0: - return ConfigurationError("Consumer.MaxProcessingTime must be > 0") - case c.Consumer.Retry.Backoff < 0: - return ConfigurationError("Consumer.Retry.Backoff must be >= 0") - case c.Consumer.Offsets.CommitInterval <= 0: - return ConfigurationError("Consumer.Offsets.CommitInterval must be > 0") - case c.Consumer.Offsets.Initial != OffsetOldest && c.Consumer.Offsets.Initial != OffsetNewest: - return ConfigurationError("Consumer.Offsets.Initial must be OffsetOldest or OffsetNewest") - - } - - // validate misc shared values - switch { - case c.ChannelBufferSize < 0: - return ConfigurationError("ChannelBufferSize must be >= 0") - case !validID.MatchString(c.ClientID): - return ConfigurationError("ClientID is invalid") - } - - return nil -} diff --git a/vendor/github.com/Shopify/sarama/consumer.go b/vendor/github.com/Shopify/sarama/consumer.go deleted file mode 100644 index 2ce69b00b..000000000 --- a/vendor/github.com/Shopify/sarama/consumer.go +++ /dev/null @@ -1,749 +0,0 @@ -package sarama - -import ( - "errors" - "fmt" - "sync" - "sync/atomic" - "time" -) - -// ConsumerMessage encapsulates a Kafka message returned by the consumer. -type ConsumerMessage struct { - Key, Value []byte - Topic string - Partition int32 - Offset int64 - Timestamp time.Time // only set if kafka is version 0.10+, inner message timestamp - BlockTimestamp time.Time // only set if kafka is version 0.10+, outer (compressed) block timestamp -} - -// ConsumerError is what is provided to the user when an error occurs. -// It wraps an error and includes the topic and partition. -type ConsumerError struct { - Topic string - Partition int32 - Err error -} - -func (ce ConsumerError) Error() string { - return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err) -} - -// ConsumerErrors is a type that wraps a batch of errors and implements the Error interface. -// It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors -// when stopping. -type ConsumerErrors []*ConsumerError - -func (ce ConsumerErrors) Error() string { - return fmt.Sprintf("kafka: %d errors while consuming", len(ce)) -} - -// Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close() -// on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of -// scope. -// -// Sarama's Consumer type does not currently support automatic consumer-group rebalancing and offset tracking. -// For Zookeeper-based tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka library -// builds on Sarama to add this support. For Kafka-based tracking (Kafka 0.9 and later), the -// https://github.com/bsm/sarama-cluster library builds on Sarama to add this support. -type Consumer interface { - - // Topics returns the set of available topics as retrieved from the cluster - // metadata. This method is the same as Client.Topics(), and is provided for - // convenience. - Topics() ([]string, error) - - // Partitions returns the sorted list of all partition IDs for the given topic. - // This method is the same as Client.Partitions(), and is provided for convenience. - Partitions(topic string) ([]int32, error) - - // ConsumePartition creates a PartitionConsumer on the given topic/partition with - // the given offset. It will return an error if this Consumer is already consuming - // on the given topic/partition. Offset can be a literal offset, or OffsetNewest - // or OffsetOldest - ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) - - // HighWaterMarks returns the current high water marks for each topic and partition. - // Consistency between partitions is not guaranteed since high water marks are updated separately. - HighWaterMarks() map[string]map[int32]int64 - - // Close shuts down the consumer. It must be called after all child - // PartitionConsumers have already been closed. - Close() error -} - -type consumer struct { - client Client - conf *Config - ownClient bool - - lock sync.Mutex - children map[string]map[int32]*partitionConsumer - brokerConsumers map[*Broker]*brokerConsumer -} - -// NewConsumer creates a new consumer using the given broker addresses and configuration. -func NewConsumer(addrs []string, config *Config) (Consumer, error) { - client, err := NewClient(addrs, config) - if err != nil { - return nil, err - } - - c, err := NewConsumerFromClient(client) - if err != nil { - return nil, err - } - c.(*consumer).ownClient = true - return c, nil -} - -// NewConsumerFromClient creates a new consumer using the given client. It is still -// necessary to call Close() on the underlying client when shutting down this consumer. -func NewConsumerFromClient(client Client) (Consumer, error) { - // Check that we are not dealing with a closed Client before processing any other arguments - if client.Closed() { - return nil, ErrClosedClient - } - - c := &consumer{ - client: client, - conf: client.Config(), - children: make(map[string]map[int32]*partitionConsumer), - brokerConsumers: make(map[*Broker]*brokerConsumer), - } - - return c, nil -} - -func (c *consumer) Close() error { - if c.ownClient { - return c.client.Close() - } - return nil -} - -func (c *consumer) Topics() ([]string, error) { - return c.client.Topics() -} - -func (c *consumer) Partitions(topic string) ([]int32, error) { - return c.client.Partitions(topic) -} - -func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) { - child := &partitionConsumer{ - consumer: c, - conf: c.conf, - topic: topic, - partition: partition, - messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize), - errors: make(chan *ConsumerError, c.conf.ChannelBufferSize), - feeder: make(chan *FetchResponse, 1), - trigger: make(chan none, 1), - dying: make(chan none), - fetchSize: c.conf.Consumer.Fetch.Default, - } - - if err := child.chooseStartingOffset(offset); err != nil { - return nil, err - } - - var leader *Broker - var err error - if leader, err = c.client.Leader(child.topic, child.partition); err != nil { - return nil, err - } - - if err := c.addChild(child); err != nil { - return nil, err - } - - go withRecover(child.dispatcher) - go withRecover(child.responseFeeder) - - child.broker = c.refBrokerConsumer(leader) - child.broker.input <- child - - return child, nil -} - -func (c *consumer) HighWaterMarks() map[string]map[int32]int64 { - c.lock.Lock() - defer c.lock.Unlock() - - hwms := make(map[string]map[int32]int64) - for topic, p := range c.children { - hwm := make(map[int32]int64, len(p)) - for partition, pc := range p { - hwm[partition] = pc.HighWaterMarkOffset() - } - hwms[topic] = hwm - } - - return hwms -} - -func (c *consumer) addChild(child *partitionConsumer) error { - c.lock.Lock() - defer c.lock.Unlock() - - topicChildren := c.children[child.topic] - if topicChildren == nil { - topicChildren = make(map[int32]*partitionConsumer) - c.children[child.topic] = topicChildren - } - - if topicChildren[child.partition] != nil { - return ConfigurationError("That topic/partition is already being consumed") - } - - topicChildren[child.partition] = child - return nil -} - -func (c *consumer) removeChild(child *partitionConsumer) { - c.lock.Lock() - defer c.lock.Unlock() - - delete(c.children[child.topic], child.partition) -} - -func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer { - c.lock.Lock() - defer c.lock.Unlock() - - bc := c.brokerConsumers[broker] - if bc == nil { - bc = c.newBrokerConsumer(broker) - c.brokerConsumers[broker] = bc - } - - bc.refs++ - - return bc -} - -func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) { - c.lock.Lock() - defer c.lock.Unlock() - - brokerWorker.refs-- - - if brokerWorker.refs == 0 { - close(brokerWorker.input) - if c.brokerConsumers[brokerWorker.broker] == brokerWorker { - delete(c.brokerConsumers, brokerWorker.broker) - } - } -} - -func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) { - c.lock.Lock() - defer c.lock.Unlock() - - delete(c.brokerConsumers, brokerWorker.broker) -} - -// PartitionConsumer - -// PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call one of Close() or -// AsyncClose() on a PartitionConsumer to avoid leaks; it will not be garbage-collected automatically when it passes out -// of scope. -// -// The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range -// loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported -// as out of range by the brokers. In this case you should decide what you want to do (try a different offset, -// notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying. -// By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set -// your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement -// or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches. -// -// To terminate such a for/range loop while the loop is executing, call AsyncClose. This will kick off the process of -// consumer tear-down & return imediately. Continue to loop, servicing the Messages channel until the teardown process -// AsyncClose initiated closes it (thus terminating the for/range loop). If you've already ceased reading Messages, call -// Close; this will signal the PartitionConsumer's goroutines to begin shutting down (just like AsyncClose), but will -// also drain the Messages channel, harvest all errors & return them once cleanup has completed. -type PartitionConsumer interface { - - // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately, after which you - // should continue to service the 'Messages' and 'Errors' channels until they are empty. It is required to call this - // function, or Close before a consumer object passes out of scope, as it will otherwise leak memory. You must call - // this before calling Close on the underlying client. - AsyncClose() - - // Close stops the PartitionConsumer from fetching messages. It will initiate a shutdown just like AsyncClose, drain - // the Messages channel, harvest any errors & return them to the caller. Note that if you are continuing to service - // the Messages channel when this function is called, you will be competing with Close for messages; consider - // calling AsyncClose, instead. It is required to call this function (or AsyncClose) before a consumer object passes - // out of scope, as it will otherwise leak memory. You must call this before calling Close on the underlying client. - Close() error - - // Messages returns the read channel for the messages that are returned by - // the broker. - Messages() <-chan *ConsumerMessage - - // Errors returns a read channel of errors that occurred during consuming, if - // enabled. By default, errors are logged and not returned over this channel. - // If you want to implement any custom error handling, set your config's - // Consumer.Return.Errors setting to true, and read from this channel. - Errors() <-chan *ConsumerError - - // HighWaterMarkOffset returns the high water mark offset of the partition, - // i.e. the offset that will be used for the next message that will be produced. - // You can use this to determine how far behind the processing is. - HighWaterMarkOffset() int64 -} - -type partitionConsumer struct { - highWaterMarkOffset int64 // must be at the top of the struct because https://golang.org/pkg/sync/atomic/#pkg-note-BUG - consumer *consumer - conf *Config - topic string - partition int32 - - broker *brokerConsumer - messages chan *ConsumerMessage - errors chan *ConsumerError - feeder chan *FetchResponse - - trigger, dying chan none - responseResult error - - fetchSize int32 - offset int64 -} - -var errTimedOut = errors.New("timed out feeding messages to the user") // not user-facing - -func (child *partitionConsumer) sendError(err error) { - cErr := &ConsumerError{ - Topic: child.topic, - Partition: child.partition, - Err: err, - } - - if child.conf.Consumer.Return.Errors { - child.errors <- cErr - } else { - Logger.Println(cErr) - } -} - -func (child *partitionConsumer) dispatcher() { - for range child.trigger { - select { - case <-child.dying: - close(child.trigger) - case <-time.After(child.conf.Consumer.Retry.Backoff): - if child.broker != nil { - child.consumer.unrefBrokerConsumer(child.broker) - child.broker = nil - } - - Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition) - if err := child.dispatch(); err != nil { - child.sendError(err) - child.trigger <- none{} - } - } - } - - if child.broker != nil { - child.consumer.unrefBrokerConsumer(child.broker) - } - child.consumer.removeChild(child) - close(child.feeder) -} - -func (child *partitionConsumer) dispatch() error { - if err := child.consumer.client.RefreshMetadata(child.topic); err != nil { - return err - } - - var leader *Broker - var err error - if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil { - return err - } - - child.broker = child.consumer.refBrokerConsumer(leader) - - child.broker.input <- child - - return nil -} - -func (child *partitionConsumer) chooseStartingOffset(offset int64) error { - newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest) - if err != nil { - return err - } - oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest) - if err != nil { - return err - } - - switch { - case offset == OffsetNewest: - child.offset = newestOffset - case offset == OffsetOldest: - child.offset = oldestOffset - case offset >= oldestOffset && offset <= newestOffset: - child.offset = offset - default: - return ErrOffsetOutOfRange - } - - return nil -} - -func (child *partitionConsumer) Messages() <-chan *ConsumerMessage { - return child.messages -} - -func (child *partitionConsumer) Errors() <-chan *ConsumerError { - return child.errors -} - -func (child *partitionConsumer) AsyncClose() { - // this triggers whatever broker owns this child to abandon it and close its trigger channel, which causes - // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and - // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will - // also just close itself) - close(child.dying) -} - -func (child *partitionConsumer) Close() error { - child.AsyncClose() - - go withRecover(func() { - for range child.messages { - // drain - } - }) - - var errors ConsumerErrors - for err := range child.errors { - errors = append(errors, err) - } - - if len(errors) > 0 { - return errors - } - return nil -} - -func (child *partitionConsumer) HighWaterMarkOffset() int64 { - return atomic.LoadInt64(&child.highWaterMarkOffset) -} - -func (child *partitionConsumer) responseFeeder() { - var msgs []*ConsumerMessage - msgSent := false - -feederLoop: - for response := range child.feeder { - msgs, child.responseResult = child.parseResponse(response) - expiryTicker := time.NewTicker(child.conf.Consumer.MaxProcessingTime) - - for i, msg := range msgs { - messageSelect: - select { - case child.messages <- msg: - msgSent = true - case <-expiryTicker.C: - if !msgSent { - child.responseResult = errTimedOut - child.broker.acks.Done() - for _, msg = range msgs[i:] { - child.messages <- msg - } - child.broker.input <- child - continue feederLoop - } else { - // current message has not been sent, return to select - // statement - msgSent = false - goto messageSelect - } - } - } - - expiryTicker.Stop() - child.broker.acks.Done() - } - - close(child.messages) - close(child.errors) -} - -func (child *partitionConsumer) parseResponse(response *FetchResponse) ([]*ConsumerMessage, error) { - block := response.GetBlock(child.topic, child.partition) - if block == nil { - return nil, ErrIncompleteResponse - } - - if block.Err != ErrNoError { - return nil, block.Err - } - - if len(block.MsgSet.Messages) == 0 { - // We got no messages. If we got a trailing one then we need to ask for more data. - // Otherwise we just poll again and wait for one to be produced... - if block.MsgSet.PartialTrailingMessage { - if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max { - // we can't ask for more data, we've hit the configured limit - child.sendError(ErrMessageTooLarge) - child.offset++ // skip this one so we can keep processing future messages - } else { - child.fetchSize *= 2 - if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max { - child.fetchSize = child.conf.Consumer.Fetch.Max - } - } - } - - return nil, nil - } - - // we got messages, reset our fetch size in case it was increased for a previous request - child.fetchSize = child.conf.Consumer.Fetch.Default - atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset) - - incomplete := false - prelude := true - var messages []*ConsumerMessage - for _, msgBlock := range block.MsgSet.Messages { - - for _, msg := range msgBlock.Messages() { - offset := msg.Offset - if msg.Msg.Version >= 1 { - baseOffset := msgBlock.Offset - msgBlock.Messages()[len(msgBlock.Messages())-1].Offset - offset += baseOffset - } - if prelude && offset < child.offset { - continue - } - prelude = false - - if offset >= child.offset { - messages = append(messages, &ConsumerMessage{ - Topic: child.topic, - Partition: child.partition, - Key: msg.Msg.Key, - Value: msg.Msg.Value, - Offset: offset, - Timestamp: msg.Msg.Timestamp, - BlockTimestamp: msgBlock.Msg.Timestamp, - }) - child.offset = offset + 1 - } else { - incomplete = true - } - } - - } - - if incomplete || len(messages) == 0 { - return nil, ErrIncompleteResponse - } - return messages, nil -} - -// brokerConsumer - -type brokerConsumer struct { - consumer *consumer - broker *Broker - input chan *partitionConsumer - newSubscriptions chan []*partitionConsumer - wait chan none - subscriptions map[*partitionConsumer]none - acks sync.WaitGroup - refs int -} - -func (c *consumer) newBrokerConsumer(broker *Broker) *brokerConsumer { - bc := &brokerConsumer{ - consumer: c, - broker: broker, - input: make(chan *partitionConsumer), - newSubscriptions: make(chan []*partitionConsumer), - wait: make(chan none), - subscriptions: make(map[*partitionConsumer]none), - refs: 0, - } - - go withRecover(bc.subscriptionManager) - go withRecover(bc.subscriptionConsumer) - - return bc -} - -func (bc *brokerConsumer) subscriptionManager() { - var buffer []*partitionConsumer - - // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer - // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks - // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give - // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available, - // so the main goroutine can block waiting for work if it has none. - for { - if len(buffer) > 0 { - select { - case event, ok := <-bc.input: - if !ok { - goto done - } - buffer = append(buffer, event) - case bc.newSubscriptions <- buffer: - buffer = nil - case bc.wait <- none{}: - } - } else { - select { - case event, ok := <-bc.input: - if !ok { - goto done - } - buffer = append(buffer, event) - case bc.newSubscriptions <- nil: - } - } - } - -done: - close(bc.wait) - if len(buffer) > 0 { - bc.newSubscriptions <- buffer - } - close(bc.newSubscriptions) -} - -func (bc *brokerConsumer) subscriptionConsumer() { - <-bc.wait // wait for our first piece of work - - // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available - for newSubscriptions := range bc.newSubscriptions { - bc.updateSubscriptions(newSubscriptions) - - if len(bc.subscriptions) == 0 { - // We're about to be shut down or we're about to receive more subscriptions. - // Either way, the signal just hasn't propagated to our goroutine yet. - <-bc.wait - continue - } - - response, err := bc.fetchNewMessages() - - if err != nil { - Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", bc.broker.ID(), err) - bc.abort(err) - return - } - - bc.acks.Add(len(bc.subscriptions)) - for child := range bc.subscriptions { - child.feeder <- response - } - bc.acks.Wait() - bc.handleResponses() - } -} - -func (bc *brokerConsumer) updateSubscriptions(newSubscriptions []*partitionConsumer) { - for _, child := range newSubscriptions { - bc.subscriptions[child] = none{} - Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition) - } - - for child := range bc.subscriptions { - select { - case <-child.dying: - Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition) - close(child.trigger) - delete(bc.subscriptions, child) - default: - break - } - } -} - -func (bc *brokerConsumer) handleResponses() { - // handles the response codes left for us by our subscriptions, and abandons ones that have been closed - for child := range bc.subscriptions { - result := child.responseResult - child.responseResult = nil - - switch result { - case nil: - break - case errTimedOut: - Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because consuming was taking too long\n", - bc.broker.ID(), child.topic, child.partition) - delete(bc.subscriptions, child) - case ErrOffsetOutOfRange: - // there's no point in retrying this it will just fail the same way again - // shut it down and force the user to choose what to do - child.sendError(result) - Logger.Printf("consumer/%s/%d shutting down because %s\n", child.topic, child.partition, result) - close(child.trigger) - delete(bc.subscriptions, child) - case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable, ErrReplicaNotAvailable: - // not an error, but does need redispatching - Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n", - bc.broker.ID(), child.topic, child.partition, result) - child.trigger <- none{} - delete(bc.subscriptions, child) - default: - // dunno, tell the user and try redispatching - child.sendError(result) - Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n", - bc.broker.ID(), child.topic, child.partition, result) - child.trigger <- none{} - delete(bc.subscriptions, child) - } - } -} - -func (bc *brokerConsumer) abort(err error) { - bc.consumer.abandonBrokerConsumer(bc) - _ = bc.broker.Close() // we don't care about the error this might return, we already have one - - for child := range bc.subscriptions { - child.sendError(err) - child.trigger <- none{} - } - - for newSubscriptions := range bc.newSubscriptions { - if len(newSubscriptions) == 0 { - <-bc.wait - continue - } - for _, child := range newSubscriptions { - child.sendError(err) - child.trigger <- none{} - } - } -} - -func (bc *brokerConsumer) fetchNewMessages() (*FetchResponse, error) { - request := &FetchRequest{ - MinBytes: bc.consumer.conf.Consumer.Fetch.Min, - MaxWaitTime: int32(bc.consumer.conf.Consumer.MaxWaitTime / time.Millisecond), - } - if bc.consumer.conf.Version.IsAtLeast(V0_10_0_0) { - request.Version = 2 - } - if bc.consumer.conf.Version.IsAtLeast(V0_10_1_0) { - request.Version = 3 - request.MaxBytes = MaxResponseSize - } - - for child := range bc.subscriptions { - request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize) - } - - return bc.broker.Fetch(request) -} diff --git a/vendor/github.com/Shopify/sarama/consumer_group_members.go b/vendor/github.com/Shopify/sarama/consumer_group_members.go deleted file mode 100644 index 9d92d350a..000000000 --- a/vendor/github.com/Shopify/sarama/consumer_group_members.go +++ /dev/null @@ -1,94 +0,0 @@ -package sarama - -type ConsumerGroupMemberMetadata struct { - Version int16 - Topics []string - UserData []byte -} - -func (m *ConsumerGroupMemberMetadata) encode(pe packetEncoder) error { - pe.putInt16(m.Version) - - if err := pe.putStringArray(m.Topics); err != nil { - return err - } - - if err := pe.putBytes(m.UserData); err != nil { - return err - } - - return nil -} - -func (m *ConsumerGroupMemberMetadata) decode(pd packetDecoder) (err error) { - if m.Version, err = pd.getInt16(); err != nil { - return - } - - if m.Topics, err = pd.getStringArray(); err != nil { - return - } - - if m.UserData, err = pd.getBytes(); err != nil { - return - } - - return nil -} - -type ConsumerGroupMemberAssignment struct { - Version int16 - Topics map[string][]int32 - UserData []byte -} - -func (m *ConsumerGroupMemberAssignment) encode(pe packetEncoder) error { - pe.putInt16(m.Version) - - if err := pe.putArrayLength(len(m.Topics)); err != nil { - return err - } - - for topic, partitions := range m.Topics { - if err := pe.putString(topic); err != nil { - return err - } - if err := pe.putInt32Array(partitions); err != nil { - return err - } - } - - if err := pe.putBytes(m.UserData); err != nil { - return err - } - - return nil -} - -func (m *ConsumerGroupMemberAssignment) decode(pd packetDecoder) (err error) { - if m.Version, err = pd.getInt16(); err != nil { - return - } - - var topicLen int - if topicLen, err = pd.getArrayLength(); err != nil { - return - } - - m.Topics = make(map[string][]int32, topicLen) - for i := 0; i < topicLen; i++ { - var topic string - if topic, err = pd.getString(); err != nil { - return - } - if m.Topics[topic], err = pd.getInt32Array(); err != nil { - return - } - } - - if m.UserData, err = pd.getBytes(); err != nil { - return - } - - return nil -} diff --git a/vendor/github.com/Shopify/sarama/consumer_metadata_request.go b/vendor/github.com/Shopify/sarama/consumer_metadata_request.go deleted file mode 100644 index 483be3354..000000000 --- a/vendor/github.com/Shopify/sarama/consumer_metadata_request.go +++ /dev/null @@ -1,26 +0,0 @@ -package sarama - -type ConsumerMetadataRequest struct { - ConsumerGroup string -} - -func (r *ConsumerMetadataRequest) encode(pe packetEncoder) error { - return pe.putString(r.ConsumerGroup) -} - -func (r *ConsumerMetadataRequest) decode(pd packetDecoder, version int16) (err error) { - r.ConsumerGroup, err = pd.getString() - return err -} - -func (r *ConsumerMetadataRequest) key() int16 { - return 10 -} - -func (r *ConsumerMetadataRequest) version() int16 { - return 0 -} - -func (r *ConsumerMetadataRequest) requiredVersion() KafkaVersion { - return V0_8_2_0 -} diff --git a/vendor/github.com/Shopify/sarama/consumer_metadata_response.go b/vendor/github.com/Shopify/sarama/consumer_metadata_response.go deleted file mode 100644 index 6b9632bba..000000000 --- a/vendor/github.com/Shopify/sarama/consumer_metadata_response.go +++ /dev/null @@ -1,85 +0,0 @@ -package sarama - -import ( - "net" - "strconv" -) - -type ConsumerMetadataResponse struct { - Err KError - Coordinator *Broker - CoordinatorID int32 // deprecated: use Coordinator.ID() - CoordinatorHost string // deprecated: use Coordinator.Addr() - CoordinatorPort int32 // deprecated: use Coordinator.Addr() -} - -func (r *ConsumerMetadataResponse) decode(pd packetDecoder, version int16) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - r.Err = KError(tmp) - - coordinator := new(Broker) - if err := coordinator.decode(pd); err != nil { - return err - } - if coordinator.addr == ":0" { - return nil - } - r.Coordinator = coordinator - - // this can all go away in 2.0, but we have to fill in deprecated fields to maintain - // backwards compatibility - host, portstr, err := net.SplitHostPort(r.Coordinator.Addr()) - if err != nil { - return err - } - port, err := strconv.ParseInt(portstr, 10, 32) - if err != nil { - return err - } - r.CoordinatorID = r.Coordinator.ID() - r.CoordinatorHost = host - r.CoordinatorPort = int32(port) - - return nil -} - -func (r *ConsumerMetadataResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - if r.Coordinator != nil { - host, portstr, err := net.SplitHostPort(r.Coordinator.Addr()) - if err != nil { - return err - } - port, err := strconv.ParseInt(portstr, 10, 32) - if err != nil { - return err - } - pe.putInt32(r.Coordinator.ID()) - if err := pe.putString(host); err != nil { - return err - } - pe.putInt32(int32(port)) - return nil - } - pe.putInt32(r.CoordinatorID) - if err := pe.putString(r.CoordinatorHost); err != nil { - return err - } - pe.putInt32(r.CoordinatorPort) - return nil -} - -func (r *ConsumerMetadataResponse) key() int16 { - return 10 -} - -func (r *ConsumerMetadataResponse) version() int16 { - return 0 -} - -func (r *ConsumerMetadataResponse) requiredVersion() KafkaVersion { - return V0_8_2_0 -} diff --git a/vendor/github.com/Shopify/sarama/crc32_field.go b/vendor/github.com/Shopify/sarama/crc32_field.go deleted file mode 100644 index e7da08c6f..000000000 --- a/vendor/github.com/Shopify/sarama/crc32_field.go +++ /dev/null @@ -1,37 +0,0 @@ -package sarama - -import ( - "encoding/binary" - "fmt" - "hash/crc32" -) - -// crc32Field implements the pushEncoder and pushDecoder interfaces for calculating CRC32s. -type crc32Field struct { - startOffset int -} - -func (c *crc32Field) saveOffset(in int) { - c.startOffset = in -} - -func (c *crc32Field) reserveLength() int { - return 4 -} - -func (c *crc32Field) run(curOffset int, buf []byte) error { - crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset]) - binary.BigEndian.PutUint32(buf[c.startOffset:], crc) - return nil -} - -func (c *crc32Field) check(curOffset int, buf []byte) error { - crc := crc32.ChecksumIEEE(buf[c.startOffset+4 : curOffset]) - - expected := binary.BigEndian.Uint32(buf[c.startOffset:]) - if crc != expected { - return PacketDecodingError{fmt.Sprintf("CRC didn't match expected %#x got %#x", expected, crc)} - } - - return nil -} diff --git a/vendor/github.com/Shopify/sarama/describe_groups_request.go b/vendor/github.com/Shopify/sarama/describe_groups_request.go deleted file mode 100644 index 1fb356777..000000000 --- a/vendor/github.com/Shopify/sarama/describe_groups_request.go +++ /dev/null @@ -1,30 +0,0 @@ -package sarama - -type DescribeGroupsRequest struct { - Groups []string -} - -func (r *DescribeGroupsRequest) encode(pe packetEncoder) error { - return pe.putStringArray(r.Groups) -} - -func (r *DescribeGroupsRequest) decode(pd packetDecoder, version int16) (err error) { - r.Groups, err = pd.getStringArray() - return -} - -func (r *DescribeGroupsRequest) key() int16 { - return 15 -} - -func (r *DescribeGroupsRequest) version() int16 { - return 0 -} - -func (r *DescribeGroupsRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} - -func (r *DescribeGroupsRequest) AddGroup(group string) { - r.Groups = append(r.Groups, group) -} diff --git a/vendor/github.com/Shopify/sarama/describe_groups_response.go b/vendor/github.com/Shopify/sarama/describe_groups_response.go deleted file mode 100644 index 542b3a971..000000000 --- a/vendor/github.com/Shopify/sarama/describe_groups_response.go +++ /dev/null @@ -1,187 +0,0 @@ -package sarama - -type DescribeGroupsResponse struct { - Groups []*GroupDescription -} - -func (r *DescribeGroupsResponse) encode(pe packetEncoder) error { - if err := pe.putArrayLength(len(r.Groups)); err != nil { - return err - } - - for _, groupDescription := range r.Groups { - if err := groupDescription.encode(pe); err != nil { - return err - } - } - - return nil -} - -func (r *DescribeGroupsResponse) decode(pd packetDecoder, version int16) (err error) { - n, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Groups = make([]*GroupDescription, n) - for i := 0; i < n; i++ { - r.Groups[i] = new(GroupDescription) - if err := r.Groups[i].decode(pd); err != nil { - return err - } - } - - return nil -} - -func (r *DescribeGroupsResponse) key() int16 { - return 15 -} - -func (r *DescribeGroupsResponse) version() int16 { - return 0 -} - -func (r *DescribeGroupsResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} - -type GroupDescription struct { - Err KError - GroupId string - State string - ProtocolType string - Protocol string - Members map[string]*GroupMemberDescription -} - -func (gd *GroupDescription) encode(pe packetEncoder) error { - pe.putInt16(int16(gd.Err)) - - if err := pe.putString(gd.GroupId); err != nil { - return err - } - if err := pe.putString(gd.State); err != nil { - return err - } - if err := pe.putString(gd.ProtocolType); err != nil { - return err - } - if err := pe.putString(gd.Protocol); err != nil { - return err - } - - if err := pe.putArrayLength(len(gd.Members)); err != nil { - return err - } - - for memberId, groupMemberDescription := range gd.Members { - if err := pe.putString(memberId); err != nil { - return err - } - if err := groupMemberDescription.encode(pe); err != nil { - return err - } - } - - return nil -} - -func (gd *GroupDescription) decode(pd packetDecoder) (err error) { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - gd.Err = KError(kerr) - - if gd.GroupId, err = pd.getString(); err != nil { - return - } - if gd.State, err = pd.getString(); err != nil { - return - } - if gd.ProtocolType, err = pd.getString(); err != nil { - return - } - if gd.Protocol, err = pd.getString(); err != nil { - return - } - - n, err := pd.getArrayLength() - if err != nil { - return err - } - if n == 0 { - return nil - } - - gd.Members = make(map[string]*GroupMemberDescription) - for i := 0; i < n; i++ { - memberId, err := pd.getString() - if err != nil { - return err - } - - gd.Members[memberId] = new(GroupMemberDescription) - if err := gd.Members[memberId].decode(pd); err != nil { - return err - } - } - - return nil -} - -type GroupMemberDescription struct { - ClientId string - ClientHost string - MemberMetadata []byte - MemberAssignment []byte -} - -func (gmd *GroupMemberDescription) encode(pe packetEncoder) error { - if err := pe.putString(gmd.ClientId); err != nil { - return err - } - if err := pe.putString(gmd.ClientHost); err != nil { - return err - } - if err := pe.putBytes(gmd.MemberMetadata); err != nil { - return err - } - if err := pe.putBytes(gmd.MemberAssignment); err != nil { - return err - } - - return nil -} - -func (gmd *GroupMemberDescription) decode(pd packetDecoder) (err error) { - if gmd.ClientId, err = pd.getString(); err != nil { - return - } - if gmd.ClientHost, err = pd.getString(); err != nil { - return - } - if gmd.MemberMetadata, err = pd.getBytes(); err != nil { - return - } - if gmd.MemberAssignment, err = pd.getBytes(); err != nil { - return - } - - return nil -} - -func (gmd *GroupMemberDescription) GetMemberAssignment() (*ConsumerGroupMemberAssignment, error) { - assignment := new(ConsumerGroupMemberAssignment) - err := decode(gmd.MemberAssignment, assignment) - return assignment, err -} - -func (gmd *GroupMemberDescription) GetMemberMetadata() (*ConsumerGroupMemberMetadata, error) { - metadata := new(ConsumerGroupMemberMetadata) - err := decode(gmd.MemberMetadata, metadata) - return metadata, err -} diff --git a/vendor/github.com/Shopify/sarama/encoder_decoder.go b/vendor/github.com/Shopify/sarama/encoder_decoder.go deleted file mode 100644 index 7ce3bc0f6..000000000 --- a/vendor/github.com/Shopify/sarama/encoder_decoder.go +++ /dev/null @@ -1,89 +0,0 @@ -package sarama - -import ( - "fmt" - - "github.com/rcrowley/go-metrics" -) - -// Encoder is the interface that wraps the basic Encode method. -// Anything implementing Encoder can be turned into bytes using Kafka's encoding rules. -type encoder interface { - encode(pe packetEncoder) error -} - -// Encode takes an Encoder and turns it into bytes while potentially recording metrics. -func encode(e encoder, metricRegistry metrics.Registry) ([]byte, error) { - if e == nil { - return nil, nil - } - - var prepEnc prepEncoder - var realEnc realEncoder - - err := e.encode(&prepEnc) - if err != nil { - return nil, err - } - - if prepEnc.length < 0 || prepEnc.length > int(MaxRequestSize) { - return nil, PacketEncodingError{fmt.Sprintf("invalid request size (%d)", prepEnc.length)} - } - - realEnc.raw = make([]byte, prepEnc.length) - realEnc.registry = metricRegistry - err = e.encode(&realEnc) - if err != nil { - return nil, err - } - - return realEnc.raw, nil -} - -// Decoder is the interface that wraps the basic Decode method. -// Anything implementing Decoder can be extracted from bytes using Kafka's encoding rules. -type decoder interface { - decode(pd packetDecoder) error -} - -type versionedDecoder interface { - decode(pd packetDecoder, version int16) error -} - -// Decode takes bytes and a Decoder and fills the fields of the decoder from the bytes, -// interpreted using Kafka's encoding rules. -func decode(buf []byte, in decoder) error { - if buf == nil { - return nil - } - - helper := realDecoder{raw: buf} - err := in.decode(&helper) - if err != nil { - return err - } - - if helper.off != len(buf) { - return PacketDecodingError{"invalid length"} - } - - return nil -} - -func versionedDecode(buf []byte, in versionedDecoder, version int16) error { - if buf == nil { - return nil - } - - helper := realDecoder{raw: buf} - err := in.decode(&helper, version) - if err != nil { - return err - } - - if helper.off != len(buf) { - return PacketDecodingError{"invalid length"} - } - - return nil -} diff --git a/vendor/github.com/Shopify/sarama/errors.go b/vendor/github.com/Shopify/sarama/errors.go deleted file mode 100644 index e6800ed49..000000000 --- a/vendor/github.com/Shopify/sarama/errors.go +++ /dev/null @@ -1,221 +0,0 @@ -package sarama - -import ( - "errors" - "fmt" -) - -// ErrOutOfBrokers is the error returned when the client has run out of brokers to talk to because all of them errored -// or otherwise failed to respond. -var ErrOutOfBrokers = errors.New("kafka: client has run out of available brokers to talk to (Is your cluster reachable?)") - -// ErrClosedClient is the error returned when a method is called on a client that has been closed. -var ErrClosedClient = errors.New("kafka: tried to use a client that was closed") - -// ErrIncompleteResponse is the error returned when the server returns a syntactically valid response, but it does -// not contain the expected information. -var ErrIncompleteResponse = errors.New("kafka: response did not contain all the expected topic/partition blocks") - -// ErrInvalidPartition is the error returned when a partitioner returns an invalid partition index -// (meaning one outside of the range [0...numPartitions-1]). -var ErrInvalidPartition = errors.New("kafka: partitioner returned an invalid partition index") - -// ErrAlreadyConnected is the error returned when calling Open() on a Broker that is already connected or connecting. -var ErrAlreadyConnected = errors.New("kafka: broker connection already initiated") - -// ErrNotConnected is the error returned when trying to send or call Close() on a Broker that is not connected. -var ErrNotConnected = errors.New("kafka: broker not connected") - -// ErrInsufficientData is returned when decoding and the packet is truncated. This can be expected -// when requesting messages, since as an optimization the server is allowed to return a partial message at the end -// of the message set. -var ErrInsufficientData = errors.New("kafka: insufficient data to decode packet, more bytes expected") - -// ErrShuttingDown is returned when a producer receives a message during shutdown. -var ErrShuttingDown = errors.New("kafka: message received by producer in process of shutting down") - -// ErrMessageTooLarge is returned when the next message to consume is larger than the configured Consumer.Fetch.Max -var ErrMessageTooLarge = errors.New("kafka: message is larger than Consumer.Fetch.Max") - -// PacketEncodingError is returned from a failure while encoding a Kafka packet. This can happen, for example, -// if you try to encode a string over 2^15 characters in length, since Kafka's encoding rules do not permit that. -type PacketEncodingError struct { - Info string -} - -func (err PacketEncodingError) Error() string { - return fmt.Sprintf("kafka: error encoding packet: %s", err.Info) -} - -// PacketDecodingError is returned when there was an error (other than truncated data) decoding the Kafka broker's response. -// This can be a bad CRC or length field, or any other invalid value. -type PacketDecodingError struct { - Info string -} - -func (err PacketDecodingError) Error() string { - return fmt.Sprintf("kafka: error decoding packet: %s", err.Info) -} - -// ConfigurationError is the type of error returned from a constructor (e.g. NewClient, or NewConsumer) -// when the specified configuration is invalid. -type ConfigurationError string - -func (err ConfigurationError) Error() string { - return "kafka: invalid configuration (" + string(err) + ")" -} - -// KError is the type of error that can be returned directly by the Kafka broker. -// See https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-ErrorCodes -type KError int16 - -// Numeric error codes returned by the Kafka server. -const ( - ErrNoError KError = 0 - ErrUnknown KError = -1 - ErrOffsetOutOfRange KError = 1 - ErrInvalidMessage KError = 2 - ErrUnknownTopicOrPartition KError = 3 - ErrInvalidMessageSize KError = 4 - ErrLeaderNotAvailable KError = 5 - ErrNotLeaderForPartition KError = 6 - ErrRequestTimedOut KError = 7 - ErrBrokerNotAvailable KError = 8 - ErrReplicaNotAvailable KError = 9 - ErrMessageSizeTooLarge KError = 10 - ErrStaleControllerEpochCode KError = 11 - ErrOffsetMetadataTooLarge KError = 12 - ErrNetworkException KError = 13 - ErrOffsetsLoadInProgress KError = 14 - ErrConsumerCoordinatorNotAvailable KError = 15 - ErrNotCoordinatorForConsumer KError = 16 - ErrInvalidTopic KError = 17 - ErrMessageSetSizeTooLarge KError = 18 - ErrNotEnoughReplicas KError = 19 - ErrNotEnoughReplicasAfterAppend KError = 20 - ErrInvalidRequiredAcks KError = 21 - ErrIllegalGeneration KError = 22 - ErrInconsistentGroupProtocol KError = 23 - ErrInvalidGroupId KError = 24 - ErrUnknownMemberId KError = 25 - ErrInvalidSessionTimeout KError = 26 - ErrRebalanceInProgress KError = 27 - ErrInvalidCommitOffsetSize KError = 28 - ErrTopicAuthorizationFailed KError = 29 - ErrGroupAuthorizationFailed KError = 30 - ErrClusterAuthorizationFailed KError = 31 - ErrInvalidTimestamp KError = 32 - ErrUnsupportedSASLMechanism KError = 33 - ErrIllegalSASLState KError = 34 - ErrUnsupportedVersion KError = 35 - ErrTopicAlreadyExists KError = 36 - ErrInvalidPartitions KError = 37 - ErrInvalidReplicationFactor KError = 38 - ErrInvalidReplicaAssignment KError = 39 - ErrInvalidConfig KError = 40 - ErrNotController KError = 41 - ErrInvalidRequest KError = 42 - ErrUnsupportedForMessageFormat KError = 43 - ErrPolicyViolation KError = 44 -) - -func (err KError) Error() string { - // Error messages stolen/adapted from - // https://kafka.apache.org/protocol#protocol_error_codes - switch err { - case ErrNoError: - return "kafka server: Not an error, why are you printing me?" - case ErrUnknown: - return "kafka server: Unexpected (unknown?) server error." - case ErrOffsetOutOfRange: - return "kafka server: The requested offset is outside the range of offsets maintained by the server for the given topic/partition." - case ErrInvalidMessage: - return "kafka server: Message contents does not match its CRC." - case ErrUnknownTopicOrPartition: - return "kafka server: Request was for a topic or partition that does not exist on this broker." - case ErrInvalidMessageSize: - return "kafka server: The message has a negative size." - case ErrLeaderNotAvailable: - return "kafka server: In the middle of a leadership election, there is currently no leader for this partition and hence it is unavailable for writes." - case ErrNotLeaderForPartition: - return "kafka server: Tried to send a message to a replica that is not the leader for some partition. Your metadata is out of date." - case ErrRequestTimedOut: - return "kafka server: Request exceeded the user-specified time limit in the request." - case ErrBrokerNotAvailable: - return "kafka server: Broker not available. Not a client facing error, we should never receive this!!!" - case ErrReplicaNotAvailable: - return "kafka server: Replica information not available, one or more brokers are down." - case ErrMessageSizeTooLarge: - return "kafka server: Message was too large, server rejected it to avoid allocation error." - case ErrStaleControllerEpochCode: - return "kafka server: StaleControllerEpochCode (internal error code for broker-to-broker communication)." - case ErrOffsetMetadataTooLarge: - return "kafka server: Specified a string larger than the configured maximum for offset metadata." - case ErrNetworkException: - return "kafka server: The server disconnected before a response was received." - case ErrOffsetsLoadInProgress: - return "kafka server: The broker is still loading offsets after a leader change for that offset's topic partition." - case ErrConsumerCoordinatorNotAvailable: - return "kafka server: Offset's topic has not yet been created." - case ErrNotCoordinatorForConsumer: - return "kafka server: Request was for a consumer group that is not coordinated by this broker." - case ErrInvalidTopic: - return "kafka server: The request attempted to perform an operation on an invalid topic." - case ErrMessageSetSizeTooLarge: - return "kafka server: The request included message batch larger than the configured segment size on the server." - case ErrNotEnoughReplicas: - return "kafka server: Messages are rejected since there are fewer in-sync replicas than required." - case ErrNotEnoughReplicasAfterAppend: - return "kafka server: Messages are written to the log, but to fewer in-sync replicas than required." - case ErrInvalidRequiredAcks: - return "kafka server: The number of required acks is invalid (should be either -1, 0, or 1)." - case ErrIllegalGeneration: - return "kafka server: The provided generation id is not the current generation." - case ErrInconsistentGroupProtocol: - return "kafka server: The provider group protocol type is incompatible with the other members." - case ErrInvalidGroupId: - return "kafka server: The provided group id was empty." - case ErrUnknownMemberId: - return "kafka server: The provided member is not known in the current generation." - case ErrInvalidSessionTimeout: - return "kafka server: The provided session timeout is outside the allowed range." - case ErrRebalanceInProgress: - return "kafka server: A rebalance for the group is in progress. Please re-join the group." - case ErrInvalidCommitOffsetSize: - return "kafka server: The provided commit metadata was too large." - case ErrTopicAuthorizationFailed: - return "kafka server: The client is not authorized to access this topic." - case ErrGroupAuthorizationFailed: - return "kafka server: The client is not authorized to access this group." - case ErrClusterAuthorizationFailed: - return "kafka server: The client is not authorized to send this request type." - case ErrInvalidTimestamp: - return "kafka server: The timestamp of the message is out of acceptable range." - case ErrUnsupportedSASLMechanism: - return "kafka server: The broker does not support the requested SASL mechanism." - case ErrIllegalSASLState: - return "kafka server: Request is not valid given the current SASL state." - case ErrUnsupportedVersion: - return "kafka server: The version of API is not supported." - case ErrTopicAlreadyExists: - return "kafka server: Topic with this name already exists." - case ErrInvalidPartitions: - return "kafka server: Number of partitions is invalid." - case ErrInvalidReplicationFactor: - return "kafka server: Replication-factor is invalid." - case ErrInvalidReplicaAssignment: - return "kafka server: Replica assignment is invalid." - case ErrInvalidConfig: - return "kafka server: Configuration is invalid." - case ErrNotController: - return "kafka server: This is not the correct controller for this cluster." - case ErrInvalidRequest: - return "kafka server: This most likely occurs because of a request being malformed by the client library or the message was sent to an incompatible broker. See the broker logs for more details." - case ErrUnsupportedForMessageFormat: - return "kafka server: The requested operation is not supported by the message format version." - case ErrPolicyViolation: - return "kafka server: Request parameters do not satisfy the configured policy." - } - - return fmt.Sprintf("Unknown error, how did this happen? Error code = %d", err) -} diff --git a/vendor/github.com/Shopify/sarama/fetch_request.go b/vendor/github.com/Shopify/sarama/fetch_request.go deleted file mode 100644 index 65600e86e..000000000 --- a/vendor/github.com/Shopify/sarama/fetch_request.go +++ /dev/null @@ -1,150 +0,0 @@ -package sarama - -type fetchRequestBlock struct { - fetchOffset int64 - maxBytes int32 -} - -func (b *fetchRequestBlock) encode(pe packetEncoder) error { - pe.putInt64(b.fetchOffset) - pe.putInt32(b.maxBytes) - return nil -} - -func (b *fetchRequestBlock) decode(pd packetDecoder) (err error) { - if b.fetchOffset, err = pd.getInt64(); err != nil { - return err - } - if b.maxBytes, err = pd.getInt32(); err != nil { - return err - } - return nil -} - -// FetchRequest (API key 1) will fetch Kafka messages. Version 3 introduced the MaxBytes field. See -// https://issues.apache.org/jira/browse/KAFKA-2063 for a discussion of the issues leading up to that. The KIP is at -// https://cwiki.apache.org/confluence/display/KAFKA/KIP-74%3A+Add+Fetch+Response+Size+Limit+in+Bytes -type FetchRequest struct { - MaxWaitTime int32 - MinBytes int32 - MaxBytes int32 - Version int16 - blocks map[string]map[int32]*fetchRequestBlock -} - -func (r *FetchRequest) encode(pe packetEncoder) (err error) { - pe.putInt32(-1) // replica ID is always -1 for clients - pe.putInt32(r.MaxWaitTime) - pe.putInt32(r.MinBytes) - if r.Version == 3 { - pe.putInt32(r.MaxBytes) - } - err = pe.putArrayLength(len(r.blocks)) - if err != nil { - return err - } - for topic, blocks := range r.blocks { - err = pe.putString(topic) - if err != nil { - return err - } - err = pe.putArrayLength(len(blocks)) - if err != nil { - return err - } - for partition, block := range blocks { - pe.putInt32(partition) - err = block.encode(pe) - if err != nil { - return err - } - } - } - return nil -} - -func (r *FetchRequest) decode(pd packetDecoder, version int16) (err error) { - r.Version = version - if _, err = pd.getInt32(); err != nil { - return err - } - if r.MaxWaitTime, err = pd.getInt32(); err != nil { - return err - } - if r.MinBytes, err = pd.getInt32(); err != nil { - return err - } - if r.Version == 3 { - if r.MaxBytes, err = pd.getInt32(); err != nil { - return err - } - } - topicCount, err := pd.getArrayLength() - if err != nil { - return err - } - if topicCount == 0 { - return nil - } - r.blocks = make(map[string]map[int32]*fetchRequestBlock) - for i := 0; i < topicCount; i++ { - topic, err := pd.getString() - if err != nil { - return err - } - partitionCount, err := pd.getArrayLength() - if err != nil { - return err - } - r.blocks[topic] = make(map[int32]*fetchRequestBlock) - for j := 0; j < partitionCount; j++ { - partition, err := pd.getInt32() - if err != nil { - return err - } - fetchBlock := &fetchRequestBlock{} - if err = fetchBlock.decode(pd); err != nil { - return err - } - r.blocks[topic][partition] = fetchBlock - } - } - return nil -} - -func (r *FetchRequest) key() int16 { - return 1 -} - -func (r *FetchRequest) version() int16 { - return r.Version -} - -func (r *FetchRequest) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_9_0_0 - case 2: - return V0_10_0_0 - case 3: - return V0_10_1_0 - default: - return minVersion - } -} - -func (r *FetchRequest) AddBlock(topic string, partitionID int32, fetchOffset int64, maxBytes int32) { - if r.blocks == nil { - r.blocks = make(map[string]map[int32]*fetchRequestBlock) - } - - if r.blocks[topic] == nil { - r.blocks[topic] = make(map[int32]*fetchRequestBlock) - } - - tmp := new(fetchRequestBlock) - tmp.maxBytes = maxBytes - tmp.fetchOffset = fetchOffset - - r.blocks[topic][partitionID] = tmp -} diff --git a/vendor/github.com/Shopify/sarama/fetch_response.go b/vendor/github.com/Shopify/sarama/fetch_response.go deleted file mode 100644 index b56b166c2..000000000 --- a/vendor/github.com/Shopify/sarama/fetch_response.go +++ /dev/null @@ -1,210 +0,0 @@ -package sarama - -import "time" - -type FetchResponseBlock struct { - Err KError - HighWaterMarkOffset int64 - MsgSet MessageSet -} - -func (b *FetchResponseBlock) decode(pd packetDecoder) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - b.Err = KError(tmp) - - b.HighWaterMarkOffset, err = pd.getInt64() - if err != nil { - return err - } - - msgSetSize, err := pd.getInt32() - if err != nil { - return err - } - - msgSetDecoder, err := pd.getSubset(int(msgSetSize)) - if err != nil { - return err - } - err = (&b.MsgSet).decode(msgSetDecoder) - - return err -} - -func (b *FetchResponseBlock) encode(pe packetEncoder) (err error) { - pe.putInt16(int16(b.Err)) - - pe.putInt64(b.HighWaterMarkOffset) - - pe.push(&lengthField{}) - err = b.MsgSet.encode(pe) - if err != nil { - return err - } - return pe.pop() -} - -type FetchResponse struct { - Blocks map[string]map[int32]*FetchResponseBlock - ThrottleTime time.Duration - Version int16 // v1 requires 0.9+, v2 requires 0.10+ -} - -func (r *FetchResponse) decode(pd packetDecoder, version int16) (err error) { - r.Version = version - - if r.Version >= 1 { - throttle, err := pd.getInt32() - if err != nil { - return err - } - r.ThrottleTime = time.Duration(throttle) * time.Millisecond - } - - numTopics, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks = make(map[string]map[int32]*FetchResponseBlock, numTopics) - for i := 0; i < numTopics; i++ { - name, err := pd.getString() - if err != nil { - return err - } - - numBlocks, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks[name] = make(map[int32]*FetchResponseBlock, numBlocks) - - for j := 0; j < numBlocks; j++ { - id, err := pd.getInt32() - if err != nil { - return err - } - - block := new(FetchResponseBlock) - err = block.decode(pd) - if err != nil { - return err - } - r.Blocks[name][id] = block - } - } - - return nil -} - -func (r *FetchResponse) encode(pe packetEncoder) (err error) { - if r.Version >= 1 { - pe.putInt32(int32(r.ThrottleTime / time.Millisecond)) - } - - err = pe.putArrayLength(len(r.Blocks)) - if err != nil { - return err - } - - for topic, partitions := range r.Blocks { - err = pe.putString(topic) - if err != nil { - return err - } - - err = pe.putArrayLength(len(partitions)) - if err != nil { - return err - } - - for id, block := range partitions { - pe.putInt32(id) - err = block.encode(pe) - if err != nil { - return err - } - } - - } - return nil -} - -func (r *FetchResponse) key() int16 { - return 1 -} - -func (r *FetchResponse) version() int16 { - return r.Version -} - -func (r *FetchResponse) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_9_0_0 - case 2: - return V0_10_0_0 - default: - return minVersion - } -} - -func (r *FetchResponse) GetBlock(topic string, partition int32) *FetchResponseBlock { - if r.Blocks == nil { - return nil - } - - if r.Blocks[topic] == nil { - return nil - } - - return r.Blocks[topic][partition] -} - -func (r *FetchResponse) AddError(topic string, partition int32, err KError) { - if r.Blocks == nil { - r.Blocks = make(map[string]map[int32]*FetchResponseBlock) - } - partitions, ok := r.Blocks[topic] - if !ok { - partitions = make(map[int32]*FetchResponseBlock) - r.Blocks[topic] = partitions - } - frb, ok := partitions[partition] - if !ok { - frb = new(FetchResponseBlock) - partitions[partition] = frb - } - frb.Err = err -} - -func (r *FetchResponse) AddMessage(topic string, partition int32, key, value Encoder, offset int64) { - if r.Blocks == nil { - r.Blocks = make(map[string]map[int32]*FetchResponseBlock) - } - partitions, ok := r.Blocks[topic] - if !ok { - partitions = make(map[int32]*FetchResponseBlock) - r.Blocks[topic] = partitions - } - frb, ok := partitions[partition] - if !ok { - frb = new(FetchResponseBlock) - partitions[partition] = frb - } - var kb []byte - var vb []byte - if key != nil { - kb, _ = key.Encode() - } - if value != nil { - vb, _ = value.Encode() - } - msg := &Message{Key: kb, Value: vb} - msgBlock := &MessageBlock{Msg: msg, Offset: offset} - frb.MsgSet.Messages = append(frb.MsgSet.Messages, msgBlock) -} diff --git a/vendor/github.com/Shopify/sarama/heartbeat_request.go b/vendor/github.com/Shopify/sarama/heartbeat_request.go deleted file mode 100644 index ce49c4739..000000000 --- a/vendor/github.com/Shopify/sarama/heartbeat_request.go +++ /dev/null @@ -1,47 +0,0 @@ -package sarama - -type HeartbeatRequest struct { - GroupId string - GenerationId int32 - MemberId string -} - -func (r *HeartbeatRequest) encode(pe packetEncoder) error { - if err := pe.putString(r.GroupId); err != nil { - return err - } - - pe.putInt32(r.GenerationId) - - if err := pe.putString(r.MemberId); err != nil { - return err - } - - return nil -} - -func (r *HeartbeatRequest) decode(pd packetDecoder, version int16) (err error) { - if r.GroupId, err = pd.getString(); err != nil { - return - } - if r.GenerationId, err = pd.getInt32(); err != nil { - return - } - if r.MemberId, err = pd.getString(); err != nil { - return - } - - return nil -} - -func (r *HeartbeatRequest) key() int16 { - return 12 -} - -func (r *HeartbeatRequest) version() int16 { - return 0 -} - -func (r *HeartbeatRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/heartbeat_response.go b/vendor/github.com/Shopify/sarama/heartbeat_response.go deleted file mode 100644 index 766f5fdec..000000000 --- a/vendor/github.com/Shopify/sarama/heartbeat_response.go +++ /dev/null @@ -1,32 +0,0 @@ -package sarama - -type HeartbeatResponse struct { - Err KError -} - -func (r *HeartbeatResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - return nil -} - -func (r *HeartbeatResponse) decode(pd packetDecoder, version int16) error { - kerr, err := pd.getInt16() - if err != nil { - return err - } - r.Err = KError(kerr) - - return nil -} - -func (r *HeartbeatResponse) key() int16 { - return 12 -} - -func (r *HeartbeatResponse) version() int16 { - return 0 -} - -func (r *HeartbeatResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/join_group_request.go b/vendor/github.com/Shopify/sarama/join_group_request.go deleted file mode 100644 index 3a7ba1712..000000000 --- a/vendor/github.com/Shopify/sarama/join_group_request.go +++ /dev/null @@ -1,143 +0,0 @@ -package sarama - -type GroupProtocol struct { - Name string - Metadata []byte -} - -func (p *GroupProtocol) decode(pd packetDecoder) (err error) { - p.Name, err = pd.getString() - if err != nil { - return err - } - p.Metadata, err = pd.getBytes() - return err -} - -func (p *GroupProtocol) encode(pe packetEncoder) (err error) { - if err := pe.putString(p.Name); err != nil { - return err - } - if err := pe.putBytes(p.Metadata); err != nil { - return err - } - return nil -} - -type JoinGroupRequest struct { - GroupId string - SessionTimeout int32 - MemberId string - ProtocolType string - GroupProtocols map[string][]byte // deprecated; use OrderedGroupProtocols - OrderedGroupProtocols []*GroupProtocol -} - -func (r *JoinGroupRequest) encode(pe packetEncoder) error { - if err := pe.putString(r.GroupId); err != nil { - return err - } - pe.putInt32(r.SessionTimeout) - if err := pe.putString(r.MemberId); err != nil { - return err - } - if err := pe.putString(r.ProtocolType); err != nil { - return err - } - - if len(r.GroupProtocols) > 0 { - if len(r.OrderedGroupProtocols) > 0 { - return PacketDecodingError{"cannot specify both GroupProtocols and OrderedGroupProtocols on JoinGroupRequest"} - } - - if err := pe.putArrayLength(len(r.GroupProtocols)); err != nil { - return err - } - for name, metadata := range r.GroupProtocols { - if err := pe.putString(name); err != nil { - return err - } - if err := pe.putBytes(metadata); err != nil { - return err - } - } - } else { - if err := pe.putArrayLength(len(r.OrderedGroupProtocols)); err != nil { - return err - } - for _, protocol := range r.OrderedGroupProtocols { - if err := protocol.encode(pe); err != nil { - return err - } - } - } - - return nil -} - -func (r *JoinGroupRequest) decode(pd packetDecoder, version int16) (err error) { - if r.GroupId, err = pd.getString(); err != nil { - return - } - - if r.SessionTimeout, err = pd.getInt32(); err != nil { - return - } - - if r.MemberId, err = pd.getString(); err != nil { - return - } - - if r.ProtocolType, err = pd.getString(); err != nil { - return - } - - n, err := pd.getArrayLength() - if err != nil { - return err - } - if n == 0 { - return nil - } - - r.GroupProtocols = make(map[string][]byte) - for i := 0; i < n; i++ { - protocol := &GroupProtocol{} - if err := protocol.decode(pd); err != nil { - return err - } - r.GroupProtocols[protocol.Name] = protocol.Metadata - r.OrderedGroupProtocols = append(r.OrderedGroupProtocols, protocol) - } - - return nil -} - -func (r *JoinGroupRequest) key() int16 { - return 11 -} - -func (r *JoinGroupRequest) version() int16 { - return 0 -} - -func (r *JoinGroupRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} - -func (r *JoinGroupRequest) AddGroupProtocol(name string, metadata []byte) { - r.OrderedGroupProtocols = append(r.OrderedGroupProtocols, &GroupProtocol{ - Name: name, - Metadata: metadata, - }) -} - -func (r *JoinGroupRequest) AddGroupProtocolMetadata(name string, metadata *ConsumerGroupMemberMetadata) error { - bin, err := encode(metadata, nil) - if err != nil { - return err - } - - r.AddGroupProtocol(name, bin) - return nil -} diff --git a/vendor/github.com/Shopify/sarama/join_group_response.go b/vendor/github.com/Shopify/sarama/join_group_response.go deleted file mode 100644 index 6d35fe364..000000000 --- a/vendor/github.com/Shopify/sarama/join_group_response.go +++ /dev/null @@ -1,115 +0,0 @@ -package sarama - -type JoinGroupResponse struct { - Err KError - GenerationId int32 - GroupProtocol string - LeaderId string - MemberId string - Members map[string][]byte -} - -func (r *JoinGroupResponse) GetMembers() (map[string]ConsumerGroupMemberMetadata, error) { - members := make(map[string]ConsumerGroupMemberMetadata, len(r.Members)) - for id, bin := range r.Members { - meta := new(ConsumerGroupMemberMetadata) - if err := decode(bin, meta); err != nil { - return nil, err - } - members[id] = *meta - } - return members, nil -} - -func (r *JoinGroupResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - pe.putInt32(r.GenerationId) - - if err := pe.putString(r.GroupProtocol); err != nil { - return err - } - if err := pe.putString(r.LeaderId); err != nil { - return err - } - if err := pe.putString(r.MemberId); err != nil { - return err - } - - if err := pe.putArrayLength(len(r.Members)); err != nil { - return err - } - - for memberId, memberMetadata := range r.Members { - if err := pe.putString(memberId); err != nil { - return err - } - - if err := pe.putBytes(memberMetadata); err != nil { - return err - } - } - - return nil -} - -func (r *JoinGroupResponse) decode(pd packetDecoder, version int16) (err error) { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - r.Err = KError(kerr) - - if r.GenerationId, err = pd.getInt32(); err != nil { - return - } - - if r.GroupProtocol, err = pd.getString(); err != nil { - return - } - - if r.LeaderId, err = pd.getString(); err != nil { - return - } - - if r.MemberId, err = pd.getString(); err != nil { - return - } - - n, err := pd.getArrayLength() - if err != nil { - return err - } - if n == 0 { - return nil - } - - r.Members = make(map[string][]byte) - for i := 0; i < n; i++ { - memberId, err := pd.getString() - if err != nil { - return err - } - - memberMetadata, err := pd.getBytes() - if err != nil { - return err - } - - r.Members[memberId] = memberMetadata - } - - return nil -} - -func (r *JoinGroupResponse) key() int16 { - return 11 -} - -func (r *JoinGroupResponse) version() int16 { - return 0 -} - -func (r *JoinGroupResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/leave_group_request.go b/vendor/github.com/Shopify/sarama/leave_group_request.go deleted file mode 100644 index e17742748..000000000 --- a/vendor/github.com/Shopify/sarama/leave_group_request.go +++ /dev/null @@ -1,40 +0,0 @@ -package sarama - -type LeaveGroupRequest struct { - GroupId string - MemberId string -} - -func (r *LeaveGroupRequest) encode(pe packetEncoder) error { - if err := pe.putString(r.GroupId); err != nil { - return err - } - if err := pe.putString(r.MemberId); err != nil { - return err - } - - return nil -} - -func (r *LeaveGroupRequest) decode(pd packetDecoder, version int16) (err error) { - if r.GroupId, err = pd.getString(); err != nil { - return - } - if r.MemberId, err = pd.getString(); err != nil { - return - } - - return nil -} - -func (r *LeaveGroupRequest) key() int16 { - return 13 -} - -func (r *LeaveGroupRequest) version() int16 { - return 0 -} - -func (r *LeaveGroupRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/leave_group_response.go b/vendor/github.com/Shopify/sarama/leave_group_response.go deleted file mode 100644 index d60c626da..000000000 --- a/vendor/github.com/Shopify/sarama/leave_group_response.go +++ /dev/null @@ -1,32 +0,0 @@ -package sarama - -type LeaveGroupResponse struct { - Err KError -} - -func (r *LeaveGroupResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - return nil -} - -func (r *LeaveGroupResponse) decode(pd packetDecoder, version int16) (err error) { - kerr, err := pd.getInt16() - if err != nil { - return err - } - r.Err = KError(kerr) - - return nil -} - -func (r *LeaveGroupResponse) key() int16 { - return 13 -} - -func (r *LeaveGroupResponse) version() int16 { - return 0 -} - -func (r *LeaveGroupResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/length_field.go b/vendor/github.com/Shopify/sarama/length_field.go deleted file mode 100644 index 70078be5d..000000000 --- a/vendor/github.com/Shopify/sarama/length_field.go +++ /dev/null @@ -1,29 +0,0 @@ -package sarama - -import "encoding/binary" - -// LengthField implements the PushEncoder and PushDecoder interfaces for calculating 4-byte lengths. -type lengthField struct { - startOffset int -} - -func (l *lengthField) saveOffset(in int) { - l.startOffset = in -} - -func (l *lengthField) reserveLength() int { - return 4 -} - -func (l *lengthField) run(curOffset int, buf []byte) error { - binary.BigEndian.PutUint32(buf[l.startOffset:], uint32(curOffset-l.startOffset-4)) - return nil -} - -func (l *lengthField) check(curOffset int, buf []byte) error { - if uint32(curOffset-l.startOffset-4) != binary.BigEndian.Uint32(buf[l.startOffset:]) { - return PacketDecodingError{"length field invalid"} - } - - return nil -} diff --git a/vendor/github.com/Shopify/sarama/list_groups_request.go b/vendor/github.com/Shopify/sarama/list_groups_request.go deleted file mode 100644 index 3b16abf7f..000000000 --- a/vendor/github.com/Shopify/sarama/list_groups_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package sarama - -type ListGroupsRequest struct { -} - -func (r *ListGroupsRequest) encode(pe packetEncoder) error { - return nil -} - -func (r *ListGroupsRequest) decode(pd packetDecoder, version int16) (err error) { - return nil -} - -func (r *ListGroupsRequest) key() int16 { - return 16 -} - -func (r *ListGroupsRequest) version() int16 { - return 0 -} - -func (r *ListGroupsRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/list_groups_response.go b/vendor/github.com/Shopify/sarama/list_groups_response.go deleted file mode 100644 index 56115d4c7..000000000 --- a/vendor/github.com/Shopify/sarama/list_groups_response.go +++ /dev/null @@ -1,69 +0,0 @@ -package sarama - -type ListGroupsResponse struct { - Err KError - Groups map[string]string -} - -func (r *ListGroupsResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - - if err := pe.putArrayLength(len(r.Groups)); err != nil { - return err - } - for groupId, protocolType := range r.Groups { - if err := pe.putString(groupId); err != nil { - return err - } - if err := pe.putString(protocolType); err != nil { - return err - } - } - - return nil -} - -func (r *ListGroupsResponse) decode(pd packetDecoder, version int16) error { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - r.Err = KError(kerr) - - n, err := pd.getArrayLength() - if err != nil { - return err - } - if n == 0 { - return nil - } - - r.Groups = make(map[string]string) - for i := 0; i < n; i++ { - groupId, err := pd.getString() - if err != nil { - return err - } - protocolType, err := pd.getString() - if err != nil { - return err - } - - r.Groups[groupId] = protocolType - } - - return nil -} - -func (r *ListGroupsResponse) key() int16 { - return 16 -} - -func (r *ListGroupsResponse) version() int16 { - return 0 -} - -func (r *ListGroupsResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/message.go b/vendor/github.com/Shopify/sarama/message.go deleted file mode 100644 index 06f175f67..000000000 --- a/vendor/github.com/Shopify/sarama/message.go +++ /dev/null @@ -1,216 +0,0 @@ -package sarama - -import ( - "bytes" - "compress/gzip" - "fmt" - "io/ioutil" - "time" - - "github.com/eapache/go-xerial-snappy" - "github.com/pierrec/lz4" -) - -// CompressionCodec represents the various compression codecs recognized by Kafka in messages. -type CompressionCodec int8 - -// only the last two bits are really used -const compressionCodecMask int8 = 0x03 - -const ( - CompressionNone CompressionCodec = 0 - CompressionGZIP CompressionCodec = 1 - CompressionSnappy CompressionCodec = 2 - CompressionLZ4 CompressionCodec = 3 -) - -type Message struct { - Codec CompressionCodec // codec used to compress the message contents - Key []byte // the message key, may be nil - Value []byte // the message contents - Set *MessageSet // the message set a message might wrap - Version int8 // v1 requires Kafka 0.10 - Timestamp time.Time // the timestamp of the message (version 1+ only) - - compressedCache []byte - compressedSize int // used for computing the compression ratio metrics -} - -func (m *Message) encode(pe packetEncoder) error { - pe.push(&crc32Field{}) - - pe.putInt8(m.Version) - - attributes := int8(m.Codec) & compressionCodecMask - pe.putInt8(attributes) - - if m.Version >= 1 { - timestamp := int64(-1) - - if !m.Timestamp.Before(time.Unix(0, 0)) { - timestamp = m.Timestamp.UnixNano() / int64(time.Millisecond) - } else if !m.Timestamp.IsZero() { - return PacketEncodingError{fmt.Sprintf("invalid timestamp (%v)", m.Timestamp)} - } - - pe.putInt64(timestamp) - } - - err := pe.putBytes(m.Key) - if err != nil { - return err - } - - var payload []byte - - if m.compressedCache != nil { - payload = m.compressedCache - m.compressedCache = nil - } else if m.Value != nil { - switch m.Codec { - case CompressionNone: - payload = m.Value - case CompressionGZIP: - var buf bytes.Buffer - writer := gzip.NewWriter(&buf) - if _, err = writer.Write(m.Value); err != nil { - return err - } - if err = writer.Close(); err != nil { - return err - } - m.compressedCache = buf.Bytes() - payload = m.compressedCache - case CompressionSnappy: - tmp := snappy.Encode(m.Value) - m.compressedCache = tmp - payload = m.compressedCache - case CompressionLZ4: - var buf bytes.Buffer - writer := lz4.NewWriter(&buf) - if _, err = writer.Write(m.Value); err != nil { - return err - } - if err = writer.Close(); err != nil { - return err - } - m.compressedCache = buf.Bytes() - payload = m.compressedCache - - default: - return PacketEncodingError{fmt.Sprintf("unsupported compression codec (%d)", m.Codec)} - } - // Keep in mind the compressed payload size for metric gathering - m.compressedSize = len(payload) - } - - if err = pe.putBytes(payload); err != nil { - return err - } - - return pe.pop() -} - -func (m *Message) decode(pd packetDecoder) (err error) { - err = pd.push(&crc32Field{}) - if err != nil { - return err - } - - m.Version, err = pd.getInt8() - if err != nil { - return err - } - - if m.Version > 1 { - return PacketDecodingError{fmt.Sprintf("unknown magic byte (%v)", m.Version)} - } - - attribute, err := pd.getInt8() - if err != nil { - return err - } - m.Codec = CompressionCodec(attribute & compressionCodecMask) - - if m.Version == 1 { - millis, err := pd.getInt64() - if err != nil { - return err - } - - // negative timestamps are invalid, in these cases we should return - // a zero time - timestamp := time.Time{} - if millis >= 0 { - timestamp = time.Unix(millis/1000, (millis%1000)*int64(time.Millisecond)) - } - - m.Timestamp = timestamp - } - - m.Key, err = pd.getBytes() - if err != nil { - return err - } - - m.Value, err = pd.getBytes() - if err != nil { - return err - } - - // Required for deep equal assertion during tests but might be useful - // for future metrics about the compression ratio in fetch requests - m.compressedSize = len(m.Value) - - switch m.Codec { - case CompressionNone: - // nothing to do - case CompressionGZIP: - if m.Value == nil { - break - } - reader, err := gzip.NewReader(bytes.NewReader(m.Value)) - if err != nil { - return err - } - if m.Value, err = ioutil.ReadAll(reader); err != nil { - return err - } - if err := m.decodeSet(); err != nil { - return err - } - case CompressionSnappy: - if m.Value == nil { - break - } - if m.Value, err = snappy.Decode(m.Value); err != nil { - return err - } - if err := m.decodeSet(); err != nil { - return err - } - case CompressionLZ4: - if m.Value == nil { - break - } - reader := lz4.NewReader(bytes.NewReader(m.Value)) - if m.Value, err = ioutil.ReadAll(reader); err != nil { - return err - } - if err := m.decodeSet(); err != nil { - return err - } - - default: - return PacketDecodingError{fmt.Sprintf("invalid compression specified (%d)", m.Codec)} - } - - return pd.pop() -} - -// decodes a message set from a previousy encoded bulk-message -func (m *Message) decodeSet() (err error) { - pd := realDecoder{raw: m.Value} - m.Set = &MessageSet{} - return m.Set.decode(&pd) -} diff --git a/vendor/github.com/Shopify/sarama/message_set.go b/vendor/github.com/Shopify/sarama/message_set.go deleted file mode 100644 index f028784e5..000000000 --- a/vendor/github.com/Shopify/sarama/message_set.go +++ /dev/null @@ -1,89 +0,0 @@ -package sarama - -type MessageBlock struct { - Offset int64 - Msg *Message -} - -// Messages convenience helper which returns either all the -// messages that are wrapped in this block -func (msb *MessageBlock) Messages() []*MessageBlock { - if msb.Msg.Set != nil { - return msb.Msg.Set.Messages - } - return []*MessageBlock{msb} -} - -func (msb *MessageBlock) encode(pe packetEncoder) error { - pe.putInt64(msb.Offset) - pe.push(&lengthField{}) - err := msb.Msg.encode(pe) - if err != nil { - return err - } - return pe.pop() -} - -func (msb *MessageBlock) decode(pd packetDecoder) (err error) { - if msb.Offset, err = pd.getInt64(); err != nil { - return err - } - - if err = pd.push(&lengthField{}); err != nil { - return err - } - - msb.Msg = new(Message) - if err = msb.Msg.decode(pd); err != nil { - return err - } - - if err = pd.pop(); err != nil { - return err - } - - return nil -} - -type MessageSet struct { - PartialTrailingMessage bool // whether the set on the wire contained an incomplete trailing MessageBlock - Messages []*MessageBlock -} - -func (ms *MessageSet) encode(pe packetEncoder) error { - for i := range ms.Messages { - err := ms.Messages[i].encode(pe) - if err != nil { - return err - } - } - return nil -} - -func (ms *MessageSet) decode(pd packetDecoder) (err error) { - ms.Messages = nil - - for pd.remaining() > 0 { - msb := new(MessageBlock) - err = msb.decode(pd) - switch err { - case nil: - ms.Messages = append(ms.Messages, msb) - case ErrInsufficientData: - // As an optimization the server is allowed to return a partial message at the - // end of the message set. Clients should handle this case. So we just ignore such things. - ms.PartialTrailingMessage = true - return nil - default: - return err - } - } - - return nil -} - -func (ms *MessageSet) addMessage(msg *Message) { - block := new(MessageBlock) - block.Msg = msg - ms.Messages = append(ms.Messages, block) -} diff --git a/vendor/github.com/Shopify/sarama/metadata_request.go b/vendor/github.com/Shopify/sarama/metadata_request.go deleted file mode 100644 index 9a26b55fd..000000000 --- a/vendor/github.com/Shopify/sarama/metadata_request.go +++ /dev/null @@ -1,52 +0,0 @@ -package sarama - -type MetadataRequest struct { - Topics []string -} - -func (r *MetadataRequest) encode(pe packetEncoder) error { - err := pe.putArrayLength(len(r.Topics)) - if err != nil { - return err - } - - for i := range r.Topics { - err = pe.putString(r.Topics[i]) - if err != nil { - return err - } - } - return nil -} - -func (r *MetadataRequest) decode(pd packetDecoder, version int16) error { - topicCount, err := pd.getArrayLength() - if err != nil { - return err - } - if topicCount == 0 { - return nil - } - - r.Topics = make([]string, topicCount) - for i := range r.Topics { - topic, err := pd.getString() - if err != nil { - return err - } - r.Topics[i] = topic - } - return nil -} - -func (r *MetadataRequest) key() int16 { - return 3 -} - -func (r *MetadataRequest) version() int16 { - return 0 -} - -func (r *MetadataRequest) requiredVersion() KafkaVersion { - return minVersion -} diff --git a/vendor/github.com/Shopify/sarama/metadata_response.go b/vendor/github.com/Shopify/sarama/metadata_response.go deleted file mode 100644 index f9d6a4271..000000000 --- a/vendor/github.com/Shopify/sarama/metadata_response.go +++ /dev/null @@ -1,239 +0,0 @@ -package sarama - -type PartitionMetadata struct { - Err KError - ID int32 - Leader int32 - Replicas []int32 - Isr []int32 -} - -func (pm *PartitionMetadata) decode(pd packetDecoder) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - pm.Err = KError(tmp) - - pm.ID, err = pd.getInt32() - if err != nil { - return err - } - - pm.Leader, err = pd.getInt32() - if err != nil { - return err - } - - pm.Replicas, err = pd.getInt32Array() - if err != nil { - return err - } - - pm.Isr, err = pd.getInt32Array() - if err != nil { - return err - } - - return nil -} - -func (pm *PartitionMetadata) encode(pe packetEncoder) (err error) { - pe.putInt16(int16(pm.Err)) - pe.putInt32(pm.ID) - pe.putInt32(pm.Leader) - - err = pe.putInt32Array(pm.Replicas) - if err != nil { - return err - } - - err = pe.putInt32Array(pm.Isr) - if err != nil { - return err - } - - return nil -} - -type TopicMetadata struct { - Err KError - Name string - Partitions []*PartitionMetadata -} - -func (tm *TopicMetadata) decode(pd packetDecoder) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - tm.Err = KError(tmp) - - tm.Name, err = pd.getString() - if err != nil { - return err - } - - n, err := pd.getArrayLength() - if err != nil { - return err - } - tm.Partitions = make([]*PartitionMetadata, n) - for i := 0; i < n; i++ { - tm.Partitions[i] = new(PartitionMetadata) - err = tm.Partitions[i].decode(pd) - if err != nil { - return err - } - } - - return nil -} - -func (tm *TopicMetadata) encode(pe packetEncoder) (err error) { - pe.putInt16(int16(tm.Err)) - - err = pe.putString(tm.Name) - if err != nil { - return err - } - - err = pe.putArrayLength(len(tm.Partitions)) - if err != nil { - return err - } - - for _, pm := range tm.Partitions { - err = pm.encode(pe) - if err != nil { - return err - } - } - - return nil -} - -type MetadataResponse struct { - Brokers []*Broker - Topics []*TopicMetadata -} - -func (r *MetadataResponse) decode(pd packetDecoder, version int16) (err error) { - n, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Brokers = make([]*Broker, n) - for i := 0; i < n; i++ { - r.Brokers[i] = new(Broker) - err = r.Brokers[i].decode(pd) - if err != nil { - return err - } - } - - n, err = pd.getArrayLength() - if err != nil { - return err - } - - r.Topics = make([]*TopicMetadata, n) - for i := 0; i < n; i++ { - r.Topics[i] = new(TopicMetadata) - err = r.Topics[i].decode(pd) - if err != nil { - return err - } - } - - return nil -} - -func (r *MetadataResponse) encode(pe packetEncoder) error { - err := pe.putArrayLength(len(r.Brokers)) - if err != nil { - return err - } - for _, broker := range r.Brokers { - err = broker.encode(pe) - if err != nil { - return err - } - } - - err = pe.putArrayLength(len(r.Topics)) - if err != nil { - return err - } - for _, tm := range r.Topics { - err = tm.encode(pe) - if err != nil { - return err - } - } - - return nil -} - -func (r *MetadataResponse) key() int16 { - return 3 -} - -func (r *MetadataResponse) version() int16 { - return 0 -} - -func (r *MetadataResponse) requiredVersion() KafkaVersion { - return minVersion -} - -// testing API - -func (r *MetadataResponse) AddBroker(addr string, id int32) { - r.Brokers = append(r.Brokers, &Broker{id: id, addr: addr}) -} - -func (r *MetadataResponse) AddTopic(topic string, err KError) *TopicMetadata { - var tmatch *TopicMetadata - - for _, tm := range r.Topics { - if tm.Name == topic { - tmatch = tm - goto foundTopic - } - } - - tmatch = new(TopicMetadata) - tmatch.Name = topic - r.Topics = append(r.Topics, tmatch) - -foundTopic: - - tmatch.Err = err - return tmatch -} - -func (r *MetadataResponse) AddTopicPartition(topic string, partition, brokerID int32, replicas, isr []int32, err KError) { - tmatch := r.AddTopic(topic, ErrNoError) - var pmatch *PartitionMetadata - - for _, pm := range tmatch.Partitions { - if pm.ID == partition { - pmatch = pm - goto foundPartition - } - } - - pmatch = new(PartitionMetadata) - pmatch.ID = partition - tmatch.Partitions = append(tmatch.Partitions, pmatch) - -foundPartition: - - pmatch.Leader = brokerID - pmatch.Replicas = replicas - pmatch.Isr = isr - pmatch.Err = err - -} diff --git a/vendor/github.com/Shopify/sarama/metrics.go b/vendor/github.com/Shopify/sarama/metrics.go deleted file mode 100644 index 4869708e9..000000000 --- a/vendor/github.com/Shopify/sarama/metrics.go +++ /dev/null @@ -1,51 +0,0 @@ -package sarama - -import ( - "fmt" - "strings" - - "github.com/rcrowley/go-metrics" -) - -// Use exponentially decaying reservoir for sampling histograms with the same defaults as the Java library: -// 1028 elements, which offers a 99.9% confidence level with a 5% margin of error assuming a normal distribution, -// and an alpha factor of 0.015, which heavily biases the reservoir to the past 5 minutes of measurements. -// See https://github.com/dropwizard/metrics/blob/v3.1.0/metrics-core/src/main/java/com/codahale/metrics/ExponentiallyDecayingReservoir.java#L38 -const ( - metricsReservoirSize = 1028 - metricsAlphaFactor = 0.015 -) - -func getOrRegisterHistogram(name string, r metrics.Registry) metrics.Histogram { - return r.GetOrRegister(name, func() metrics.Histogram { - return metrics.NewHistogram(metrics.NewExpDecaySample(metricsReservoirSize, metricsAlphaFactor)) - }).(metrics.Histogram) -} - -func getMetricNameForBroker(name string, broker *Broker) string { - // Use broker id like the Java client as it does not contain '.' or ':' characters that - // can be interpreted as special character by monitoring tool (e.g. Graphite) - return fmt.Sprintf(name+"-for-broker-%d", broker.ID()) -} - -func getOrRegisterBrokerMeter(name string, broker *Broker, r metrics.Registry) metrics.Meter { - return metrics.GetOrRegisterMeter(getMetricNameForBroker(name, broker), r) -} - -func getOrRegisterBrokerHistogram(name string, broker *Broker, r metrics.Registry) metrics.Histogram { - return getOrRegisterHistogram(getMetricNameForBroker(name, broker), r) -} - -func getMetricNameForTopic(name string, topic string) string { - // Convert dot to _ since reporters like Graphite typically use dot to represent hierarchy - // cf. KAFKA-1902 and KAFKA-2337 - return fmt.Sprintf(name+"-for-topic-%s", strings.Replace(topic, ".", "_", -1)) -} - -func getOrRegisterTopicMeter(name string, topic string, r metrics.Registry) metrics.Meter { - return metrics.GetOrRegisterMeter(getMetricNameForTopic(name, topic), r) -} - -func getOrRegisterTopicHistogram(name string, topic string, r metrics.Registry) metrics.Histogram { - return getOrRegisterHistogram(getMetricNameForTopic(name, topic), r) -} diff --git a/vendor/github.com/Shopify/sarama/mockbroker.go b/vendor/github.com/Shopify/sarama/mockbroker.go deleted file mode 100644 index 0734d34f6..000000000 --- a/vendor/github.com/Shopify/sarama/mockbroker.go +++ /dev/null @@ -1,324 +0,0 @@ -package sarama - -import ( - "bytes" - "encoding/binary" - "fmt" - "io" - "net" - "reflect" - "strconv" - "sync" - "time" - - "github.com/davecgh/go-spew/spew" -) - -const ( - expectationTimeout = 500 * time.Millisecond -) - -type requestHandlerFunc func(req *request) (res encoder) - -// RequestNotifierFunc is invoked when a mock broker processes a request successfully -// and will provides the number of bytes read and written. -type RequestNotifierFunc func(bytesRead, bytesWritten int) - -// MockBroker is a mock Kafka broker that is used in unit tests. It is exposed -// to facilitate testing of higher level or specialized consumers and producers -// built on top of Sarama. Note that it does not 'mimic' the Kafka API protocol, -// but rather provides a facility to do that. It takes care of the TCP -// transport, request unmarshaling, response marshaling, and makes it the test -// writer responsibility to program correct according to the Kafka API protocol -// MockBroker behaviour. -// -// MockBroker is implemented as a TCP server listening on a kernel-selected -// localhost port that can accept many connections. It reads Kafka requests -// from that connection and returns responses programmed by the SetHandlerByMap -// function. If a MockBroker receives a request that it has no programmed -// response for, then it returns nothing and the request times out. -// -// A set of MockRequest builders to define mappings used by MockBroker is -// provided by Sarama. But users can develop MockRequests of their own and use -// them along with or instead of the standard ones. -// -// When running tests with MockBroker it is strongly recommended to specify -// a timeout to `go test` so that if the broker hangs waiting for a response, -// the test panics. -// -// It is not necessary to prefix message length or correlation ID to your -// response bytes, the server does that automatically as a convenience. -type MockBroker struct { - brokerID int32 - port int32 - closing chan none - stopper chan none - expectations chan encoder - listener net.Listener - t TestReporter - latency time.Duration - handler requestHandlerFunc - notifier RequestNotifierFunc - history []RequestResponse - lock sync.Mutex -} - -// RequestResponse represents a Request/Response pair processed by MockBroker. -type RequestResponse struct { - Request protocolBody - Response encoder -} - -// SetLatency makes broker pause for the specified period every time before -// replying. -func (b *MockBroker) SetLatency(latency time.Duration) { - b.latency = latency -} - -// SetHandlerByMap defines mapping of Request types to MockResponses. When a -// request is received by the broker, it looks up the request type in the map -// and uses the found MockResponse instance to generate an appropriate reply. -// If the request type is not found in the map then nothing is sent. -func (b *MockBroker) SetHandlerByMap(handlerMap map[string]MockResponse) { - b.setHandler(func(req *request) (res encoder) { - reqTypeName := reflect.TypeOf(req.body).Elem().Name() - mockResponse := handlerMap[reqTypeName] - if mockResponse == nil { - return nil - } - return mockResponse.For(req.body) - }) -} - -// SetNotifier set a function that will get invoked whenever a request has been -// processed successfully and will provide the number of bytes read and written -func (b *MockBroker) SetNotifier(notifier RequestNotifierFunc) { - b.lock.Lock() - b.notifier = notifier - b.lock.Unlock() -} - -// BrokerID returns broker ID assigned to the broker. -func (b *MockBroker) BrokerID() int32 { - return b.brokerID -} - -// History returns a slice of RequestResponse pairs in the order they were -// processed by the broker. Note that in case of multiple connections to the -// broker the order expected by a test can be different from the order recorded -// in the history, unless some synchronization is implemented in the test. -func (b *MockBroker) History() []RequestResponse { - b.lock.Lock() - history := make([]RequestResponse, len(b.history)) - copy(history, b.history) - b.lock.Unlock() - return history -} - -// Port returns the TCP port number the broker is listening for requests on. -func (b *MockBroker) Port() int32 { - return b.port -} - -// Addr returns the broker connection string in the form "
:". -func (b *MockBroker) Addr() string { - return b.listener.Addr().String() -} - -// Close terminates the broker blocking until it stops internal goroutines and -// releases all resources. -func (b *MockBroker) Close() { - close(b.expectations) - if len(b.expectations) > 0 { - buf := bytes.NewBufferString(fmt.Sprintf("mockbroker/%d: not all expectations were satisfied! Still waiting on:\n", b.BrokerID())) - for e := range b.expectations { - _, _ = buf.WriteString(spew.Sdump(e)) - } - b.t.Error(buf.String()) - } - close(b.closing) - <-b.stopper -} - -// setHandler sets the specified function as the request handler. Whenever -// a mock broker reads a request from the wire it passes the request to the -// function and sends back whatever the handler function returns. -func (b *MockBroker) setHandler(handler requestHandlerFunc) { - b.lock.Lock() - b.handler = handler - b.lock.Unlock() -} - -func (b *MockBroker) serverLoop() { - defer close(b.stopper) - var err error - var conn net.Conn - - go func() { - <-b.closing - err := b.listener.Close() - if err != nil { - b.t.Error(err) - } - }() - - wg := &sync.WaitGroup{} - i := 0 - for conn, err = b.listener.Accept(); err == nil; conn, err = b.listener.Accept() { - wg.Add(1) - go b.handleRequests(conn, i, wg) - i++ - } - wg.Wait() - Logger.Printf("*** mockbroker/%d: listener closed, err=%v", b.BrokerID(), err) -} - -func (b *MockBroker) handleRequests(conn net.Conn, idx int, wg *sync.WaitGroup) { - defer wg.Done() - defer func() { - _ = conn.Close() - }() - Logger.Printf("*** mockbroker/%d/%d: connection opened", b.BrokerID(), idx) - var err error - - abort := make(chan none) - defer close(abort) - go func() { - select { - case <-b.closing: - _ = conn.Close() - case <-abort: - } - }() - - resHeader := make([]byte, 8) - for { - req, bytesRead, err := decodeRequest(conn) - if err != nil { - Logger.Printf("*** mockbroker/%d/%d: invalid request: err=%+v, %+v", b.brokerID, idx, err, spew.Sdump(req)) - b.serverError(err) - break - } - - if b.latency > 0 { - time.Sleep(b.latency) - } - - b.lock.Lock() - res := b.handler(req) - b.history = append(b.history, RequestResponse{req.body, res}) - b.lock.Unlock() - - if res == nil { - Logger.Printf("*** mockbroker/%d/%d: ignored %v", b.brokerID, idx, spew.Sdump(req)) - continue - } - Logger.Printf("*** mockbroker/%d/%d: served %v -> %v", b.brokerID, idx, req, res) - - encodedRes, err := encode(res, nil) - if err != nil { - b.serverError(err) - break - } - if len(encodedRes) == 0 { - b.lock.Lock() - if b.notifier != nil { - b.notifier(bytesRead, 0) - } - b.lock.Unlock() - continue - } - - binary.BigEndian.PutUint32(resHeader, uint32(len(encodedRes)+4)) - binary.BigEndian.PutUint32(resHeader[4:], uint32(req.correlationID)) - if _, err = conn.Write(resHeader); err != nil { - b.serverError(err) - break - } - if _, err = conn.Write(encodedRes); err != nil { - b.serverError(err) - break - } - - b.lock.Lock() - if b.notifier != nil { - b.notifier(bytesRead, len(resHeader)+len(encodedRes)) - } - b.lock.Unlock() - } - Logger.Printf("*** mockbroker/%d/%d: connection closed, err=%v", b.BrokerID(), idx, err) -} - -func (b *MockBroker) defaultRequestHandler(req *request) (res encoder) { - select { - case res, ok := <-b.expectations: - if !ok { - return nil - } - return res - case <-time.After(expectationTimeout): - return nil - } -} - -func (b *MockBroker) serverError(err error) { - isConnectionClosedError := false - if _, ok := err.(*net.OpError); ok { - isConnectionClosedError = true - } else if err == io.EOF { - isConnectionClosedError = true - } else if err.Error() == "use of closed network connection" { - isConnectionClosedError = true - } - - if isConnectionClosedError { - return - } - - b.t.Errorf(err.Error()) -} - -// NewMockBroker launches a fake Kafka broker. It takes a TestReporter as provided by the -// test framework and a channel of responses to use. If an error occurs it is -// simply logged to the TestReporter and the broker exits. -func NewMockBroker(t TestReporter, brokerID int32) *MockBroker { - return NewMockBrokerAddr(t, brokerID, "localhost:0") -} - -// NewMockBrokerAddr behaves like newMockBroker but listens on the address you give -// it rather than just some ephemeral port. -func NewMockBrokerAddr(t TestReporter, brokerID int32, addr string) *MockBroker { - var err error - - broker := &MockBroker{ - closing: make(chan none), - stopper: make(chan none), - t: t, - brokerID: brokerID, - expectations: make(chan encoder, 512), - } - broker.handler = broker.defaultRequestHandler - - broker.listener, err = net.Listen("tcp", addr) - if err != nil { - t.Fatal(err) - } - Logger.Printf("*** mockbroker/%d listening on %s\n", brokerID, broker.listener.Addr().String()) - _, portStr, err := net.SplitHostPort(broker.listener.Addr().String()) - if err != nil { - t.Fatal(err) - } - tmp, err := strconv.ParseInt(portStr, 10, 32) - if err != nil { - t.Fatal(err) - } - broker.port = int32(tmp) - - go broker.serverLoop() - - return broker -} - -func (b *MockBroker) Returns(e encoder) { - b.expectations <- e -} diff --git a/vendor/github.com/Shopify/sarama/mockresponses.go b/vendor/github.com/Shopify/sarama/mockresponses.go deleted file mode 100644 index d94bd24c6..000000000 --- a/vendor/github.com/Shopify/sarama/mockresponses.go +++ /dev/null @@ -1,463 +0,0 @@ -package sarama - -import ( - "fmt" -) - -// TestReporter has methods matching go's testing.T to avoid importing -// `testing` in the main part of the library. -type TestReporter interface { - Error(...interface{}) - Errorf(string, ...interface{}) - Fatal(...interface{}) - Fatalf(string, ...interface{}) -} - -// MockResponse is a response builder interface it defines one method that -// allows generating a response based on a request body. MockResponses are used -// to program behavior of MockBroker in tests. -type MockResponse interface { - For(reqBody versionedDecoder) (res encoder) -} - -// MockWrapper is a mock response builder that returns a particular concrete -// response regardless of the actual request passed to the `For` method. -type MockWrapper struct { - res encoder -} - -func (mw *MockWrapper) For(reqBody versionedDecoder) (res encoder) { - return mw.res -} - -func NewMockWrapper(res encoder) *MockWrapper { - return &MockWrapper{res: res} -} - -// MockSequence is a mock response builder that is created from a sequence of -// concrete responses. Every time when a `MockBroker` calls its `For` method -// the next response from the sequence is returned. When the end of the -// sequence is reached the last element from the sequence is returned. -type MockSequence struct { - responses []MockResponse -} - -func NewMockSequence(responses ...interface{}) *MockSequence { - ms := &MockSequence{} - ms.responses = make([]MockResponse, len(responses)) - for i, res := range responses { - switch res := res.(type) { - case MockResponse: - ms.responses[i] = res - case encoder: - ms.responses[i] = NewMockWrapper(res) - default: - panic(fmt.Sprintf("Unexpected response type: %T", res)) - } - } - return ms -} - -func (mc *MockSequence) For(reqBody versionedDecoder) (res encoder) { - res = mc.responses[0].For(reqBody) - if len(mc.responses) > 1 { - mc.responses = mc.responses[1:] - } - return res -} - -// MockMetadataResponse is a `MetadataResponse` builder. -type MockMetadataResponse struct { - leaders map[string]map[int32]int32 - brokers map[string]int32 - t TestReporter -} - -func NewMockMetadataResponse(t TestReporter) *MockMetadataResponse { - return &MockMetadataResponse{ - leaders: make(map[string]map[int32]int32), - brokers: make(map[string]int32), - t: t, - } -} - -func (mmr *MockMetadataResponse) SetLeader(topic string, partition, brokerID int32) *MockMetadataResponse { - partitions := mmr.leaders[topic] - if partitions == nil { - partitions = make(map[int32]int32) - mmr.leaders[topic] = partitions - } - partitions[partition] = brokerID - return mmr -} - -func (mmr *MockMetadataResponse) SetBroker(addr string, brokerID int32) *MockMetadataResponse { - mmr.brokers[addr] = brokerID - return mmr -} - -func (mmr *MockMetadataResponse) For(reqBody versionedDecoder) encoder { - metadataRequest := reqBody.(*MetadataRequest) - metadataResponse := &MetadataResponse{} - for addr, brokerID := range mmr.brokers { - metadataResponse.AddBroker(addr, brokerID) - } - if len(metadataRequest.Topics) == 0 { - for topic, partitions := range mmr.leaders { - for partition, brokerID := range partitions { - metadataResponse.AddTopicPartition(topic, partition, brokerID, nil, nil, ErrNoError) - } - } - return metadataResponse - } - for _, topic := range metadataRequest.Topics { - for partition, brokerID := range mmr.leaders[topic] { - metadataResponse.AddTopicPartition(topic, partition, brokerID, nil, nil, ErrNoError) - } - } - return metadataResponse -} - -// MockOffsetResponse is an `OffsetResponse` builder. -type MockOffsetResponse struct { - offsets map[string]map[int32]map[int64]int64 - t TestReporter -} - -func NewMockOffsetResponse(t TestReporter) *MockOffsetResponse { - return &MockOffsetResponse{ - offsets: make(map[string]map[int32]map[int64]int64), - t: t, - } -} - -func (mor *MockOffsetResponse) SetOffset(topic string, partition int32, time, offset int64) *MockOffsetResponse { - partitions := mor.offsets[topic] - if partitions == nil { - partitions = make(map[int32]map[int64]int64) - mor.offsets[topic] = partitions - } - times := partitions[partition] - if times == nil { - times = make(map[int64]int64) - partitions[partition] = times - } - times[time] = offset - return mor -} - -func (mor *MockOffsetResponse) For(reqBody versionedDecoder) encoder { - offsetRequest := reqBody.(*OffsetRequest) - offsetResponse := &OffsetResponse{} - for topic, partitions := range offsetRequest.blocks { - for partition, block := range partitions { - offset := mor.getOffset(topic, partition, block.time) - offsetResponse.AddTopicPartition(topic, partition, offset) - } - } - return offsetResponse -} - -func (mor *MockOffsetResponse) getOffset(topic string, partition int32, time int64) int64 { - partitions := mor.offsets[topic] - if partitions == nil { - mor.t.Errorf("missing topic: %s", topic) - } - times := partitions[partition] - if times == nil { - mor.t.Errorf("missing partition: %d", partition) - } - offset, ok := times[time] - if !ok { - mor.t.Errorf("missing time: %d", time) - } - return offset -} - -// MockFetchResponse is a `FetchResponse` builder. -type MockFetchResponse struct { - messages map[string]map[int32]map[int64]Encoder - highWaterMarks map[string]map[int32]int64 - t TestReporter - batchSize int - version int16 -} - -func NewMockFetchResponse(t TestReporter, batchSize int) *MockFetchResponse { - return &MockFetchResponse{ - messages: make(map[string]map[int32]map[int64]Encoder), - highWaterMarks: make(map[string]map[int32]int64), - t: t, - batchSize: batchSize, - } -} - -func (mfr *MockFetchResponse) SetVersion(version int16) *MockFetchResponse { - mfr.version = version - return mfr -} - -func (mfr *MockFetchResponse) SetMessage(topic string, partition int32, offset int64, msg Encoder) *MockFetchResponse { - partitions := mfr.messages[topic] - if partitions == nil { - partitions = make(map[int32]map[int64]Encoder) - mfr.messages[topic] = partitions - } - messages := partitions[partition] - if messages == nil { - messages = make(map[int64]Encoder) - partitions[partition] = messages - } - messages[offset] = msg - return mfr -} - -func (mfr *MockFetchResponse) SetHighWaterMark(topic string, partition int32, offset int64) *MockFetchResponse { - partitions := mfr.highWaterMarks[topic] - if partitions == nil { - partitions = make(map[int32]int64) - mfr.highWaterMarks[topic] = partitions - } - partitions[partition] = offset - return mfr -} - -func (mfr *MockFetchResponse) For(reqBody versionedDecoder) encoder { - fetchRequest := reqBody.(*FetchRequest) - res := &FetchResponse{ - Version: mfr.version, - } - for topic, partitions := range fetchRequest.blocks { - for partition, block := range partitions { - initialOffset := block.fetchOffset - offset := initialOffset - maxOffset := initialOffset + int64(mfr.getMessageCount(topic, partition)) - for i := 0; i < mfr.batchSize && offset < maxOffset; { - msg := mfr.getMessage(topic, partition, offset) - if msg != nil { - res.AddMessage(topic, partition, nil, msg, offset) - i++ - } - offset++ - } - fb := res.GetBlock(topic, partition) - if fb == nil { - res.AddError(topic, partition, ErrNoError) - fb = res.GetBlock(topic, partition) - } - fb.HighWaterMarkOffset = mfr.getHighWaterMark(topic, partition) - } - } - return res -} - -func (mfr *MockFetchResponse) getMessage(topic string, partition int32, offset int64) Encoder { - partitions := mfr.messages[topic] - if partitions == nil { - return nil - } - messages := partitions[partition] - if messages == nil { - return nil - } - return messages[offset] -} - -func (mfr *MockFetchResponse) getMessageCount(topic string, partition int32) int { - partitions := mfr.messages[topic] - if partitions == nil { - return 0 - } - messages := partitions[partition] - if messages == nil { - return 0 - } - return len(messages) -} - -func (mfr *MockFetchResponse) getHighWaterMark(topic string, partition int32) int64 { - partitions := mfr.highWaterMarks[topic] - if partitions == nil { - return 0 - } - return partitions[partition] -} - -// MockConsumerMetadataResponse is a `ConsumerMetadataResponse` builder. -type MockConsumerMetadataResponse struct { - coordinators map[string]interface{} - t TestReporter -} - -func NewMockConsumerMetadataResponse(t TestReporter) *MockConsumerMetadataResponse { - return &MockConsumerMetadataResponse{ - coordinators: make(map[string]interface{}), - t: t, - } -} - -func (mr *MockConsumerMetadataResponse) SetCoordinator(group string, broker *MockBroker) *MockConsumerMetadataResponse { - mr.coordinators[group] = broker - return mr -} - -func (mr *MockConsumerMetadataResponse) SetError(group string, kerror KError) *MockConsumerMetadataResponse { - mr.coordinators[group] = kerror - return mr -} - -func (mr *MockConsumerMetadataResponse) For(reqBody versionedDecoder) encoder { - req := reqBody.(*ConsumerMetadataRequest) - group := req.ConsumerGroup - res := &ConsumerMetadataResponse{} - v := mr.coordinators[group] - switch v := v.(type) { - case *MockBroker: - res.Coordinator = &Broker{id: v.BrokerID(), addr: v.Addr()} - case KError: - res.Err = v - } - return res -} - -// MockOffsetCommitResponse is a `OffsetCommitResponse` builder. -type MockOffsetCommitResponse struct { - errors map[string]map[string]map[int32]KError - t TestReporter -} - -func NewMockOffsetCommitResponse(t TestReporter) *MockOffsetCommitResponse { - return &MockOffsetCommitResponse{t: t} -} - -func (mr *MockOffsetCommitResponse) SetError(group, topic string, partition int32, kerror KError) *MockOffsetCommitResponse { - if mr.errors == nil { - mr.errors = make(map[string]map[string]map[int32]KError) - } - topics := mr.errors[group] - if topics == nil { - topics = make(map[string]map[int32]KError) - mr.errors[group] = topics - } - partitions := topics[topic] - if partitions == nil { - partitions = make(map[int32]KError) - topics[topic] = partitions - } - partitions[partition] = kerror - return mr -} - -func (mr *MockOffsetCommitResponse) For(reqBody versionedDecoder) encoder { - req := reqBody.(*OffsetCommitRequest) - group := req.ConsumerGroup - res := &OffsetCommitResponse{} - for topic, partitions := range req.blocks { - for partition := range partitions { - res.AddError(topic, partition, mr.getError(group, topic, partition)) - } - } - return res -} - -func (mr *MockOffsetCommitResponse) getError(group, topic string, partition int32) KError { - topics := mr.errors[group] - if topics == nil { - return ErrNoError - } - partitions := topics[topic] - if partitions == nil { - return ErrNoError - } - kerror, ok := partitions[partition] - if !ok { - return ErrNoError - } - return kerror -} - -// MockProduceResponse is a `ProduceResponse` builder. -type MockProduceResponse struct { - errors map[string]map[int32]KError - t TestReporter -} - -func NewMockProduceResponse(t TestReporter) *MockProduceResponse { - return &MockProduceResponse{t: t} -} - -func (mr *MockProduceResponse) SetError(topic string, partition int32, kerror KError) *MockProduceResponse { - if mr.errors == nil { - mr.errors = make(map[string]map[int32]KError) - } - partitions := mr.errors[topic] - if partitions == nil { - partitions = make(map[int32]KError) - mr.errors[topic] = partitions - } - partitions[partition] = kerror - return mr -} - -func (mr *MockProduceResponse) For(reqBody versionedDecoder) encoder { - req := reqBody.(*ProduceRequest) - res := &ProduceResponse{} - for topic, partitions := range req.msgSets { - for partition := range partitions { - res.AddTopicPartition(topic, partition, mr.getError(topic, partition)) - } - } - return res -} - -func (mr *MockProduceResponse) getError(topic string, partition int32) KError { - partitions := mr.errors[topic] - if partitions == nil { - return ErrNoError - } - kerror, ok := partitions[partition] - if !ok { - return ErrNoError - } - return kerror -} - -// MockOffsetFetchResponse is a `OffsetFetchResponse` builder. -type MockOffsetFetchResponse struct { - offsets map[string]map[string]map[int32]*OffsetFetchResponseBlock - t TestReporter -} - -func NewMockOffsetFetchResponse(t TestReporter) *MockOffsetFetchResponse { - return &MockOffsetFetchResponse{t: t} -} - -func (mr *MockOffsetFetchResponse) SetOffset(group, topic string, partition int32, offset int64, metadata string, kerror KError) *MockOffsetFetchResponse { - if mr.offsets == nil { - mr.offsets = make(map[string]map[string]map[int32]*OffsetFetchResponseBlock) - } - topics := mr.offsets[group] - if topics == nil { - topics = make(map[string]map[int32]*OffsetFetchResponseBlock) - mr.offsets[group] = topics - } - partitions := topics[topic] - if partitions == nil { - partitions = make(map[int32]*OffsetFetchResponseBlock) - topics[topic] = partitions - } - partitions[partition] = &OffsetFetchResponseBlock{offset, metadata, kerror} - return mr -} - -func (mr *MockOffsetFetchResponse) For(reqBody versionedDecoder) encoder { - req := reqBody.(*OffsetFetchRequest) - group := req.ConsumerGroup - res := &OffsetFetchResponse{} - for topic, partitions := range mr.offsets[group] { - for partition, block := range partitions { - res.AddBlock(topic, partition, block) - } - } - return res -} diff --git a/vendor/github.com/Shopify/sarama/offset_commit_request.go b/vendor/github.com/Shopify/sarama/offset_commit_request.go deleted file mode 100644 index b21ea634b..000000000 --- a/vendor/github.com/Shopify/sarama/offset_commit_request.go +++ /dev/null @@ -1,190 +0,0 @@ -package sarama - -// ReceiveTime is a special value for the timestamp field of Offset Commit Requests which -// tells the broker to set the timestamp to the time at which the request was received. -// The timestamp is only used if message version 1 is used, which requires kafka 0.8.2. -const ReceiveTime int64 = -1 - -// GroupGenerationUndefined is a special value for the group generation field of -// Offset Commit Requests that should be used when a consumer group does not rely -// on Kafka for partition management. -const GroupGenerationUndefined = -1 - -type offsetCommitRequestBlock struct { - offset int64 - timestamp int64 - metadata string -} - -func (b *offsetCommitRequestBlock) encode(pe packetEncoder, version int16) error { - pe.putInt64(b.offset) - if version == 1 { - pe.putInt64(b.timestamp) - } else if b.timestamp != 0 { - Logger.Println("Non-zero timestamp specified for OffsetCommitRequest not v1, it will be ignored") - } - - return pe.putString(b.metadata) -} - -func (b *offsetCommitRequestBlock) decode(pd packetDecoder, version int16) (err error) { - if b.offset, err = pd.getInt64(); err != nil { - return err - } - if version == 1 { - if b.timestamp, err = pd.getInt64(); err != nil { - return err - } - } - b.metadata, err = pd.getString() - return err -} - -type OffsetCommitRequest struct { - ConsumerGroup string - ConsumerGroupGeneration int32 // v1 or later - ConsumerID string // v1 or later - RetentionTime int64 // v2 or later - - // Version can be: - // - 0 (kafka 0.8.1 and later) - // - 1 (kafka 0.8.2 and later) - // - 2 (kafka 0.9.0 and later) - Version int16 - blocks map[string]map[int32]*offsetCommitRequestBlock -} - -func (r *OffsetCommitRequest) encode(pe packetEncoder) error { - if r.Version < 0 || r.Version > 2 { - return PacketEncodingError{"invalid or unsupported OffsetCommitRequest version field"} - } - - if err := pe.putString(r.ConsumerGroup); err != nil { - return err - } - - if r.Version >= 1 { - pe.putInt32(r.ConsumerGroupGeneration) - if err := pe.putString(r.ConsumerID); err != nil { - return err - } - } else { - if r.ConsumerGroupGeneration != 0 { - Logger.Println("Non-zero ConsumerGroupGeneration specified for OffsetCommitRequest v0, it will be ignored") - } - if r.ConsumerID != "" { - Logger.Println("Non-empty ConsumerID specified for OffsetCommitRequest v0, it will be ignored") - } - } - - if r.Version >= 2 { - pe.putInt64(r.RetentionTime) - } else if r.RetentionTime != 0 { - Logger.Println("Non-zero RetentionTime specified for OffsetCommitRequest version <2, it will be ignored") - } - - if err := pe.putArrayLength(len(r.blocks)); err != nil { - return err - } - for topic, partitions := range r.blocks { - if err := pe.putString(topic); err != nil { - return err - } - if err := pe.putArrayLength(len(partitions)); err != nil { - return err - } - for partition, block := range partitions { - pe.putInt32(partition) - if err := block.encode(pe, r.Version); err != nil { - return err - } - } - } - return nil -} - -func (r *OffsetCommitRequest) decode(pd packetDecoder, version int16) (err error) { - r.Version = version - - if r.ConsumerGroup, err = pd.getString(); err != nil { - return err - } - - if r.Version >= 1 { - if r.ConsumerGroupGeneration, err = pd.getInt32(); err != nil { - return err - } - if r.ConsumerID, err = pd.getString(); err != nil { - return err - } - } - - if r.Version >= 2 { - if r.RetentionTime, err = pd.getInt64(); err != nil { - return err - } - } - - topicCount, err := pd.getArrayLength() - if err != nil { - return err - } - if topicCount == 0 { - return nil - } - r.blocks = make(map[string]map[int32]*offsetCommitRequestBlock) - for i := 0; i < topicCount; i++ { - topic, err := pd.getString() - if err != nil { - return err - } - partitionCount, err := pd.getArrayLength() - if err != nil { - return err - } - r.blocks[topic] = make(map[int32]*offsetCommitRequestBlock) - for j := 0; j < partitionCount; j++ { - partition, err := pd.getInt32() - if err != nil { - return err - } - block := &offsetCommitRequestBlock{} - if err := block.decode(pd, r.Version); err != nil { - return err - } - r.blocks[topic][partition] = block - } - } - return nil -} - -func (r *OffsetCommitRequest) key() int16 { - return 8 -} - -func (r *OffsetCommitRequest) version() int16 { - return r.Version -} - -func (r *OffsetCommitRequest) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_8_2_0 - case 2: - return V0_9_0_0 - default: - return minVersion - } -} - -func (r *OffsetCommitRequest) AddBlock(topic string, partitionID int32, offset int64, timestamp int64, metadata string) { - if r.blocks == nil { - r.blocks = make(map[string]map[int32]*offsetCommitRequestBlock) - } - - if r.blocks[topic] == nil { - r.blocks[topic] = make(map[int32]*offsetCommitRequestBlock) - } - - r.blocks[topic][partitionID] = &offsetCommitRequestBlock{offset, timestamp, metadata} -} diff --git a/vendor/github.com/Shopify/sarama/offset_commit_response.go b/vendor/github.com/Shopify/sarama/offset_commit_response.go deleted file mode 100644 index 7f277e775..000000000 --- a/vendor/github.com/Shopify/sarama/offset_commit_response.go +++ /dev/null @@ -1,85 +0,0 @@ -package sarama - -type OffsetCommitResponse struct { - Errors map[string]map[int32]KError -} - -func (r *OffsetCommitResponse) AddError(topic string, partition int32, kerror KError) { - if r.Errors == nil { - r.Errors = make(map[string]map[int32]KError) - } - partitions := r.Errors[topic] - if partitions == nil { - partitions = make(map[int32]KError) - r.Errors[topic] = partitions - } - partitions[partition] = kerror -} - -func (r *OffsetCommitResponse) encode(pe packetEncoder) error { - if err := pe.putArrayLength(len(r.Errors)); err != nil { - return err - } - for topic, partitions := range r.Errors { - if err := pe.putString(topic); err != nil { - return err - } - if err := pe.putArrayLength(len(partitions)); err != nil { - return err - } - for partition, kerror := range partitions { - pe.putInt32(partition) - pe.putInt16(int16(kerror)) - } - } - return nil -} - -func (r *OffsetCommitResponse) decode(pd packetDecoder, version int16) (err error) { - numTopics, err := pd.getArrayLength() - if err != nil || numTopics == 0 { - return err - } - - r.Errors = make(map[string]map[int32]KError, numTopics) - for i := 0; i < numTopics; i++ { - name, err := pd.getString() - if err != nil { - return err - } - - numErrors, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Errors[name] = make(map[int32]KError, numErrors) - - for j := 0; j < numErrors; j++ { - id, err := pd.getInt32() - if err != nil { - return err - } - - tmp, err := pd.getInt16() - if err != nil { - return err - } - r.Errors[name][id] = KError(tmp) - } - } - - return nil -} - -func (r *OffsetCommitResponse) key() int16 { - return 8 -} - -func (r *OffsetCommitResponse) version() int16 { - return 0 -} - -func (r *OffsetCommitResponse) requiredVersion() KafkaVersion { - return minVersion -} diff --git a/vendor/github.com/Shopify/sarama/offset_fetch_request.go b/vendor/github.com/Shopify/sarama/offset_fetch_request.go deleted file mode 100644 index b19fe79ba..000000000 --- a/vendor/github.com/Shopify/sarama/offset_fetch_request.go +++ /dev/null @@ -1,81 +0,0 @@ -package sarama - -type OffsetFetchRequest struct { - ConsumerGroup string - Version int16 - partitions map[string][]int32 -} - -func (r *OffsetFetchRequest) encode(pe packetEncoder) (err error) { - if r.Version < 0 || r.Version > 1 { - return PacketEncodingError{"invalid or unsupported OffsetFetchRequest version field"} - } - - if err = pe.putString(r.ConsumerGroup); err != nil { - return err - } - if err = pe.putArrayLength(len(r.partitions)); err != nil { - return err - } - for topic, partitions := range r.partitions { - if err = pe.putString(topic); err != nil { - return err - } - if err = pe.putInt32Array(partitions); err != nil { - return err - } - } - return nil -} - -func (r *OffsetFetchRequest) decode(pd packetDecoder, version int16) (err error) { - r.Version = version - if r.ConsumerGroup, err = pd.getString(); err != nil { - return err - } - partitionCount, err := pd.getArrayLength() - if err != nil { - return err - } - if partitionCount == 0 { - return nil - } - r.partitions = make(map[string][]int32) - for i := 0; i < partitionCount; i++ { - topic, err := pd.getString() - if err != nil { - return err - } - partitions, err := pd.getInt32Array() - if err != nil { - return err - } - r.partitions[topic] = partitions - } - return nil -} - -func (r *OffsetFetchRequest) key() int16 { - return 9 -} - -func (r *OffsetFetchRequest) version() int16 { - return r.Version -} - -func (r *OffsetFetchRequest) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_8_2_0 - default: - return minVersion - } -} - -func (r *OffsetFetchRequest) AddPartition(topic string, partitionID int32) { - if r.partitions == nil { - r.partitions = make(map[string][]int32) - } - - r.partitions[topic] = append(r.partitions[topic], partitionID) -} diff --git a/vendor/github.com/Shopify/sarama/offset_fetch_response.go b/vendor/github.com/Shopify/sarama/offset_fetch_response.go deleted file mode 100644 index 323220eac..000000000 --- a/vendor/github.com/Shopify/sarama/offset_fetch_response.go +++ /dev/null @@ -1,143 +0,0 @@ -package sarama - -type OffsetFetchResponseBlock struct { - Offset int64 - Metadata string - Err KError -} - -func (b *OffsetFetchResponseBlock) decode(pd packetDecoder) (err error) { - b.Offset, err = pd.getInt64() - if err != nil { - return err - } - - b.Metadata, err = pd.getString() - if err != nil { - return err - } - - tmp, err := pd.getInt16() - if err != nil { - return err - } - b.Err = KError(tmp) - - return nil -} - -func (b *OffsetFetchResponseBlock) encode(pe packetEncoder) (err error) { - pe.putInt64(b.Offset) - - err = pe.putString(b.Metadata) - if err != nil { - return err - } - - pe.putInt16(int16(b.Err)) - - return nil -} - -type OffsetFetchResponse struct { - Blocks map[string]map[int32]*OffsetFetchResponseBlock -} - -func (r *OffsetFetchResponse) encode(pe packetEncoder) error { - if err := pe.putArrayLength(len(r.Blocks)); err != nil { - return err - } - for topic, partitions := range r.Blocks { - if err := pe.putString(topic); err != nil { - return err - } - if err := pe.putArrayLength(len(partitions)); err != nil { - return err - } - for partition, block := range partitions { - pe.putInt32(partition) - if err := block.encode(pe); err != nil { - return err - } - } - } - return nil -} - -func (r *OffsetFetchResponse) decode(pd packetDecoder, version int16) (err error) { - numTopics, err := pd.getArrayLength() - if err != nil || numTopics == 0 { - return err - } - - r.Blocks = make(map[string]map[int32]*OffsetFetchResponseBlock, numTopics) - for i := 0; i < numTopics; i++ { - name, err := pd.getString() - if err != nil { - return err - } - - numBlocks, err := pd.getArrayLength() - if err != nil { - return err - } - - if numBlocks == 0 { - r.Blocks[name] = nil - continue - } - r.Blocks[name] = make(map[int32]*OffsetFetchResponseBlock, numBlocks) - - for j := 0; j < numBlocks; j++ { - id, err := pd.getInt32() - if err != nil { - return err - } - - block := new(OffsetFetchResponseBlock) - err = block.decode(pd) - if err != nil { - return err - } - r.Blocks[name][id] = block - } - } - - return nil -} - -func (r *OffsetFetchResponse) key() int16 { - return 9 -} - -func (r *OffsetFetchResponse) version() int16 { - return 0 -} - -func (r *OffsetFetchResponse) requiredVersion() KafkaVersion { - return minVersion -} - -func (r *OffsetFetchResponse) GetBlock(topic string, partition int32) *OffsetFetchResponseBlock { - if r.Blocks == nil { - return nil - } - - if r.Blocks[topic] == nil { - return nil - } - - return r.Blocks[topic][partition] -} - -func (r *OffsetFetchResponse) AddBlock(topic string, partition int32, block *OffsetFetchResponseBlock) { - if r.Blocks == nil { - r.Blocks = make(map[string]map[int32]*OffsetFetchResponseBlock) - } - partitions := r.Blocks[topic] - if partitions == nil { - partitions = make(map[int32]*OffsetFetchResponseBlock) - r.Blocks[topic] = partitions - } - partitions[partition] = block -} diff --git a/vendor/github.com/Shopify/sarama/offset_manager.go b/vendor/github.com/Shopify/sarama/offset_manager.go deleted file mode 100644 index 6c01f959e..000000000 --- a/vendor/github.com/Shopify/sarama/offset_manager.go +++ /dev/null @@ -1,560 +0,0 @@ -package sarama - -import ( - "sync" - "time" -) - -// Offset Manager - -// OffsetManager uses Kafka to store and fetch consumed partition offsets. -type OffsetManager interface { - // ManagePartition creates a PartitionOffsetManager on the given topic/partition. - // It will return an error if this OffsetManager is already managing the given - // topic/partition. - ManagePartition(topic string, partition int32) (PartitionOffsetManager, error) - - // Close stops the OffsetManager from managing offsets. It is required to call - // this function before an OffsetManager object passes out of scope, as it - // will otherwise leak memory. You must call this after all the - // PartitionOffsetManagers are closed. - Close() error -} - -type offsetManager struct { - client Client - conf *Config - group string - - lock sync.Mutex - poms map[string]map[int32]*partitionOffsetManager - boms map[*Broker]*brokerOffsetManager -} - -// NewOffsetManagerFromClient creates a new OffsetManager from the given client. -// It is still necessary to call Close() on the underlying client when finished with the partition manager. -func NewOffsetManagerFromClient(group string, client Client) (OffsetManager, error) { - // Check that we are not dealing with a closed Client before processing any other arguments - if client.Closed() { - return nil, ErrClosedClient - } - - om := &offsetManager{ - client: client, - conf: client.Config(), - group: group, - poms: make(map[string]map[int32]*partitionOffsetManager), - boms: make(map[*Broker]*brokerOffsetManager), - } - - return om, nil -} - -func (om *offsetManager) ManagePartition(topic string, partition int32) (PartitionOffsetManager, error) { - pom, err := om.newPartitionOffsetManager(topic, partition) - if err != nil { - return nil, err - } - - om.lock.Lock() - defer om.lock.Unlock() - - topicManagers := om.poms[topic] - if topicManagers == nil { - topicManagers = make(map[int32]*partitionOffsetManager) - om.poms[topic] = topicManagers - } - - if topicManagers[partition] != nil { - return nil, ConfigurationError("That topic/partition is already being managed") - } - - topicManagers[partition] = pom - return pom, nil -} - -func (om *offsetManager) Close() error { - return nil -} - -func (om *offsetManager) refBrokerOffsetManager(broker *Broker) *brokerOffsetManager { - om.lock.Lock() - defer om.lock.Unlock() - - bom := om.boms[broker] - if bom == nil { - bom = om.newBrokerOffsetManager(broker) - om.boms[broker] = bom - } - - bom.refs++ - - return bom -} - -func (om *offsetManager) unrefBrokerOffsetManager(bom *brokerOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() - - bom.refs-- - - if bom.refs == 0 { - close(bom.updateSubscriptions) - if om.boms[bom.broker] == bom { - delete(om.boms, bom.broker) - } - } -} - -func (om *offsetManager) abandonBroker(bom *brokerOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() - - delete(om.boms, bom.broker) -} - -func (om *offsetManager) abandonPartitionOffsetManager(pom *partitionOffsetManager) { - om.lock.Lock() - defer om.lock.Unlock() - - delete(om.poms[pom.topic], pom.partition) - if len(om.poms[pom.topic]) == 0 { - delete(om.poms, pom.topic) - } -} - -// Partition Offset Manager - -// PartitionOffsetManager uses Kafka to store and fetch consumed partition offsets. You MUST call Close() -// on a partition offset manager to avoid leaks, it will not be garbage-collected automatically when it passes -// out of scope. -type PartitionOffsetManager interface { - // NextOffset returns the next offset that should be consumed for the managed - // partition, accompanied by metadata which can be used to reconstruct the state - // of the partition consumer when it resumes. NextOffset() will return - // `config.Consumer.Offsets.Initial` and an empty metadata string if no offset - // was committed for this partition yet. - NextOffset() (int64, string) - - // MarkOffset marks the provided offset, alongside a metadata string - // that represents the state of the partition consumer at that point in time. The - // metadata string can be used by another consumer to restore that state, so it - // can resume consumption. - // - // To follow upstream conventions, you are expected to mark the offset of the - // next message to read, not the last message read. Thus, when calling `MarkOffset` - // you should typically add one to the offset of the last consumed message. - // - // Note: calling MarkOffset does not necessarily commit the offset to the backend - // store immediately for efficiency reasons, and it may never be committed if - // your application crashes. This means that you may end up processing the same - // message twice, and your processing should ideally be idempotent. - MarkOffset(offset int64, metadata string) - - // ResetOffset resets to the provided offset, alongside a metadata string that - // represents the state of the partition consumer at that point in time. Reset - // acts as a counterpart to MarkOffset, the difference being that it allows to - // reset an offset to an earlier or smaller value, where MarkOffset only - // allows incrementing the offset. cf MarkOffset for more details. - ResetOffset(offset int64, metadata string) - - // Errors returns a read channel of errors that occur during offset management, if - // enabled. By default, errors are logged and not returned over this channel. If - // you want to implement any custom error handling, set your config's - // Consumer.Return.Errors setting to true, and read from this channel. - Errors() <-chan *ConsumerError - - // AsyncClose initiates a shutdown of the PartitionOffsetManager. This method will - // return immediately, after which you should wait until the 'errors' channel has - // been drained and closed. It is required to call this function, or Close before - // a consumer object passes out of scope, as it will otherwise leak memory. You - // must call this before calling Close on the underlying client. - AsyncClose() - - // Close stops the PartitionOffsetManager from managing offsets. It is required to - // call this function (or AsyncClose) before a PartitionOffsetManager object - // passes out of scope, as it will otherwise leak memory. You must call this - // before calling Close on the underlying client. - Close() error -} - -type partitionOffsetManager struct { - parent *offsetManager - topic string - partition int32 - - lock sync.Mutex - offset int64 - metadata string - dirty bool - clean sync.Cond - broker *brokerOffsetManager - - errors chan *ConsumerError - rebalance chan none - dying chan none -} - -func (om *offsetManager) newPartitionOffsetManager(topic string, partition int32) (*partitionOffsetManager, error) { - pom := &partitionOffsetManager{ - parent: om, - topic: topic, - partition: partition, - errors: make(chan *ConsumerError, om.conf.ChannelBufferSize), - rebalance: make(chan none, 1), - dying: make(chan none), - } - pom.clean.L = &pom.lock - - if err := pom.selectBroker(); err != nil { - return nil, err - } - - if err := pom.fetchInitialOffset(om.conf.Metadata.Retry.Max); err != nil { - return nil, err - } - - pom.broker.updateSubscriptions <- pom - - go withRecover(pom.mainLoop) - - return pom, nil -} - -func (pom *partitionOffsetManager) mainLoop() { - for { - select { - case <-pom.rebalance: - if err := pom.selectBroker(); err != nil { - pom.handleError(err) - pom.rebalance <- none{} - } else { - pom.broker.updateSubscriptions <- pom - } - case <-pom.dying: - if pom.broker != nil { - select { - case <-pom.rebalance: - case pom.broker.updateSubscriptions <- pom: - } - pom.parent.unrefBrokerOffsetManager(pom.broker) - } - pom.parent.abandonPartitionOffsetManager(pom) - close(pom.errors) - return - } - } -} - -func (pom *partitionOffsetManager) selectBroker() error { - if pom.broker != nil { - pom.parent.unrefBrokerOffsetManager(pom.broker) - pom.broker = nil - } - - var broker *Broker - var err error - - if err = pom.parent.client.RefreshCoordinator(pom.parent.group); err != nil { - return err - } - - if broker, err = pom.parent.client.Coordinator(pom.parent.group); err != nil { - return err - } - - pom.broker = pom.parent.refBrokerOffsetManager(broker) - return nil -} - -func (pom *partitionOffsetManager) fetchInitialOffset(retries int) error { - request := new(OffsetFetchRequest) - request.Version = 1 - request.ConsumerGroup = pom.parent.group - request.AddPartition(pom.topic, pom.partition) - - response, err := pom.broker.broker.FetchOffset(request) - if err != nil { - return err - } - - block := response.GetBlock(pom.topic, pom.partition) - if block == nil { - return ErrIncompleteResponse - } - - switch block.Err { - case ErrNoError: - pom.offset = block.Offset - pom.metadata = block.Metadata - return nil - case ErrNotCoordinatorForConsumer: - if retries <= 0 { - return block.Err - } - if err := pom.selectBroker(); err != nil { - return err - } - return pom.fetchInitialOffset(retries - 1) - case ErrOffsetsLoadInProgress: - if retries <= 0 { - return block.Err - } - time.Sleep(pom.parent.conf.Metadata.Retry.Backoff) - return pom.fetchInitialOffset(retries - 1) - default: - return block.Err - } -} - -func (pom *partitionOffsetManager) handleError(err error) { - cErr := &ConsumerError{ - Topic: pom.topic, - Partition: pom.partition, - Err: err, - } - - if pom.parent.conf.Consumer.Return.Errors { - pom.errors <- cErr - } else { - Logger.Println(cErr) - } -} - -func (pom *partitionOffsetManager) Errors() <-chan *ConsumerError { - return pom.errors -} - -func (pom *partitionOffsetManager) MarkOffset(offset int64, metadata string) { - pom.lock.Lock() - defer pom.lock.Unlock() - - if offset > pom.offset { - pom.offset = offset - pom.metadata = metadata - pom.dirty = true - } -} - -func (pom *partitionOffsetManager) ResetOffset(offset int64, metadata string) { - pom.lock.Lock() - defer pom.lock.Unlock() - - if offset <= pom.offset { - pom.offset = offset - pom.metadata = metadata - pom.dirty = true - } -} - -func (pom *partitionOffsetManager) updateCommitted(offset int64, metadata string) { - pom.lock.Lock() - defer pom.lock.Unlock() - - if pom.offset == offset && pom.metadata == metadata { - pom.dirty = false - pom.clean.Signal() - } -} - -func (pom *partitionOffsetManager) NextOffset() (int64, string) { - pom.lock.Lock() - defer pom.lock.Unlock() - - if pom.offset >= 0 { - return pom.offset, pom.metadata - } - - return pom.parent.conf.Consumer.Offsets.Initial, "" -} - -func (pom *partitionOffsetManager) AsyncClose() { - go func() { - pom.lock.Lock() - defer pom.lock.Unlock() - - for pom.dirty { - pom.clean.Wait() - } - - close(pom.dying) - }() -} - -func (pom *partitionOffsetManager) Close() error { - pom.AsyncClose() - - var errors ConsumerErrors - for err := range pom.errors { - errors = append(errors, err) - } - - if len(errors) > 0 { - return errors - } - return nil -} - -// Broker Offset Manager - -type brokerOffsetManager struct { - parent *offsetManager - broker *Broker - timer *time.Ticker - updateSubscriptions chan *partitionOffsetManager - subscriptions map[*partitionOffsetManager]none - refs int -} - -func (om *offsetManager) newBrokerOffsetManager(broker *Broker) *brokerOffsetManager { - bom := &brokerOffsetManager{ - parent: om, - broker: broker, - timer: time.NewTicker(om.conf.Consumer.Offsets.CommitInterval), - updateSubscriptions: make(chan *partitionOffsetManager), - subscriptions: make(map[*partitionOffsetManager]none), - } - - go withRecover(bom.mainLoop) - - return bom -} - -func (bom *brokerOffsetManager) mainLoop() { - for { - select { - case <-bom.timer.C: - if len(bom.subscriptions) > 0 { - bom.flushToBroker() - } - case s, ok := <-bom.updateSubscriptions: - if !ok { - bom.timer.Stop() - return - } - if _, ok := bom.subscriptions[s]; ok { - delete(bom.subscriptions, s) - } else { - bom.subscriptions[s] = none{} - } - } - } -} - -func (bom *brokerOffsetManager) flushToBroker() { - request := bom.constructRequest() - if request == nil { - return - } - - response, err := bom.broker.CommitOffset(request) - - if err != nil { - bom.abort(err) - return - } - - for s := range bom.subscriptions { - if request.blocks[s.topic] == nil || request.blocks[s.topic][s.partition] == nil { - continue - } - - var err KError - var ok bool - - if response.Errors[s.topic] == nil { - s.handleError(ErrIncompleteResponse) - delete(bom.subscriptions, s) - s.rebalance <- none{} - continue - } - if err, ok = response.Errors[s.topic][s.partition]; !ok { - s.handleError(ErrIncompleteResponse) - delete(bom.subscriptions, s) - s.rebalance <- none{} - continue - } - - switch err { - case ErrNoError: - block := request.blocks[s.topic][s.partition] - s.updateCommitted(block.offset, block.metadata) - case ErrNotLeaderForPartition, ErrLeaderNotAvailable, - ErrConsumerCoordinatorNotAvailable, ErrNotCoordinatorForConsumer: - // not a critical error, we just need to redispatch - delete(bom.subscriptions, s) - s.rebalance <- none{} - case ErrOffsetMetadataTooLarge, ErrInvalidCommitOffsetSize: - // nothing we can do about this, just tell the user and carry on - s.handleError(err) - case ErrOffsetsLoadInProgress: - // nothing wrong but we didn't commit, we'll get it next time round - break - case ErrUnknownTopicOrPartition: - // let the user know *and* try redispatching - if topic-auto-create is - // enabled, redispatching should trigger a metadata request and create the - // topic; if not then re-dispatching won't help, but we've let the user - // know and it shouldn't hurt either (see https://github.com/Shopify/sarama/issues/706) - fallthrough - default: - // dunno, tell the user and try redispatching - s.handleError(err) - delete(bom.subscriptions, s) - s.rebalance <- none{} - } - } -} - -func (bom *brokerOffsetManager) constructRequest() *OffsetCommitRequest { - var r *OffsetCommitRequest - var perPartitionTimestamp int64 - if bom.parent.conf.Consumer.Offsets.Retention == 0 { - perPartitionTimestamp = ReceiveTime - r = &OffsetCommitRequest{ - Version: 1, - ConsumerGroup: bom.parent.group, - ConsumerGroupGeneration: GroupGenerationUndefined, - } - } else { - r = &OffsetCommitRequest{ - Version: 2, - RetentionTime: int64(bom.parent.conf.Consumer.Offsets.Retention / time.Millisecond), - ConsumerGroup: bom.parent.group, - ConsumerGroupGeneration: GroupGenerationUndefined, - } - - } - - for s := range bom.subscriptions { - s.lock.Lock() - if s.dirty { - r.AddBlock(s.topic, s.partition, s.offset, perPartitionTimestamp, s.metadata) - } - s.lock.Unlock() - } - - if len(r.blocks) > 0 { - return r - } - - return nil -} - -func (bom *brokerOffsetManager) abort(err error) { - _ = bom.broker.Close() // we don't care about the error this might return, we already have one - bom.parent.abandonBroker(bom) - - for pom := range bom.subscriptions { - pom.handleError(err) - pom.rebalance <- none{} - } - - for s := range bom.updateSubscriptions { - if _, ok := bom.subscriptions[s]; !ok { - s.handleError(err) - s.rebalance <- none{} - } - } - - bom.subscriptions = make(map[*partitionOffsetManager]none) -} diff --git a/vendor/github.com/Shopify/sarama/offset_request.go b/vendor/github.com/Shopify/sarama/offset_request.go deleted file mode 100644 index 6c2696016..000000000 --- a/vendor/github.com/Shopify/sarama/offset_request.go +++ /dev/null @@ -1,132 +0,0 @@ -package sarama - -type offsetRequestBlock struct { - time int64 - maxOffsets int32 // Only used in version 0 -} - -func (b *offsetRequestBlock) encode(pe packetEncoder, version int16) error { - pe.putInt64(int64(b.time)) - if version == 0 { - pe.putInt32(b.maxOffsets) - } - - return nil -} - -func (b *offsetRequestBlock) decode(pd packetDecoder, version int16) (err error) { - if b.time, err = pd.getInt64(); err != nil { - return err - } - if version == 0 { - if b.maxOffsets, err = pd.getInt32(); err != nil { - return err - } - } - return nil -} - -type OffsetRequest struct { - Version int16 - blocks map[string]map[int32]*offsetRequestBlock -} - -func (r *OffsetRequest) encode(pe packetEncoder) error { - pe.putInt32(-1) // replica ID is always -1 for clients - err := pe.putArrayLength(len(r.blocks)) - if err != nil { - return err - } - for topic, partitions := range r.blocks { - err = pe.putString(topic) - if err != nil { - return err - } - err = pe.putArrayLength(len(partitions)) - if err != nil { - return err - } - for partition, block := range partitions { - pe.putInt32(partition) - if err = block.encode(pe, r.Version); err != nil { - return err - } - } - } - return nil -} - -func (r *OffsetRequest) decode(pd packetDecoder, version int16) error { - r.Version = version - - // Ignore replica ID - if _, err := pd.getInt32(); err != nil { - return err - } - blockCount, err := pd.getArrayLength() - if err != nil { - return err - } - if blockCount == 0 { - return nil - } - r.blocks = make(map[string]map[int32]*offsetRequestBlock) - for i := 0; i < blockCount; i++ { - topic, err := pd.getString() - if err != nil { - return err - } - partitionCount, err := pd.getArrayLength() - if err != nil { - return err - } - r.blocks[topic] = make(map[int32]*offsetRequestBlock) - for j := 0; j < partitionCount; j++ { - partition, err := pd.getInt32() - if err != nil { - return err - } - block := &offsetRequestBlock{} - if err := block.decode(pd, version); err != nil { - return err - } - r.blocks[topic][partition] = block - } - } - return nil -} - -func (r *OffsetRequest) key() int16 { - return 2 -} - -func (r *OffsetRequest) version() int16 { - return r.Version -} - -func (r *OffsetRequest) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_10_1_0 - default: - return minVersion - } -} - -func (r *OffsetRequest) AddBlock(topic string, partitionID int32, time int64, maxOffsets int32) { - if r.blocks == nil { - r.blocks = make(map[string]map[int32]*offsetRequestBlock) - } - - if r.blocks[topic] == nil { - r.blocks[topic] = make(map[int32]*offsetRequestBlock) - } - - tmp := new(offsetRequestBlock) - tmp.time = time - if r.Version == 0 { - tmp.maxOffsets = maxOffsets - } - - r.blocks[topic][partitionID] = tmp -} diff --git a/vendor/github.com/Shopify/sarama/offset_response.go b/vendor/github.com/Shopify/sarama/offset_response.go deleted file mode 100644 index 9a9cfe96f..000000000 --- a/vendor/github.com/Shopify/sarama/offset_response.go +++ /dev/null @@ -1,174 +0,0 @@ -package sarama - -type OffsetResponseBlock struct { - Err KError - Offsets []int64 // Version 0 - Offset int64 // Version 1 - Timestamp int64 // Version 1 -} - -func (b *OffsetResponseBlock) decode(pd packetDecoder, version int16) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - b.Err = KError(tmp) - - if version == 0 { - b.Offsets, err = pd.getInt64Array() - - return err - } - - b.Timestamp, err = pd.getInt64() - if err != nil { - return err - } - - b.Offset, err = pd.getInt64() - if err != nil { - return err - } - - // For backwards compatibility put the offset in the offsets array too - b.Offsets = []int64{b.Offset} - - return nil -} - -func (b *OffsetResponseBlock) encode(pe packetEncoder, version int16) (err error) { - pe.putInt16(int16(b.Err)) - - if version == 0 { - return pe.putInt64Array(b.Offsets) - } - - pe.putInt64(b.Timestamp) - pe.putInt64(b.Offset) - - return nil -} - -type OffsetResponse struct { - Version int16 - Blocks map[string]map[int32]*OffsetResponseBlock -} - -func (r *OffsetResponse) decode(pd packetDecoder, version int16) (err error) { - numTopics, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks = make(map[string]map[int32]*OffsetResponseBlock, numTopics) - for i := 0; i < numTopics; i++ { - name, err := pd.getString() - if err != nil { - return err - } - - numBlocks, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks[name] = make(map[int32]*OffsetResponseBlock, numBlocks) - - for j := 0; j < numBlocks; j++ { - id, err := pd.getInt32() - if err != nil { - return err - } - - block := new(OffsetResponseBlock) - err = block.decode(pd, version) - if err != nil { - return err - } - r.Blocks[name][id] = block - } - } - - return nil -} - -func (r *OffsetResponse) GetBlock(topic string, partition int32) *OffsetResponseBlock { - if r.Blocks == nil { - return nil - } - - if r.Blocks[topic] == nil { - return nil - } - - return r.Blocks[topic][partition] -} - -/* -// [0 0 0 1 ntopics -0 8 109 121 95 116 111 112 105 99 topic -0 0 0 1 npartitions -0 0 0 0 id -0 0 - -0 0 0 1 0 0 0 0 -0 1 1 1 0 0 0 1 -0 8 109 121 95 116 111 112 -105 99 0 0 0 1 0 0 -0 0 0 0 0 0 0 1 -0 0 0 0 0 1 1 1] - -*/ -func (r *OffsetResponse) encode(pe packetEncoder) (err error) { - if err = pe.putArrayLength(len(r.Blocks)); err != nil { - return err - } - - for topic, partitions := range r.Blocks { - if err = pe.putString(topic); err != nil { - return err - } - if err = pe.putArrayLength(len(partitions)); err != nil { - return err - } - for partition, block := range partitions { - pe.putInt32(partition) - if err = block.encode(pe, r.version()); err != nil { - return err - } - } - } - - return nil -} - -func (r *OffsetResponse) key() int16 { - return 2 -} - -func (r *OffsetResponse) version() int16 { - return r.Version -} - -func (r *OffsetResponse) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_10_1_0 - default: - return minVersion - } -} - -// testing API - -func (r *OffsetResponse) AddTopicPartition(topic string, partition int32, offset int64) { - if r.Blocks == nil { - r.Blocks = make(map[string]map[int32]*OffsetResponseBlock) - } - byTopic, ok := r.Blocks[topic] - if !ok { - byTopic = make(map[int32]*OffsetResponseBlock) - r.Blocks[topic] = byTopic - } - byTopic[partition] = &OffsetResponseBlock{Offsets: []int64{offset}, Offset: offset} -} diff --git a/vendor/github.com/Shopify/sarama/packet_decoder.go b/vendor/github.com/Shopify/sarama/packet_decoder.go deleted file mode 100644 index 28670c0e6..000000000 --- a/vendor/github.com/Shopify/sarama/packet_decoder.go +++ /dev/null @@ -1,45 +0,0 @@ -package sarama - -// PacketDecoder is the interface providing helpers for reading with Kafka's encoding rules. -// Types implementing Decoder only need to worry about calling methods like GetString, -// not about how a string is represented in Kafka. -type packetDecoder interface { - // Primitives - getInt8() (int8, error) - getInt16() (int16, error) - getInt32() (int32, error) - getInt64() (int64, error) - getArrayLength() (int, error) - - // Collections - getBytes() ([]byte, error) - getString() (string, error) - getInt32Array() ([]int32, error) - getInt64Array() ([]int64, error) - getStringArray() ([]string, error) - - // Subsets - remaining() int - getSubset(length int) (packetDecoder, error) - - // Stacks, see PushDecoder - push(in pushDecoder) error - pop() error -} - -// PushDecoder is the interface for decoding fields like CRCs and lengths where the validity -// of the field depends on what is after it in the packet. Start them with PacketDecoder.Push() where -// the actual value is located in the packet, then PacketDecoder.Pop() them when all the bytes they -// depend upon have been decoded. -type pushDecoder interface { - // Saves the offset into the input buffer as the location to actually read the calculated value when able. - saveOffset(in int) - - // Returns the length of data to reserve for the input of this encoder (eg 4 bytes for a CRC32). - reserveLength() int - - // Indicates that all required data is now available to calculate and check the field. - // SaveOffset is guaranteed to have been called first. The implementation should read ReserveLength() bytes - // of data from the saved offset, and verify it based on the data between the saved offset and curOffset. - check(curOffset int, buf []byte) error -} diff --git a/vendor/github.com/Shopify/sarama/packet_encoder.go b/vendor/github.com/Shopify/sarama/packet_encoder.go deleted file mode 100644 index 27a10f6d4..000000000 --- a/vendor/github.com/Shopify/sarama/packet_encoder.go +++ /dev/null @@ -1,50 +0,0 @@ -package sarama - -import "github.com/rcrowley/go-metrics" - -// PacketEncoder is the interface providing helpers for writing with Kafka's encoding rules. -// Types implementing Encoder only need to worry about calling methods like PutString, -// not about how a string is represented in Kafka. -type packetEncoder interface { - // Primitives - putInt8(in int8) - putInt16(in int16) - putInt32(in int32) - putInt64(in int64) - putArrayLength(in int) error - - // Collections - putBytes(in []byte) error - putRawBytes(in []byte) error - putString(in string) error - putStringArray(in []string) error - putInt32Array(in []int32) error - putInt64Array(in []int64) error - - // Provide the current offset to record the batch size metric - offset() int - - // Stacks, see PushEncoder - push(in pushEncoder) - pop() error - - // To record metrics when provided - metricRegistry() metrics.Registry -} - -// PushEncoder is the interface for encoding fields like CRCs and lengths where the value -// of the field depends on what is encoded after it in the packet. Start them with PacketEncoder.Push() where -// the actual value is located in the packet, then PacketEncoder.Pop() them when all the bytes they -// depend upon have been written. -type pushEncoder interface { - // Saves the offset into the input buffer as the location to actually write the calculated value when able. - saveOffset(in int) - - // Returns the length of data to reserve for the output of this encoder (eg 4 bytes for a CRC32). - reserveLength() int - - // Indicates that all required data is now available to calculate and write the field. - // SaveOffset is guaranteed to have been called first. The implementation should write ReserveLength() bytes - // of data to the saved offset, based on the data between the saved offset and curOffset. - run(curOffset int, buf []byte) error -} diff --git a/vendor/github.com/Shopify/sarama/partitioner.go b/vendor/github.com/Shopify/sarama/partitioner.go deleted file mode 100644 index 972932728..000000000 --- a/vendor/github.com/Shopify/sarama/partitioner.go +++ /dev/null @@ -1,135 +0,0 @@ -package sarama - -import ( - "hash" - "hash/fnv" - "math/rand" - "time" -) - -// Partitioner is anything that, given a Kafka message and a number of partitions indexed [0...numPartitions-1], -// decides to which partition to send the message. RandomPartitioner, RoundRobinPartitioner and HashPartitioner are provided -// as simple default implementations. -type Partitioner interface { - // Partition takes a message and partition count and chooses a partition - Partition(message *ProducerMessage, numPartitions int32) (int32, error) - - // RequiresConsistency indicates to the user of the partitioner whether the - // mapping of key->partition is consistent or not. Specifically, if a - // partitioner requires consistency then it must be allowed to choose from all - // partitions (even ones known to be unavailable), and its choice must be - // respected by the caller. The obvious example is the HashPartitioner. - RequiresConsistency() bool -} - -// PartitionerConstructor is the type for a function capable of constructing new Partitioners. -type PartitionerConstructor func(topic string) Partitioner - -type manualPartitioner struct{} - -// NewManualPartitioner returns a Partitioner which uses the partition manually set in the provided -// ProducerMessage's Partition field as the partition to produce to. -func NewManualPartitioner(topic string) Partitioner { - return new(manualPartitioner) -} - -func (p *manualPartitioner) Partition(message *ProducerMessage, numPartitions int32) (int32, error) { - return message.Partition, nil -} - -func (p *manualPartitioner) RequiresConsistency() bool { - return true -} - -type randomPartitioner struct { - generator *rand.Rand -} - -// NewRandomPartitioner returns a Partitioner which chooses a random partition each time. -func NewRandomPartitioner(topic string) Partitioner { - p := new(randomPartitioner) - p.generator = rand.New(rand.NewSource(time.Now().UTC().UnixNano())) - return p -} - -func (p *randomPartitioner) Partition(message *ProducerMessage, numPartitions int32) (int32, error) { - return int32(p.generator.Intn(int(numPartitions))), nil -} - -func (p *randomPartitioner) RequiresConsistency() bool { - return false -} - -type roundRobinPartitioner struct { - partition int32 -} - -// NewRoundRobinPartitioner returns a Partitioner which walks through the available partitions one at a time. -func NewRoundRobinPartitioner(topic string) Partitioner { - return &roundRobinPartitioner{} -} - -func (p *roundRobinPartitioner) Partition(message *ProducerMessage, numPartitions int32) (int32, error) { - if p.partition >= numPartitions { - p.partition = 0 - } - ret := p.partition - p.partition++ - return ret, nil -} - -func (p *roundRobinPartitioner) RequiresConsistency() bool { - return false -} - -type hashPartitioner struct { - random Partitioner - hasher hash.Hash32 -} - -// NewCustomHashPartitioner is a wrapper around NewHashPartitioner, allowing the use of custom hasher. -// The argument is a function providing the instance, implementing the hash.Hash32 interface. This is to ensure that -// each partition dispatcher gets its own hasher, to avoid concurrency issues by sharing an instance. -func NewCustomHashPartitioner(hasher func() hash.Hash32) PartitionerConstructor { - return func(topic string) Partitioner { - p := new(hashPartitioner) - p.random = NewRandomPartitioner(topic) - p.hasher = hasher() - return p - } -} - -// NewHashPartitioner returns a Partitioner which behaves as follows. If the message's key is nil then a -// random partition is chosen. Otherwise the FNV-1a hash of the encoded bytes of the message key is used, -// modulus the number of partitions. This ensures that messages with the same key always end up on the -// same partition. -func NewHashPartitioner(topic string) Partitioner { - p := new(hashPartitioner) - p.random = NewRandomPartitioner(topic) - p.hasher = fnv.New32a() - return p -} - -func (p *hashPartitioner) Partition(message *ProducerMessage, numPartitions int32) (int32, error) { - if message.Key == nil { - return p.random.Partition(message, numPartitions) - } - bytes, err := message.Key.Encode() - if err != nil { - return -1, err - } - p.hasher.Reset() - _, err = p.hasher.Write(bytes) - if err != nil { - return -1, err - } - partition := int32(p.hasher.Sum32()) % numPartitions - if partition < 0 { - partition = -partition - } - return partition, nil -} - -func (p *hashPartitioner) RequiresConsistency() bool { - return true -} diff --git a/vendor/github.com/Shopify/sarama/prep_encoder.go b/vendor/github.com/Shopify/sarama/prep_encoder.go deleted file mode 100644 index fd5ea0f91..000000000 --- a/vendor/github.com/Shopify/sarama/prep_encoder.go +++ /dev/null @@ -1,121 +0,0 @@ -package sarama - -import ( - "fmt" - "math" - - "github.com/rcrowley/go-metrics" -) - -type prepEncoder struct { - length int -} - -// primitives - -func (pe *prepEncoder) putInt8(in int8) { - pe.length++ -} - -func (pe *prepEncoder) putInt16(in int16) { - pe.length += 2 -} - -func (pe *prepEncoder) putInt32(in int32) { - pe.length += 4 -} - -func (pe *prepEncoder) putInt64(in int64) { - pe.length += 8 -} - -func (pe *prepEncoder) putArrayLength(in int) error { - if in > math.MaxInt32 { - return PacketEncodingError{fmt.Sprintf("array too long (%d)", in)} - } - pe.length += 4 - return nil -} - -// arrays - -func (pe *prepEncoder) putBytes(in []byte) error { - pe.length += 4 - if in == nil { - return nil - } - if len(in) > math.MaxInt32 { - return PacketEncodingError{fmt.Sprintf("byteslice too long (%d)", len(in))} - } - pe.length += len(in) - return nil -} - -func (pe *prepEncoder) putRawBytes(in []byte) error { - if len(in) > math.MaxInt32 { - return PacketEncodingError{fmt.Sprintf("byteslice too long (%d)", len(in))} - } - pe.length += len(in) - return nil -} - -func (pe *prepEncoder) putString(in string) error { - pe.length += 2 - if len(in) > math.MaxInt16 { - return PacketEncodingError{fmt.Sprintf("string too long (%d)", len(in))} - } - pe.length += len(in) - return nil -} - -func (pe *prepEncoder) putStringArray(in []string) error { - err := pe.putArrayLength(len(in)) - if err != nil { - return err - } - - for _, str := range in { - if err := pe.putString(str); err != nil { - return err - } - } - - return nil -} - -func (pe *prepEncoder) putInt32Array(in []int32) error { - err := pe.putArrayLength(len(in)) - if err != nil { - return err - } - pe.length += 4 * len(in) - return nil -} - -func (pe *prepEncoder) putInt64Array(in []int64) error { - err := pe.putArrayLength(len(in)) - if err != nil { - return err - } - pe.length += 8 * len(in) - return nil -} - -func (pe *prepEncoder) offset() int { - return pe.length -} - -// stackable - -func (pe *prepEncoder) push(in pushEncoder) { - pe.length += in.reserveLength() -} - -func (pe *prepEncoder) pop() error { - return nil -} - -// we do not record metrics during the prep encoder pass -func (pe *prepEncoder) metricRegistry() metrics.Registry { - return nil -} diff --git a/vendor/github.com/Shopify/sarama/produce_request.go b/vendor/github.com/Shopify/sarama/produce_request.go deleted file mode 100644 index 40dc80151..000000000 --- a/vendor/github.com/Shopify/sarama/produce_request.go +++ /dev/null @@ -1,209 +0,0 @@ -package sarama - -import "github.com/rcrowley/go-metrics" - -// RequiredAcks is used in Produce Requests to tell the broker how many replica acknowledgements -// it must see before responding. Any of the constants defined here are valid. On broker versions -// prior to 0.8.2.0 any other positive int16 is also valid (the broker will wait for that many -// acknowledgements) but in 0.8.2.0 and later this will raise an exception (it has been replaced -// by setting the `min.isr` value in the brokers configuration). -type RequiredAcks int16 - -const ( - // NoResponse doesn't send any response, the TCP ACK is all you get. - NoResponse RequiredAcks = 0 - // WaitForLocal waits for only the local commit to succeed before responding. - WaitForLocal RequiredAcks = 1 - // WaitForAll waits for all in-sync replicas to commit before responding. - // The minimum number of in-sync replicas is configured on the broker via - // the `min.insync.replicas` configuration key. - WaitForAll RequiredAcks = -1 -) - -type ProduceRequest struct { - RequiredAcks RequiredAcks - Timeout int32 - Version int16 // v1 requires Kafka 0.9, v2 requires Kafka 0.10 - msgSets map[string]map[int32]*MessageSet -} - -func (r *ProduceRequest) encode(pe packetEncoder) error { - pe.putInt16(int16(r.RequiredAcks)) - pe.putInt32(r.Timeout) - err := pe.putArrayLength(len(r.msgSets)) - if err != nil { - return err - } - metricRegistry := pe.metricRegistry() - var batchSizeMetric metrics.Histogram - var compressionRatioMetric metrics.Histogram - if metricRegistry != nil { - batchSizeMetric = getOrRegisterHistogram("batch-size", metricRegistry) - compressionRatioMetric = getOrRegisterHistogram("compression-ratio", metricRegistry) - } - - totalRecordCount := int64(0) - for topic, partitions := range r.msgSets { - err = pe.putString(topic) - if err != nil { - return err - } - err = pe.putArrayLength(len(partitions)) - if err != nil { - return err - } - topicRecordCount := int64(0) - var topicCompressionRatioMetric metrics.Histogram - if metricRegistry != nil { - topicCompressionRatioMetric = getOrRegisterTopicHistogram("compression-ratio", topic, metricRegistry) - } - for id, msgSet := range partitions { - startOffset := pe.offset() - pe.putInt32(id) - pe.push(&lengthField{}) - err = msgSet.encode(pe) - if err != nil { - return err - } - err = pe.pop() - if err != nil { - return err - } - if metricRegistry != nil { - for _, messageBlock := range msgSet.Messages { - // Is this a fake "message" wrapping real messages? - if messageBlock.Msg.Set != nil { - topicRecordCount += int64(len(messageBlock.Msg.Set.Messages)) - } else { - // A single uncompressed message - topicRecordCount++ - } - // Better be safe than sorry when computing the compression ratio - if messageBlock.Msg.compressedSize != 0 { - compressionRatio := float64(len(messageBlock.Msg.Value)) / - float64(messageBlock.Msg.compressedSize) - // Histogram do not support decimal values, let's multiple it by 100 for better precision - intCompressionRatio := int64(100 * compressionRatio) - compressionRatioMetric.Update(intCompressionRatio) - topicCompressionRatioMetric.Update(intCompressionRatio) - } - } - batchSize := int64(pe.offset() - startOffset) - batchSizeMetric.Update(batchSize) - getOrRegisterTopicHistogram("batch-size", topic, metricRegistry).Update(batchSize) - } - } - if topicRecordCount > 0 { - getOrRegisterTopicMeter("record-send-rate", topic, metricRegistry).Mark(topicRecordCount) - getOrRegisterTopicHistogram("records-per-request", topic, metricRegistry).Update(topicRecordCount) - totalRecordCount += topicRecordCount - } - } - if totalRecordCount > 0 { - metrics.GetOrRegisterMeter("record-send-rate", metricRegistry).Mark(totalRecordCount) - getOrRegisterHistogram("records-per-request", metricRegistry).Update(totalRecordCount) - } - - return nil -} - -func (r *ProduceRequest) decode(pd packetDecoder, version int16) error { - requiredAcks, err := pd.getInt16() - if err != nil { - return err - } - r.RequiredAcks = RequiredAcks(requiredAcks) - if r.Timeout, err = pd.getInt32(); err != nil { - return err - } - topicCount, err := pd.getArrayLength() - if err != nil { - return err - } - if topicCount == 0 { - return nil - } - r.msgSets = make(map[string]map[int32]*MessageSet) - for i := 0; i < topicCount; i++ { - topic, err := pd.getString() - if err != nil { - return err - } - partitionCount, err := pd.getArrayLength() - if err != nil { - return err - } - r.msgSets[topic] = make(map[int32]*MessageSet) - for j := 0; j < partitionCount; j++ { - partition, err := pd.getInt32() - if err != nil { - return err - } - messageSetSize, err := pd.getInt32() - if err != nil { - return err - } - msgSetDecoder, err := pd.getSubset(int(messageSetSize)) - if err != nil { - return err - } - msgSet := &MessageSet{} - err = msgSet.decode(msgSetDecoder) - if err != nil { - return err - } - r.msgSets[topic][partition] = msgSet - } - } - return nil -} - -func (r *ProduceRequest) key() int16 { - return 0 -} - -func (r *ProduceRequest) version() int16 { - return r.Version -} - -func (r *ProduceRequest) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_9_0_0 - case 2: - return V0_10_0_0 - default: - return minVersion - } -} - -func (r *ProduceRequest) AddMessage(topic string, partition int32, msg *Message) { - if r.msgSets == nil { - r.msgSets = make(map[string]map[int32]*MessageSet) - } - - if r.msgSets[topic] == nil { - r.msgSets[topic] = make(map[int32]*MessageSet) - } - - set := r.msgSets[topic][partition] - - if set == nil { - set = new(MessageSet) - r.msgSets[topic][partition] = set - } - - set.addMessage(msg) -} - -func (r *ProduceRequest) AddSet(topic string, partition int32, set *MessageSet) { - if r.msgSets == nil { - r.msgSets = make(map[string]map[int32]*MessageSet) - } - - if r.msgSets[topic] == nil { - r.msgSets[topic] = make(map[int32]*MessageSet) - } - - r.msgSets[topic][partition] = set -} diff --git a/vendor/github.com/Shopify/sarama/produce_response.go b/vendor/github.com/Shopify/sarama/produce_response.go deleted file mode 100644 index 3f05dd9fb..000000000 --- a/vendor/github.com/Shopify/sarama/produce_response.go +++ /dev/null @@ -1,159 +0,0 @@ -package sarama - -import "time" - -type ProduceResponseBlock struct { - Err KError - Offset int64 - // only provided if Version >= 2 and the broker is configured with `LogAppendTime` - Timestamp time.Time -} - -func (b *ProduceResponseBlock) decode(pd packetDecoder, version int16) (err error) { - tmp, err := pd.getInt16() - if err != nil { - return err - } - b.Err = KError(tmp) - - b.Offset, err = pd.getInt64() - if err != nil { - return err - } - - if version >= 2 { - if millis, err := pd.getInt64(); err != nil { - return err - } else if millis != -1 { - b.Timestamp = time.Unix(millis/1000, (millis%1000)*int64(time.Millisecond)) - } - } - - return nil -} - -type ProduceResponse struct { - Blocks map[string]map[int32]*ProduceResponseBlock - Version int16 - ThrottleTime time.Duration // only provided if Version >= 1 -} - -func (r *ProduceResponse) decode(pd packetDecoder, version int16) (err error) { - r.Version = version - - numTopics, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks = make(map[string]map[int32]*ProduceResponseBlock, numTopics) - for i := 0; i < numTopics; i++ { - name, err := pd.getString() - if err != nil { - return err - } - - numBlocks, err := pd.getArrayLength() - if err != nil { - return err - } - - r.Blocks[name] = make(map[int32]*ProduceResponseBlock, numBlocks) - - for j := 0; j < numBlocks; j++ { - id, err := pd.getInt32() - if err != nil { - return err - } - - block := new(ProduceResponseBlock) - err = block.decode(pd, version) - if err != nil { - return err - } - r.Blocks[name][id] = block - } - } - - if r.Version >= 1 { - millis, err := pd.getInt32() - if err != nil { - return err - } - - r.ThrottleTime = time.Duration(millis) * time.Millisecond - } - - return nil -} - -func (r *ProduceResponse) encode(pe packetEncoder) error { - err := pe.putArrayLength(len(r.Blocks)) - if err != nil { - return err - } - for topic, partitions := range r.Blocks { - err = pe.putString(topic) - if err != nil { - return err - } - err = pe.putArrayLength(len(partitions)) - if err != nil { - return err - } - for id, prb := range partitions { - pe.putInt32(id) - pe.putInt16(int16(prb.Err)) - pe.putInt64(prb.Offset) - } - } - if r.Version >= 1 { - pe.putInt32(int32(r.ThrottleTime / time.Millisecond)) - } - return nil -} - -func (r *ProduceResponse) key() int16 { - return 0 -} - -func (r *ProduceResponse) version() int16 { - return r.Version -} - -func (r *ProduceResponse) requiredVersion() KafkaVersion { - switch r.Version { - case 1: - return V0_9_0_0 - case 2: - return V0_10_0_0 - default: - return minVersion - } -} - -func (r *ProduceResponse) GetBlock(topic string, partition int32) *ProduceResponseBlock { - if r.Blocks == nil { - return nil - } - - if r.Blocks[topic] == nil { - return nil - } - - return r.Blocks[topic][partition] -} - -// Testing API - -func (r *ProduceResponse) AddTopicPartition(topic string, partition int32, err KError) { - if r.Blocks == nil { - r.Blocks = make(map[string]map[int32]*ProduceResponseBlock) - } - byTopic, ok := r.Blocks[topic] - if !ok { - byTopic = make(map[int32]*ProduceResponseBlock) - r.Blocks[topic] = byTopic - } - byTopic[partition] = &ProduceResponseBlock{Err: err} -} diff --git a/vendor/github.com/Shopify/sarama/produce_set.go b/vendor/github.com/Shopify/sarama/produce_set.go deleted file mode 100644 index 158d9c475..000000000 --- a/vendor/github.com/Shopify/sarama/produce_set.go +++ /dev/null @@ -1,176 +0,0 @@ -package sarama - -import "time" - -type partitionSet struct { - msgs []*ProducerMessage - setToSend *MessageSet - bufferBytes int -} - -type produceSet struct { - parent *asyncProducer - msgs map[string]map[int32]*partitionSet - - bufferBytes int - bufferCount int -} - -func newProduceSet(parent *asyncProducer) *produceSet { - return &produceSet{ - msgs: make(map[string]map[int32]*partitionSet), - parent: parent, - } -} - -func (ps *produceSet) add(msg *ProducerMessage) error { - var err error - var key, val []byte - - if msg.Key != nil { - if key, err = msg.Key.Encode(); err != nil { - return err - } - } - - if msg.Value != nil { - if val, err = msg.Value.Encode(); err != nil { - return err - } - } - - partitions := ps.msgs[msg.Topic] - if partitions == nil { - partitions = make(map[int32]*partitionSet) - ps.msgs[msg.Topic] = partitions - } - - set := partitions[msg.Partition] - if set == nil { - set = &partitionSet{setToSend: new(MessageSet)} - partitions[msg.Partition] = set - } - - set.msgs = append(set.msgs, msg) - msgToSend := &Message{Codec: CompressionNone, Key: key, Value: val} - if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) { - if msg.Timestamp.IsZero() { - msgToSend.Timestamp = time.Now() - } else { - msgToSend.Timestamp = msg.Timestamp - } - msgToSend.Version = 1 - } - set.setToSend.addMessage(msgToSend) - - size := producerMessageOverhead + len(key) + len(val) - set.bufferBytes += size - ps.bufferBytes += size - ps.bufferCount++ - - return nil -} - -func (ps *produceSet) buildRequest() *ProduceRequest { - req := &ProduceRequest{ - RequiredAcks: ps.parent.conf.Producer.RequiredAcks, - Timeout: int32(ps.parent.conf.Producer.Timeout / time.Millisecond), - } - if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) { - req.Version = 2 - } - - for topic, partitionSet := range ps.msgs { - for partition, set := range partitionSet { - if ps.parent.conf.Producer.Compression == CompressionNone { - req.AddSet(topic, partition, set.setToSend) - } else { - // When compression is enabled, the entire set for each partition is compressed - // and sent as the payload of a single fake "message" with the appropriate codec - // set and no key. When the server sees a message with a compression codec, it - // decompresses the payload and treats the result as its message set. - payload, err := encode(set.setToSend, ps.parent.conf.MetricRegistry) - if err != nil { - Logger.Println(err) // if this happens, it's basically our fault. - panic(err) - } - compMsg := &Message{ - Codec: ps.parent.conf.Producer.Compression, - Key: nil, - Value: payload, - Set: set.setToSend, // Provide the underlying message set for accurate metrics - } - if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) { - compMsg.Version = 1 - compMsg.Timestamp = set.setToSend.Messages[0].Msg.Timestamp - } - req.AddMessage(topic, partition, compMsg) - } - } - } - - return req -} - -func (ps *produceSet) eachPartition(cb func(topic string, partition int32, msgs []*ProducerMessage)) { - for topic, partitionSet := range ps.msgs { - for partition, set := range partitionSet { - cb(topic, partition, set.msgs) - } - } -} - -func (ps *produceSet) dropPartition(topic string, partition int32) []*ProducerMessage { - if ps.msgs[topic] == nil { - return nil - } - set := ps.msgs[topic][partition] - if set == nil { - return nil - } - ps.bufferBytes -= set.bufferBytes - ps.bufferCount -= len(set.msgs) - delete(ps.msgs[topic], partition) - return set.msgs -} - -func (ps *produceSet) wouldOverflow(msg *ProducerMessage) bool { - switch { - // Would we overflow our maximum possible size-on-the-wire? 10KiB is arbitrary overhead for safety. - case ps.bufferBytes+msg.byteSize() >= int(MaxRequestSize-(10*1024)): - return true - // Would we overflow the size-limit of a compressed message-batch for this partition? - case ps.parent.conf.Producer.Compression != CompressionNone && - ps.msgs[msg.Topic] != nil && ps.msgs[msg.Topic][msg.Partition] != nil && - ps.msgs[msg.Topic][msg.Partition].bufferBytes+msg.byteSize() >= ps.parent.conf.Producer.MaxMessageBytes: - return true - // Would we overflow simply in number of messages? - case ps.parent.conf.Producer.Flush.MaxMessages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.MaxMessages: - return true - default: - return false - } -} - -func (ps *produceSet) readyToFlush() bool { - switch { - // If we don't have any messages, nothing else matters - case ps.empty(): - return false - // If all three config values are 0, we always flush as-fast-as-possible - case ps.parent.conf.Producer.Flush.Frequency == 0 && ps.parent.conf.Producer.Flush.Bytes == 0 && ps.parent.conf.Producer.Flush.Messages == 0: - return true - // If we've passed the message trigger-point - case ps.parent.conf.Producer.Flush.Messages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.Messages: - return true - // If we've passed the byte trigger-point - case ps.parent.conf.Producer.Flush.Bytes > 0 && ps.bufferBytes >= ps.parent.conf.Producer.Flush.Bytes: - return true - default: - return false - } -} - -func (ps *produceSet) empty() bool { - return ps.bufferCount == 0 -} diff --git a/vendor/github.com/Shopify/sarama/real_decoder.go b/vendor/github.com/Shopify/sarama/real_decoder.go deleted file mode 100644 index 3cf93533a..000000000 --- a/vendor/github.com/Shopify/sarama/real_decoder.go +++ /dev/null @@ -1,260 +0,0 @@ -package sarama - -import ( - "encoding/binary" - "math" -) - -var errInvalidArrayLength = PacketDecodingError{"invalid array length"} -var errInvalidByteSliceLength = PacketDecodingError{"invalid byteslice length"} -var errInvalidStringLength = PacketDecodingError{"invalid string length"} -var errInvalidSubsetSize = PacketDecodingError{"invalid subset size"} - -type realDecoder struct { - raw []byte - off int - stack []pushDecoder -} - -// primitives - -func (rd *realDecoder) getInt8() (int8, error) { - if rd.remaining() < 1 { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } - tmp := int8(rd.raw[rd.off]) - rd.off++ - return tmp, nil -} - -func (rd *realDecoder) getInt16() (int16, error) { - if rd.remaining() < 2 { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } - tmp := int16(binary.BigEndian.Uint16(rd.raw[rd.off:])) - rd.off += 2 - return tmp, nil -} - -func (rd *realDecoder) getInt32() (int32, error) { - if rd.remaining() < 4 { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } - tmp := int32(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - return tmp, nil -} - -func (rd *realDecoder) getInt64() (int64, error) { - if rd.remaining() < 8 { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } - tmp := int64(binary.BigEndian.Uint64(rd.raw[rd.off:])) - rd.off += 8 - return tmp, nil -} - -func (rd *realDecoder) getArrayLength() (int, error) { - if rd.remaining() < 4 { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } - tmp := int(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - if tmp > rd.remaining() { - rd.off = len(rd.raw) - return -1, ErrInsufficientData - } else if tmp > 2*math.MaxUint16 { - return -1, errInvalidArrayLength - } - return tmp, nil -} - -// collections - -func (rd *realDecoder) getBytes() ([]byte, error) { - tmp, err := rd.getInt32() - - if err != nil { - return nil, err - } - - n := int(tmp) - - switch { - case n < -1: - return nil, errInvalidByteSliceLength - case n == -1: - return nil, nil - case n == 0: - return make([]byte, 0), nil - case n > rd.remaining(): - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - - tmpStr := rd.raw[rd.off : rd.off+n] - rd.off += n - return tmpStr, nil -} - -func (rd *realDecoder) getString() (string, error) { - tmp, err := rd.getInt16() - - if err != nil { - return "", err - } - - n := int(tmp) - - switch { - case n < -1: - return "", errInvalidStringLength - case n == -1: - return "", nil - case n == 0: - return "", nil - case n > rd.remaining(): - rd.off = len(rd.raw) - return "", ErrInsufficientData - } - - tmpStr := string(rd.raw[rd.off : rd.off+n]) - rd.off += n - return tmpStr, nil -} - -func (rd *realDecoder) getInt32Array() ([]int32, error) { - if rd.remaining() < 4 { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - n := int(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - - if rd.remaining() < 4*n { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - - if n == 0 { - return nil, nil - } - - if n < 0 { - return nil, errInvalidArrayLength - } - - ret := make([]int32, n) - for i := range ret { - ret[i] = int32(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - } - return ret, nil -} - -func (rd *realDecoder) getInt64Array() ([]int64, error) { - if rd.remaining() < 4 { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - n := int(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - - if rd.remaining() < 8*n { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - - if n == 0 { - return nil, nil - } - - if n < 0 { - return nil, errInvalidArrayLength - } - - ret := make([]int64, n) - for i := range ret { - ret[i] = int64(binary.BigEndian.Uint64(rd.raw[rd.off:])) - rd.off += 8 - } - return ret, nil -} - -func (rd *realDecoder) getStringArray() ([]string, error) { - if rd.remaining() < 4 { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - n := int(binary.BigEndian.Uint32(rd.raw[rd.off:])) - rd.off += 4 - - if n == 0 { - return nil, nil - } - - if n < 0 { - return nil, errInvalidArrayLength - } - - ret := make([]string, n) - for i := range ret { - str, err := rd.getString() - if err != nil { - return nil, err - } - - ret[i] = str - } - return ret, nil -} - -// subsets - -func (rd *realDecoder) remaining() int { - return len(rd.raw) - rd.off -} - -func (rd *realDecoder) getSubset(length int) (packetDecoder, error) { - if length < 0 { - return nil, errInvalidSubsetSize - } else if length > rd.remaining() { - rd.off = len(rd.raw) - return nil, ErrInsufficientData - } - - start := rd.off - rd.off += length - return &realDecoder{raw: rd.raw[start:rd.off]}, nil -} - -// stacks - -func (rd *realDecoder) push(in pushDecoder) error { - in.saveOffset(rd.off) - - reserve := in.reserveLength() - if rd.remaining() < reserve { - rd.off = len(rd.raw) - return ErrInsufficientData - } - - rd.stack = append(rd.stack, in) - - rd.off += reserve - - return nil -} - -func (rd *realDecoder) pop() error { - // this is go's ugly pop pattern (the inverse of append) - in := rd.stack[len(rd.stack)-1] - rd.stack = rd.stack[:len(rd.stack)-1] - - return in.check(rd.off, rd.raw) -} diff --git a/vendor/github.com/Shopify/sarama/real_encoder.go b/vendor/github.com/Shopify/sarama/real_encoder.go deleted file mode 100644 index ced4267c3..000000000 --- a/vendor/github.com/Shopify/sarama/real_encoder.go +++ /dev/null @@ -1,129 +0,0 @@ -package sarama - -import ( - "encoding/binary" - - "github.com/rcrowley/go-metrics" -) - -type realEncoder struct { - raw []byte - off int - stack []pushEncoder - registry metrics.Registry -} - -// primitives - -func (re *realEncoder) putInt8(in int8) { - re.raw[re.off] = byte(in) - re.off++ -} - -func (re *realEncoder) putInt16(in int16) { - binary.BigEndian.PutUint16(re.raw[re.off:], uint16(in)) - re.off += 2 -} - -func (re *realEncoder) putInt32(in int32) { - binary.BigEndian.PutUint32(re.raw[re.off:], uint32(in)) - re.off += 4 -} - -func (re *realEncoder) putInt64(in int64) { - binary.BigEndian.PutUint64(re.raw[re.off:], uint64(in)) - re.off += 8 -} - -func (re *realEncoder) putArrayLength(in int) error { - re.putInt32(int32(in)) - return nil -} - -// collection - -func (re *realEncoder) putRawBytes(in []byte) error { - copy(re.raw[re.off:], in) - re.off += len(in) - return nil -} - -func (re *realEncoder) putBytes(in []byte) error { - if in == nil { - re.putInt32(-1) - return nil - } - re.putInt32(int32(len(in))) - copy(re.raw[re.off:], in) - re.off += len(in) - return nil -} - -func (re *realEncoder) putString(in string) error { - re.putInt16(int16(len(in))) - copy(re.raw[re.off:], in) - re.off += len(in) - return nil -} - -func (re *realEncoder) putStringArray(in []string) error { - err := re.putArrayLength(len(in)) - if err != nil { - return err - } - - for _, val := range in { - if err := re.putString(val); err != nil { - return err - } - } - - return nil -} - -func (re *realEncoder) putInt32Array(in []int32) error { - err := re.putArrayLength(len(in)) - if err != nil { - return err - } - for _, val := range in { - re.putInt32(val) - } - return nil -} - -func (re *realEncoder) putInt64Array(in []int64) error { - err := re.putArrayLength(len(in)) - if err != nil { - return err - } - for _, val := range in { - re.putInt64(val) - } - return nil -} - -func (re *realEncoder) offset() int { - return re.off -} - -// stacks - -func (re *realEncoder) push(in pushEncoder) { - in.saveOffset(re.off) - re.off += in.reserveLength() - re.stack = append(re.stack, in) -} - -func (re *realEncoder) pop() error { - // this is go's ugly pop pattern (the inverse of append) - in := re.stack[len(re.stack)-1] - re.stack = re.stack[:len(re.stack)-1] - - return in.run(re.off, re.raw) -} - -// we do record metrics during the real encoder pass -func (re *realEncoder) metricRegistry() metrics.Registry { - return re.registry -} diff --git a/vendor/github.com/Shopify/sarama/request.go b/vendor/github.com/Shopify/sarama/request.go deleted file mode 100644 index 73310ca87..000000000 --- a/vendor/github.com/Shopify/sarama/request.go +++ /dev/null @@ -1,119 +0,0 @@ -package sarama - -import ( - "encoding/binary" - "fmt" - "io" -) - -type protocolBody interface { - encoder - versionedDecoder - key() int16 - version() int16 - requiredVersion() KafkaVersion -} - -type request struct { - correlationID int32 - clientID string - body protocolBody -} - -func (r *request) encode(pe packetEncoder) (err error) { - pe.push(&lengthField{}) - pe.putInt16(r.body.key()) - pe.putInt16(r.body.version()) - pe.putInt32(r.correlationID) - err = pe.putString(r.clientID) - if err != nil { - return err - } - err = r.body.encode(pe) - if err != nil { - return err - } - return pe.pop() -} - -func (r *request) decode(pd packetDecoder) (err error) { - var key int16 - if key, err = pd.getInt16(); err != nil { - return err - } - var version int16 - if version, err = pd.getInt16(); err != nil { - return err - } - if r.correlationID, err = pd.getInt32(); err != nil { - return err - } - r.clientID, err = pd.getString() - - r.body = allocateBody(key, version) - if r.body == nil { - return PacketDecodingError{fmt.Sprintf("unknown request key (%d)", key)} - } - return r.body.decode(pd, version) -} - -func decodeRequest(r io.Reader) (req *request, bytesRead int, err error) { - lengthBytes := make([]byte, 4) - if _, err := io.ReadFull(r, lengthBytes); err != nil { - return nil, bytesRead, err - } - bytesRead += len(lengthBytes) - - length := int32(binary.BigEndian.Uint32(lengthBytes)) - if length <= 4 || length > MaxRequestSize { - return nil, bytesRead, PacketDecodingError{fmt.Sprintf("message of length %d too large or too small", length)} - } - - encodedReq := make([]byte, length) - if _, err := io.ReadFull(r, encodedReq); err != nil { - return nil, bytesRead, err - } - bytesRead += len(encodedReq) - - req = &request{} - if err := decode(encodedReq, req); err != nil { - return nil, bytesRead, err - } - return req, bytesRead, nil -} - -func allocateBody(key, version int16) protocolBody { - switch key { - case 0: - return &ProduceRequest{} - case 1: - return &FetchRequest{} - case 2: - return &OffsetRequest{Version: version} - case 3: - return &MetadataRequest{} - case 8: - return &OffsetCommitRequest{Version: version} - case 9: - return &OffsetFetchRequest{} - case 10: - return &ConsumerMetadataRequest{} - case 11: - return &JoinGroupRequest{} - case 12: - return &HeartbeatRequest{} - case 13: - return &LeaveGroupRequest{} - case 14: - return &SyncGroupRequest{} - case 15: - return &DescribeGroupsRequest{} - case 16: - return &ListGroupsRequest{} - case 17: - return &SaslHandshakeRequest{} - case 18: - return &ApiVersionsRequest{} - } - return nil -} diff --git a/vendor/github.com/Shopify/sarama/response_header.go b/vendor/github.com/Shopify/sarama/response_header.go deleted file mode 100644 index f3f4d27d6..000000000 --- a/vendor/github.com/Shopify/sarama/response_header.go +++ /dev/null @@ -1,21 +0,0 @@ -package sarama - -import "fmt" - -type responseHeader struct { - length int32 - correlationID int32 -} - -func (r *responseHeader) decode(pd packetDecoder) (err error) { - r.length, err = pd.getInt32() - if err != nil { - return err - } - if r.length <= 4 || r.length > MaxResponseSize { - return PacketDecodingError{fmt.Sprintf("message of length %d too large or too small", r.length)} - } - - r.correlationID, err = pd.getInt32() - return err -} diff --git a/vendor/github.com/Shopify/sarama/sarama.go b/vendor/github.com/Shopify/sarama/sarama.go deleted file mode 100644 index 7d5dc60d3..000000000 --- a/vendor/github.com/Shopify/sarama/sarama.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Package sarama is a pure Go client library for dealing with Apache Kafka (versions 0.8 and later). It includes a high-level -API for easily producing and consuming messages, and a low-level API for controlling bytes on the wire when the high-level -API is insufficient. Usage examples for the high-level APIs are provided inline with their full documentation. - -To produce messages, use either the AsyncProducer or the SyncProducer. The AsyncProducer accepts messages on a channel -and produces them asynchronously in the background as efficiently as possible; it is preferred in most cases. -The SyncProducer provides a method which will block until Kafka acknowledges the message as produced. This can be -useful but comes with two caveats: it will generally be less efficient, and the actual durability guarantees -depend on the configured value of `Producer.RequiredAcks`. There are configurations where a message acknowledged by the -SyncProducer can still sometimes be lost. - -To consume messages, use the Consumer. Note that Sarama's Consumer implementation does not currently support automatic -consumer-group rebalancing and offset tracking. For Zookeeper-based tracking (Kafka 0.8.2 and earlier), the -https://github.com/wvanbergen/kafka library builds on Sarama to add this support. For Kafka-based tracking (Kafka 0.9 -and later), the https://github.com/bsm/sarama-cluster library builds on Sarama to add this support. - -For lower-level needs, the Broker and Request/Response objects permit precise control over each connection -and message sent on the wire; the Client provides higher-level metadata management that is shared between -the producers and the consumer. The Request/Response objects and properties are mostly undocumented, as they line up -exactly with the protocol fields documented by Kafka at -https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol - -Metrics are exposed through https://github.com/rcrowley/go-metrics library in a local registry. - -Broker related metrics: - - +----------------------------------------------+------------+---------------------------------------------------------------+ - | Name | Type | Description | - +----------------------------------------------+------------+---------------------------------------------------------------+ - | incoming-byte-rate | meter | Bytes/second read off all brokers | - | incoming-byte-rate-for-broker- | meter | Bytes/second read off a given broker | - | outgoing-byte-rate | meter | Bytes/second written off all brokers | - | outgoing-byte-rate-for-broker- | meter | Bytes/second written off a given broker | - | request-rate | meter | Requests/second sent to all brokers | - | request-rate-for-broker- | meter | Requests/second sent to a given broker | - | request-size | histogram | Distribution of the request size in bytes for all brokers | - | request-size-for-broker- | histogram | Distribution of the request size in bytes for a given broker | - | request-latency-in-ms | histogram | Distribution of the request latency in ms for all brokers | - | request-latency-in-ms-for-broker- | histogram | Distribution of the request latency in ms for a given broker | - | response-rate | meter | Responses/second received from all brokers | - | response-rate-for-broker- | meter | Responses/second received from a given broker | - | response-size | histogram | Distribution of the response size in bytes for all brokers | - | response-size-for-broker- | histogram | Distribution of the response size in bytes for a given broker | - +----------------------------------------------+------------+---------------------------------------------------------------+ - -Note that we do not gather specific metrics for seed brokers but they are part of the "all brokers" metrics. - -Producer related metrics: - - +-------------------------------------------+------------+--------------------------------------------------------------------------------------+ - | Name | Type | Description | - +-------------------------------------------+------------+--------------------------------------------------------------------------------------+ - | batch-size | histogram | Distribution of the number of bytes sent per partition per request for all topics | - | batch-size-for-topic- | histogram | Distribution of the number of bytes sent per partition per request for a given topic | - | record-send-rate | meter | Records/second sent to all topics | - | record-send-rate-for-topic- | meter | Records/second sent to a given topic | - | records-per-request | histogram | Distribution of the number of records sent per request for all topics | - | records-per-request-for-topic- | histogram | Distribution of the number of records sent per request for a given topic | - | compression-ratio | histogram | Distribution of the compression ratio times 100 of record batches for all topics | - | compression-ratio-for-topic- | histogram | Distribution of the compression ratio times 100 of record batches for a given topic | - +-------------------------------------------+------------+--------------------------------------------------------------------------------------+ - -*/ -package sarama - -import ( - "io/ioutil" - "log" -) - -// Logger is the instance of a StdLogger interface that Sarama writes connection -// management events to. By default it is set to discard all log messages via ioutil.Discard, -// but you can set it to redirect wherever you want. -var Logger StdLogger = log.New(ioutil.Discard, "[Sarama] ", log.LstdFlags) - -// StdLogger is used to log error messages. -type StdLogger interface { - Print(v ...interface{}) - Printf(format string, v ...interface{}) - Println(v ...interface{}) -} - -// PanicHandler is called for recovering from panics spawned internally to the library (and thus -// not recoverable by the caller's goroutine). Defaults to nil, which means panics are not recovered. -var PanicHandler func(interface{}) - -// MaxRequestSize is the maximum size (in bytes) of any request that Sarama will attempt to send. Trying -// to send a request larger than this will result in an PacketEncodingError. The default of 100 MiB is aligned -// with Kafka's default `socket.request.max.bytes`, which is the largest request the broker will attempt -// to process. -var MaxRequestSize int32 = 100 * 1024 * 1024 - -// MaxResponseSize is the maximum size (in bytes) of any response that Sarama will attempt to parse. If -// a broker returns a response message larger than this value, Sarama will return a PacketDecodingError to -// protect the client from running out of memory. Please note that brokers do not have any natural limit on -// the size of responses they send. In particular, they can send arbitrarily large fetch responses to consumers -// (see https://issues.apache.org/jira/browse/KAFKA-2063). -var MaxResponseSize int32 = 100 * 1024 * 1024 diff --git a/vendor/github.com/Shopify/sarama/sasl_handshake_request.go b/vendor/github.com/Shopify/sarama/sasl_handshake_request.go deleted file mode 100644 index fbbc8947b..000000000 --- a/vendor/github.com/Shopify/sarama/sasl_handshake_request.go +++ /dev/null @@ -1,33 +0,0 @@ -package sarama - -type SaslHandshakeRequest struct { - Mechanism string -} - -func (r *SaslHandshakeRequest) encode(pe packetEncoder) error { - if err := pe.putString(r.Mechanism); err != nil { - return err - } - - return nil -} - -func (r *SaslHandshakeRequest) decode(pd packetDecoder, version int16) (err error) { - if r.Mechanism, err = pd.getString(); err != nil { - return err - } - - return nil -} - -func (r *SaslHandshakeRequest) key() int16 { - return 17 -} - -func (r *SaslHandshakeRequest) version() int16 { - return 0 -} - -func (r *SaslHandshakeRequest) requiredVersion() KafkaVersion { - return V0_10_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/sasl_handshake_response.go b/vendor/github.com/Shopify/sarama/sasl_handshake_response.go deleted file mode 100644 index ef290d4bc..000000000 --- a/vendor/github.com/Shopify/sarama/sasl_handshake_response.go +++ /dev/null @@ -1,38 +0,0 @@ -package sarama - -type SaslHandshakeResponse struct { - Err KError - EnabledMechanisms []string -} - -func (r *SaslHandshakeResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - return pe.putStringArray(r.EnabledMechanisms) -} - -func (r *SaslHandshakeResponse) decode(pd packetDecoder, version int16) error { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - r.Err = KError(kerr) - - if r.EnabledMechanisms, err = pd.getStringArray(); err != nil { - return err - } - - return nil -} - -func (r *SaslHandshakeResponse) key() int16 { - return 17 -} - -func (r *SaslHandshakeResponse) version() int16 { - return 0 -} - -func (r *SaslHandshakeResponse) requiredVersion() KafkaVersion { - return V0_10_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/sync_group_request.go b/vendor/github.com/Shopify/sarama/sync_group_request.go deleted file mode 100644 index fe207080e..000000000 --- a/vendor/github.com/Shopify/sarama/sync_group_request.go +++ /dev/null @@ -1,100 +0,0 @@ -package sarama - -type SyncGroupRequest struct { - GroupId string - GenerationId int32 - MemberId string - GroupAssignments map[string][]byte -} - -func (r *SyncGroupRequest) encode(pe packetEncoder) error { - if err := pe.putString(r.GroupId); err != nil { - return err - } - - pe.putInt32(r.GenerationId) - - if err := pe.putString(r.MemberId); err != nil { - return err - } - - if err := pe.putArrayLength(len(r.GroupAssignments)); err != nil { - return err - } - for memberId, memberAssignment := range r.GroupAssignments { - if err := pe.putString(memberId); err != nil { - return err - } - if err := pe.putBytes(memberAssignment); err != nil { - return err - } - } - - return nil -} - -func (r *SyncGroupRequest) decode(pd packetDecoder, version int16) (err error) { - if r.GroupId, err = pd.getString(); err != nil { - return - } - if r.GenerationId, err = pd.getInt32(); err != nil { - return - } - if r.MemberId, err = pd.getString(); err != nil { - return - } - - n, err := pd.getArrayLength() - if err != nil { - return err - } - if n == 0 { - return nil - } - - r.GroupAssignments = make(map[string][]byte) - for i := 0; i < n; i++ { - memberId, err := pd.getString() - if err != nil { - return err - } - memberAssignment, err := pd.getBytes() - if err != nil { - return err - } - - r.GroupAssignments[memberId] = memberAssignment - } - - return nil -} - -func (r *SyncGroupRequest) key() int16 { - return 14 -} - -func (r *SyncGroupRequest) version() int16 { - return 0 -} - -func (r *SyncGroupRequest) requiredVersion() KafkaVersion { - return V0_9_0_0 -} - -func (r *SyncGroupRequest) AddGroupAssignment(memberId string, memberAssignment []byte) { - if r.GroupAssignments == nil { - r.GroupAssignments = make(map[string][]byte) - } - - r.GroupAssignments[memberId] = memberAssignment -} - -func (r *SyncGroupRequest) AddGroupAssignmentMember(memberId string, memberAssignment *ConsumerGroupMemberAssignment) error { - bin, err := encode(memberAssignment, nil) - if err != nil { - return err - } - - r.AddGroupAssignment(memberId, bin) - return nil -} diff --git a/vendor/github.com/Shopify/sarama/sync_group_response.go b/vendor/github.com/Shopify/sarama/sync_group_response.go deleted file mode 100644 index 194b382b4..000000000 --- a/vendor/github.com/Shopify/sarama/sync_group_response.go +++ /dev/null @@ -1,41 +0,0 @@ -package sarama - -type SyncGroupResponse struct { - Err KError - MemberAssignment []byte -} - -func (r *SyncGroupResponse) GetMemberAssignment() (*ConsumerGroupMemberAssignment, error) { - assignment := new(ConsumerGroupMemberAssignment) - err := decode(r.MemberAssignment, assignment) - return assignment, err -} - -func (r *SyncGroupResponse) encode(pe packetEncoder) error { - pe.putInt16(int16(r.Err)) - return pe.putBytes(r.MemberAssignment) -} - -func (r *SyncGroupResponse) decode(pd packetDecoder, version int16) (err error) { - kerr, err := pd.getInt16() - if err != nil { - return err - } - - r.Err = KError(kerr) - - r.MemberAssignment, err = pd.getBytes() - return -} - -func (r *SyncGroupResponse) key() int16 { - return 14 -} - -func (r *SyncGroupResponse) version() int16 { - return 0 -} - -func (r *SyncGroupResponse) requiredVersion() KafkaVersion { - return V0_9_0_0 -} diff --git a/vendor/github.com/Shopify/sarama/sync_producer.go b/vendor/github.com/Shopify/sarama/sync_producer.go deleted file mode 100644 index dd096b6db..000000000 --- a/vendor/github.com/Shopify/sarama/sync_producer.go +++ /dev/null @@ -1,164 +0,0 @@ -package sarama - -import "sync" - -// SyncProducer publishes Kafka messages, blocking until they have been acknowledged. It routes messages to the correct -// broker, refreshing metadata as appropriate, and parses responses for errors. You must call Close() on a producer -// to avoid leaks, it may not be garbage-collected automatically when it passes out of scope. -// -// The SyncProducer comes with two caveats: it will generally be less efficient than the AsyncProducer, and the actual -// durability guarantee provided when a message is acknowledged depend on the configured value of `Producer.RequiredAcks`. -// There are configurations where a message acknowledged by the SyncProducer can still sometimes be lost. -// -// For implementation reasons, the SyncProducer requires `Producer.Return.Errors` and `Producer.Return.Successes` to -// be set to true in its configuration. -type SyncProducer interface { - - // SendMessage produces a given message, and returns only when it either has - // succeeded or failed to produce. It will return the partition and the offset - // of the produced message, or an error if the message failed to produce. - SendMessage(msg *ProducerMessage) (partition int32, offset int64, err error) - - // SendMessages produces a given set of messages, and returns only when all - // messages in the set have either succeeded or failed. Note that messages - // can succeed and fail individually; if some succeed and some fail, - // SendMessages will return an error. - SendMessages(msgs []*ProducerMessage) error - - // Close shuts down the producer and waits for any buffered messages to be - // flushed. You must call this function before a producer object passes out of - // scope, as it may otherwise leak memory. You must call this before calling - // Close on the underlying client. - Close() error -} - -type syncProducer struct { - producer *asyncProducer - wg sync.WaitGroup -} - -// NewSyncProducer creates a new SyncProducer using the given broker addresses and configuration. -func NewSyncProducer(addrs []string, config *Config) (SyncProducer, error) { - if config == nil { - config = NewConfig() - config.Producer.Return.Successes = true - } - - if err := verifyProducerConfig(config); err != nil { - return nil, err - } - - p, err := NewAsyncProducer(addrs, config) - if err != nil { - return nil, err - } - return newSyncProducerFromAsyncProducer(p.(*asyncProducer)), nil -} - -// NewSyncProducerFromClient creates a new SyncProducer using the given client. It is still -// necessary to call Close() on the underlying client when shutting down this producer. -func NewSyncProducerFromClient(client Client) (SyncProducer, error) { - if err := verifyProducerConfig(client.Config()); err != nil { - return nil, err - } - - p, err := NewAsyncProducerFromClient(client) - if err != nil { - return nil, err - } - return newSyncProducerFromAsyncProducer(p.(*asyncProducer)), nil -} - -func newSyncProducerFromAsyncProducer(p *asyncProducer) *syncProducer { - sp := &syncProducer{producer: p} - - sp.wg.Add(2) - go withRecover(sp.handleSuccesses) - go withRecover(sp.handleErrors) - - return sp -} - -func verifyProducerConfig(config *Config) error { - if !config.Producer.Return.Errors { - return ConfigurationError("Producer.Return.Errors must be true to be used in a SyncProducer") - } - if !config.Producer.Return.Successes { - return ConfigurationError("Producer.Return.Successes must be true to be used in a SyncProducer") - } - return nil -} - -func (sp *syncProducer) SendMessage(msg *ProducerMessage) (partition int32, offset int64, err error) { - oldMetadata := msg.Metadata - defer func() { - msg.Metadata = oldMetadata - }() - - expectation := make(chan *ProducerError, 1) - msg.Metadata = expectation - sp.producer.Input() <- msg - - if err := <-expectation; err != nil { - return -1, -1, err.Err - } - - return msg.Partition, msg.Offset, nil -} - -func (sp *syncProducer) SendMessages(msgs []*ProducerMessage) error { - savedMetadata := make([]interface{}, len(msgs)) - for i := range msgs { - savedMetadata[i] = msgs[i].Metadata - } - defer func() { - for i := range msgs { - msgs[i].Metadata = savedMetadata[i] - } - }() - - expectations := make(chan chan *ProducerError, len(msgs)) - go func() { - for _, msg := range msgs { - expectation := make(chan *ProducerError, 1) - msg.Metadata = expectation - sp.producer.Input() <- msg - expectations <- expectation - } - close(expectations) - }() - - var errors ProducerErrors - for expectation := range expectations { - if err := <-expectation; err != nil { - errors = append(errors, err) - } - } - - if len(errors) > 0 { - return errors - } - return nil -} - -func (sp *syncProducer) handleSuccesses() { - defer sp.wg.Done() - for msg := range sp.producer.Successes() { - expectation := msg.Metadata.(chan *ProducerError) - expectation <- nil - } -} - -func (sp *syncProducer) handleErrors() { - defer sp.wg.Done() - for err := range sp.producer.Errors() { - expectation := err.Msg.Metadata.(chan *ProducerError) - expectation <- err - } -} - -func (sp *syncProducer) Close() error { - sp.producer.AsyncClose() - sp.wg.Wait() - return nil -} diff --git a/vendor/github.com/Shopify/sarama/utils.go b/vendor/github.com/Shopify/sarama/utils.go deleted file mode 100644 index dc0e7e947..000000000 --- a/vendor/github.com/Shopify/sarama/utils.go +++ /dev/null @@ -1,150 +0,0 @@ -package sarama - -import ( - "bufio" - "net" -) - -type none struct{} - -// make []int32 sortable so we can sort partition numbers -type int32Slice []int32 - -func (slice int32Slice) Len() int { - return len(slice) -} - -func (slice int32Slice) Less(i, j int) bool { - return slice[i] < slice[j] -} - -func (slice int32Slice) Swap(i, j int) { - slice[i], slice[j] = slice[j], slice[i] -} - -func dupInt32Slice(input []int32) []int32 { - ret := make([]int32, 0, len(input)) - for _, val := range input { - ret = append(ret, val) - } - return ret -} - -func withRecover(fn func()) { - defer func() { - handler := PanicHandler - if handler != nil { - if err := recover(); err != nil { - handler(err) - } - } - }() - - fn() -} - -func safeAsyncClose(b *Broker) { - tmp := b // local var prevents clobbering in goroutine - go withRecover(func() { - if connected, _ := tmp.Connected(); connected { - if err := tmp.Close(); err != nil { - Logger.Println("Error closing broker", tmp.ID(), ":", err) - } - } - }) -} - -// Encoder is a simple interface for any type that can be encoded as an array of bytes -// in order to be sent as the key or value of a Kafka message. Length() is provided as an -// optimization, and must return the same as len() on the result of Encode(). -type Encoder interface { - Encode() ([]byte, error) - Length() int -} - -// make strings and byte slices encodable for convenience so they can be used as keys -// and/or values in kafka messages - -// StringEncoder implements the Encoder interface for Go strings so that they can be used -// as the Key or Value in a ProducerMessage. -type StringEncoder string - -func (s StringEncoder) Encode() ([]byte, error) { - return []byte(s), nil -} - -func (s StringEncoder) Length() int { - return len(s) -} - -// ByteEncoder implements the Encoder interface for Go byte slices so that they can be used -// as the Key or Value in a ProducerMessage. -type ByteEncoder []byte - -func (b ByteEncoder) Encode() ([]byte, error) { - return b, nil -} - -func (b ByteEncoder) Length() int { - return len(b) -} - -// bufConn wraps a net.Conn with a buffer for reads to reduce the number of -// reads that trigger syscalls. -type bufConn struct { - net.Conn - buf *bufio.Reader -} - -func newBufConn(conn net.Conn) *bufConn { - return &bufConn{ - Conn: conn, - buf: bufio.NewReader(conn), - } -} - -func (bc *bufConn) Read(b []byte) (n int, err error) { - return bc.buf.Read(b) -} - -// KafkaVersion instances represent versions of the upstream Kafka broker. -type KafkaVersion struct { - // it's a struct rather than just typing the array directly to make it opaque and stop people - // generating their own arbitrary versions - version [4]uint -} - -func newKafkaVersion(major, minor, veryMinor, patch uint) KafkaVersion { - return KafkaVersion{ - version: [4]uint{major, minor, veryMinor, patch}, - } -} - -// IsAtLeast return true if and only if the version it is called on is -// greater than or equal to the version passed in: -// V1.IsAtLeast(V2) // false -// V2.IsAtLeast(V1) // true -func (v KafkaVersion) IsAtLeast(other KafkaVersion) bool { - for i := range v.version { - if v.version[i] > other.version[i] { - return true - } else if v.version[i] < other.version[i] { - return false - } - } - return true -} - -// Effective constants defining the supported kafka versions. -var ( - V0_8_2_0 = newKafkaVersion(0, 8, 2, 0) - V0_8_2_1 = newKafkaVersion(0, 8, 2, 1) - V0_8_2_2 = newKafkaVersion(0, 8, 2, 2) - V0_9_0_0 = newKafkaVersion(0, 9, 0, 0) - V0_9_0_1 = newKafkaVersion(0, 9, 0, 1) - V0_10_0_0 = newKafkaVersion(0, 10, 0, 0) - V0_10_0_1 = newKafkaVersion(0, 10, 0, 1) - V0_10_1_0 = newKafkaVersion(0, 10, 1, 0) - V0_10_2_0 = newKafkaVersion(0, 10, 2, 0) - minVersion = V0_8_2_0 -) diff --git a/vendor/github.com/VividCortex/gohistogram/LICENSE b/vendor/github.com/VividCortex/gohistogram/LICENSE deleted file mode 100644 index d23fea365..000000000 --- a/vendor/github.com/VividCortex/gohistogram/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2013 VividCortex - -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/VividCortex/gohistogram/histogram.go b/vendor/github.com/VividCortex/gohistogram/histogram.go deleted file mode 100644 index ede21fd31..000000000 --- a/vendor/github.com/VividCortex/gohistogram/histogram.go +++ /dev/null @@ -1,23 +0,0 @@ -package gohistogram - -// Copyright (c) 2013 VividCortex, Inc. All rights reserved. -// Please see the LICENSE file for applicable license terms. - -// Histogram is the interface that wraps the Add and Quantile methods. -type Histogram interface { - // Add adds a new value, n, to the histogram. Trimming is done - // automatically. - Add(n float64) - - // Quantile returns an approximation. - Quantile(n float64) (q float64) - - // String returns a string reprentation of the histogram, - // which is useful for printing to a terminal. - String() (str string) -} - -type bin struct { - value float64 - count float64 -} diff --git a/vendor/github.com/VividCortex/gohistogram/numerichistogram.go b/vendor/github.com/VividCortex/gohistogram/numerichistogram.go deleted file mode 100644 index 20dea740d..000000000 --- a/vendor/github.com/VividCortex/gohistogram/numerichistogram.go +++ /dev/null @@ -1,160 +0,0 @@ -package gohistogram - -// Copyright (c) 2013 VividCortex, Inc. All rights reserved. -// Please see the LICENSE file for applicable license terms. - -import ( - "fmt" -) - -type NumericHistogram struct { - bins []bin - maxbins int - total uint64 -} - -// NewHistogram returns a new NumericHistogram with a maximum of n bins. -// -// There is no "optimal" bin count, but somewhere between 20 and 80 bins -// should be sufficient. -func NewHistogram(n int) *NumericHistogram { - return &NumericHistogram{ - bins: make([]bin, 0), - maxbins: n, - total: 0, - } -} - -func (h *NumericHistogram) Add(n float64) { - defer h.trim() - h.total++ - for i := range h.bins { - if h.bins[i].value == n { - h.bins[i].count++ - return - } - - if h.bins[i].value > n { - - newbin := bin{value: n, count: 1} - head := append(make([]bin, 0), h.bins[0:i]...) - - head = append(head, newbin) - tail := h.bins[i:] - h.bins = append(head, tail...) - return - } - } - - h.bins = append(h.bins, bin{count: 1, value: n}) -} - -func (h *NumericHistogram) Quantile(q float64) float64 { - count := q * float64(h.total) - for i := range h.bins { - count -= float64(h.bins[i].count) - - if count <= 0 { - return h.bins[i].value - } - } - - return -1 -} - -// CDF returns the value of the cumulative distribution function -// at x -func (h *NumericHistogram) CDF(x float64) float64 { - count := 0.0 - for i := range h.bins { - if h.bins[i].value <= x { - count += float64(h.bins[i].count) - } - } - - return count / float64(h.total) -} - -// Mean returns the sample mean of the distribution -func (h *NumericHistogram) Mean() float64 { - if h.total == 0 { - return 0 - } - - sum := 0.0 - - for i := range h.bins { - sum += h.bins[i].value * h.bins[i].count - } - - return sum / float64(h.total) -} - -// Variance returns the variance of the distribution -func (h *NumericHistogram) Variance() float64 { - if h.total == 0 { - return 0 - } - - sum := 0.0 - mean := h.Mean() - - for i := range h.bins { - sum += (h.bins[i].count * (h.bins[i].value - mean) * (h.bins[i].value - mean)) - } - - return sum / float64(h.total) -} - -func (h *NumericHistogram) Count() float64 { - return float64(h.total) -} - -// trim merges adjacent bins to decrease the bin count to the maximum value -func (h *NumericHistogram) trim() { - for len(h.bins) > h.maxbins { - // Find closest bins in terms of value - minDelta := 1e99 - minDeltaIndex := 0 - for i := range h.bins { - if i == 0 { - continue - } - - if delta := h.bins[i].value - h.bins[i-1].value; delta < minDelta { - minDelta = delta - minDeltaIndex = i - } - } - - // We need to merge bins minDeltaIndex-1 and minDeltaIndex - totalCount := h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].count - mergedbin := bin{ - value: (h.bins[minDeltaIndex-1].value* - h.bins[minDeltaIndex-1].count + - h.bins[minDeltaIndex].value* - h.bins[minDeltaIndex].count) / - totalCount, // weighted average - count: totalCount, // summed heights - } - head := append(make([]bin, 0), h.bins[0:minDeltaIndex-1]...) - tail := append([]bin{mergedbin}, h.bins[minDeltaIndex+1:]...) - h.bins = append(head, tail...) - } -} - -// String returns a string reprentation of the histogram, -// which is useful for printing to a terminal. -func (h *NumericHistogram) String() (str string) { - str += fmt.Sprintln("Total:", h.total) - - for i := range h.bins { - var bar string - for j := 0; j < int(float64(h.bins[i].count)/float64(h.total)*200); j++ { - bar += "." - } - str += fmt.Sprintln(h.bins[i].value, "\t", bar) - } - - return -} diff --git a/vendor/github.com/VividCortex/gohistogram/weightedhistogram.go b/vendor/github.com/VividCortex/gohistogram/weightedhistogram.go deleted file mode 100644 index 16eed3719..000000000 --- a/vendor/github.com/VividCortex/gohistogram/weightedhistogram.go +++ /dev/null @@ -1,190 +0,0 @@ -// Package gohistogram contains implementations of weighted and exponential histograms. -package gohistogram - -// Copyright (c) 2013 VividCortex, Inc. All rights reserved. -// Please see the LICENSE file for applicable license terms. - -import "fmt" - -// A WeightedHistogram implements Histogram. A WeightedHistogram has bins that have values -// which are exponentially weighted moving averages. This allows you keep inserting large -// amounts of data into the histogram and approximate quantiles with recency factored in. -type WeightedHistogram struct { - bins []bin - maxbins int - total float64 - alpha float64 -} - -// NewWeightedHistogram returns a new WeightedHistogram with a maximum of n bins with a decay factor -// of alpha. -// -// There is no "optimal" bin count, but somewhere between 20 and 80 bins should be -// sufficient. -// -// Alpha should be set to 2 / (N+1), where N represents the average age of the moving window. -// For example, a 60-second window with an average age of 30 seconds would yield an -// alpha of 0.064516129. -func NewWeightedHistogram(n int, alpha float64) *WeightedHistogram { - return &WeightedHistogram{ - bins: make([]bin, 0), - maxbins: n, - total: 0, - alpha: alpha, - } -} - -func ewma(existingVal float64, newVal float64, alpha float64) (result float64) { - result = newVal*(1-alpha) + existingVal*alpha - return -} - -func (h *WeightedHistogram) scaleDown(except int) { - for i := range h.bins { - if i != except { - h.bins[i].count = ewma(h.bins[i].count, 0, h.alpha) - } - } -} - -func (h *WeightedHistogram) Add(n float64) { - defer h.trim() - for i := range h.bins { - if h.bins[i].value == n { - h.bins[i].count++ - - defer h.scaleDown(i) - return - } - - if h.bins[i].value > n { - - newbin := bin{value: n, count: 1} - head := append(make([]bin, 0), h.bins[0:i]...) - - head = append(head, newbin) - tail := h.bins[i:] - h.bins = append(head, tail...) - - defer h.scaleDown(i) - return - } - } - - h.bins = append(h.bins, bin{count: 1, value: n}) -} - -func (h *WeightedHistogram) Quantile(q float64) float64 { - count := q * h.total - for i := range h.bins { - count -= float64(h.bins[i].count) - - if count <= 0 { - return h.bins[i].value - } - } - - return -1 -} - -// CDF returns the value of the cumulative distribution function -// at x -func (h *WeightedHistogram) CDF(x float64) float64 { - count := 0.0 - for i := range h.bins { - if h.bins[i].value <= x { - count += float64(h.bins[i].count) - } - } - - return count / h.total -} - -// Mean returns the sample mean of the distribution -func (h *WeightedHistogram) Mean() float64 { - if h.total == 0 { - return 0 - } - - sum := 0.0 - - for i := range h.bins { - sum += h.bins[i].value * h.bins[i].count - } - - return sum / h.total -} - -// Variance returns the variance of the distribution -func (h *WeightedHistogram) Variance() float64 { - if h.total == 0 { - return 0 - } - - sum := 0.0 - mean := h.Mean() - - for i := range h.bins { - sum += (h.bins[i].count * (h.bins[i].value - mean) * (h.bins[i].value - mean)) - } - - return sum / h.total -} - -func (h *WeightedHistogram) Count() float64 { - return h.total -} - -func (h *WeightedHistogram) trim() { - total := 0.0 - for i := range h.bins { - total += h.bins[i].count - } - h.total = total - for len(h.bins) > h.maxbins { - - // Find closest bins in terms of value - minDelta := 1e99 - minDeltaIndex := 0 - for i := range h.bins { - if i == 0 { - continue - } - - if delta := h.bins[i].value - h.bins[i-1].value; delta < minDelta { - minDelta = delta - minDeltaIndex = i - } - } - - // We need to merge bins minDeltaIndex-1 and minDeltaIndex - totalCount := h.bins[minDeltaIndex-1].count + h.bins[minDeltaIndex].count - mergedbin := bin{ - value: (h.bins[minDeltaIndex-1].value* - h.bins[minDeltaIndex-1].count + - h.bins[minDeltaIndex].value* - h.bins[minDeltaIndex].count) / - totalCount, // weighted average - count: totalCount, // summed heights - } - head := append(make([]bin, 0), h.bins[0:minDeltaIndex-1]...) - tail := append([]bin{mergedbin}, h.bins[minDeltaIndex+1:]...) - h.bins = append(head, tail...) - } -} - -// String returns a string reprentation of the histogram, -// which is useful for printing to a terminal. -func (h *WeightedHistogram) String() (str string) { - str += fmt.Sprintln("Total:", h.total) - - for i := range h.bins { - var bar string - for j := 0; j < int(float64(h.bins[i].count)/float64(h.total)*200); j++ { - bar += "." - } - str += fmt.Sprintln(h.bins[i].value, "\t", bar) - } - - return -} diff --git a/vendor/github.com/abbot/go-http-auth/LICENSE b/vendor/github.com/abbot/go-http-auth/LICENSE deleted file mode 100644 index e454a5258..000000000 --- a/vendor/github.com/abbot/go-http-auth/LICENSE +++ /dev/null @@ -1,178 +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 - diff --git a/vendor/github.com/abbot/go-http-auth/auth.go b/vendor/github.com/abbot/go-http-auth/auth.go deleted file mode 100644 index 05ded165e..000000000 --- a/vendor/github.com/abbot/go-http-auth/auth.go +++ /dev/null @@ -1,109 +0,0 @@ -// Package auth is an implementation of HTTP Basic and HTTP Digest authentication. -package auth - -import ( - "net/http" - - "golang.org/x/net/context" -) - -/* - Request handlers must take AuthenticatedRequest instead of http.Request -*/ -type AuthenticatedRequest struct { - http.Request - /* - Authenticated user name. Current API implies that Username is - never empty, which means that authentication is always done - before calling the request handler. - */ - Username string -} - -/* - AuthenticatedHandlerFunc is like http.HandlerFunc, but takes - AuthenticatedRequest instead of http.Request -*/ -type AuthenticatedHandlerFunc func(http.ResponseWriter, *AuthenticatedRequest) - -/* - Authenticator wraps an AuthenticatedHandlerFunc with - authentication-checking code. - - Typical Authenticator usage is something like: - - authenticator := SomeAuthenticator(...) - http.HandleFunc("/", authenticator(my_handler)) - - Authenticator wrapper checks the user authentication and calls the - wrapped function only after authentication has succeeded. Otherwise, - it returns a handler which initiates the authentication procedure. -*/ -type Authenticator func(AuthenticatedHandlerFunc) http.HandlerFunc - -// Info contains authentication information for the request. -type Info struct { - // Authenticated is set to true when request was authenticated - // successfully, i.e. username and password passed in request did - // pass the check. - Authenticated bool - - // Username contains a user name passed in the request when - // Authenticated is true. It's value is undefined if Authenticated - // is false. - Username string - - // ResponseHeaders contains extra headers that must be set by server - // when sending back HTTP response. - ResponseHeaders http.Header -} - -// UpdateHeaders updates headers with this Info's ResponseHeaders. It is -// safe to call this function on nil Info. -func (i *Info) UpdateHeaders(headers http.Header) { - if i == nil { - return - } - for k, values := range i.ResponseHeaders { - for _, v := range values { - headers.Add(k, v) - } - } -} - -type key int // used for context keys - -var infoKey key = 0 - -type AuthenticatorInterface interface { - // NewContext returns a new context carrying authentication - // information extracted from the request. - NewContext(ctx context.Context, r *http.Request) context.Context - - // Wrap returns an http.HandlerFunc which wraps - // AuthenticatedHandlerFunc with this authenticator's - // authentication checks. - Wrap(AuthenticatedHandlerFunc) http.HandlerFunc -} - -// FromContext returns authentication information from the context or -// nil if no such information present. -func FromContext(ctx context.Context) *Info { - info, ok := ctx.Value(infoKey).(*Info) - if !ok { - return nil - } - return info -} - -// AuthUsernameHeader is the header set by JustCheck functions. It -// contains an authenticated username (if authentication was -// successful). -const AuthUsernameHeader = "X-Authenticated-Username" - -func JustCheck(auth AuthenticatorInterface, wrapped http.HandlerFunc) http.HandlerFunc { - return auth.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { - ar.Header.Set(AuthUsernameHeader, ar.Username) - wrapped(w, &ar.Request) - }) -} diff --git a/vendor/github.com/abbot/go-http-auth/basic.go b/vendor/github.com/abbot/go-http-auth/basic.go deleted file mode 100644 index b03dd5823..000000000 --- a/vendor/github.com/abbot/go-http-auth/basic.go +++ /dev/null @@ -1,163 +0,0 @@ -package auth - -import ( - "bytes" - "crypto/sha1" - "crypto/subtle" - "encoding/base64" - "errors" - "net/http" - "strings" - - "golang.org/x/crypto/bcrypt" - "golang.org/x/net/context" -) - -type compareFunc func(hashedPassword, password []byte) error - -var ( - errMismatchedHashAndPassword = errors.New("mismatched hash and password") - - compareFuncs = []struct { - prefix string - compare compareFunc - }{ - {"", compareMD5HashAndPassword}, // default compareFunc - {"{SHA}", compareShaHashAndPassword}, - // Bcrypt is complicated. According to crypt(3) from - // crypt_blowfish version 1.3 (fetched from - // http://www.openwall.com/crypt/crypt_blowfish-1.3.tar.gz), there - // are three different has prefixes: "$2a$", used by versions up - // to 1.0.4, and "$2x$" and "$2y$", used in all later - // versions. "$2a$" has a known bug, "$2x$" was added as a - // migration path for systems with "$2a$" prefix and still has a - // bug, and only "$2y$" should be used by modern systems. The bug - // has something to do with handling of 8-bit characters. Since - // both "$2a$" and "$2x$" are deprecated, we are handling them the - // same way as "$2y$", which will yield correct results for 7-bit - // character passwords, but is wrong for 8-bit character - // passwords. You have to upgrade to "$2y$" if you want sant 8-bit - // character password support with bcrypt. To add to the mess, - // OpenBSD 5.5. introduced "$2b$" prefix, which behaves exactly - // like "$2y$" according to the same source. - {"$2a$", bcrypt.CompareHashAndPassword}, - {"$2b$", bcrypt.CompareHashAndPassword}, - {"$2x$", bcrypt.CompareHashAndPassword}, - {"$2y$", bcrypt.CompareHashAndPassword}, - } -) - -type BasicAuth struct { - Realm string - Secrets SecretProvider - // Headers used by authenticator. Set to ProxyHeaders to use with - // proxy server. When nil, NormalHeaders are used. - Headers *Headers -} - -// check that BasicAuth implements AuthenticatorInterface -var _ = (AuthenticatorInterface)((*BasicAuth)(nil)) - -/* - Checks the username/password combination from the request. Returns - either an empty string (authentication failed) or the name of the - authenticated user. - - Supports MD5 and SHA1 password entries -*/ -func (a *BasicAuth) CheckAuth(r *http.Request) string { - s := strings.SplitN(r.Header.Get(a.Headers.V().Authorization), " ", 2) - if len(s) != 2 || s[0] != "Basic" { - return "" - } - - b, err := base64.StdEncoding.DecodeString(s[1]) - if err != nil { - return "" - } - pair := strings.SplitN(string(b), ":", 2) - if len(pair) != 2 { - return "" - } - user, password := pair[0], pair[1] - secret := a.Secrets(user, a.Realm) - if secret == "" { - return "" - } - compare := compareFuncs[0].compare - for _, cmp := range compareFuncs[1:] { - if strings.HasPrefix(secret, cmp.prefix) { - compare = cmp.compare - break - } - } - if compare([]byte(secret), []byte(password)) != nil { - return "" - } - return pair[0] -} - -func compareShaHashAndPassword(hashedPassword, password []byte) error { - d := sha1.New() - d.Write(password) - if subtle.ConstantTimeCompare(hashedPassword[5:], []byte(base64.StdEncoding.EncodeToString(d.Sum(nil)))) != 1 { - return errMismatchedHashAndPassword - } - return nil -} - -func compareMD5HashAndPassword(hashedPassword, password []byte) error { - parts := bytes.SplitN(hashedPassword, []byte("$"), 4) - if len(parts) != 4 { - return errMismatchedHashAndPassword - } - magic := []byte("$" + string(parts[1]) + "$") - salt := parts[2] - if subtle.ConstantTimeCompare(hashedPassword, MD5Crypt(password, salt, magic)) != 1 { - return errMismatchedHashAndPassword - } - return nil -} - -/* - http.Handler for BasicAuth which initiates the authentication process - (or requires reauthentication). -*/ -func (a *BasicAuth) RequireAuth(w http.ResponseWriter, r *http.Request) { - w.Header().Set(contentType, a.Headers.V().UnauthContentType) - w.Header().Set(a.Headers.V().Authenticate, `Basic realm="`+a.Realm+`"`) - w.WriteHeader(a.Headers.V().UnauthCode) - w.Write([]byte(a.Headers.V().UnauthResponse)) -} - -/* - BasicAuthenticator returns a function, which wraps an - AuthenticatedHandlerFunc converting it to http.HandlerFunc. This - wrapper function checks the authentication and either sends back - required authentication headers, or calls the wrapped function with - authenticated username in the AuthenticatedRequest. -*/ -func (a *BasicAuth) Wrap(wrapped AuthenticatedHandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if username := a.CheckAuth(r); username == "" { - a.RequireAuth(w, r) - } else { - ar := &AuthenticatedRequest{Request: *r, Username: username} - wrapped(w, ar) - } - } -} - -// NewContext returns a context carrying authentication information for the request. -func (a *BasicAuth) NewContext(ctx context.Context, r *http.Request) context.Context { - info := &Info{Username: a.CheckAuth(r), ResponseHeaders: make(http.Header)} - info.Authenticated = (info.Username != "") - if !info.Authenticated { - info.ResponseHeaders.Set(a.Headers.V().Authenticate, `Basic realm="`+a.Realm+`"`) - } - return context.WithValue(ctx, infoKey, info) -} - -func NewBasicAuthenticator(realm string, secrets SecretProvider) *BasicAuth { - return &BasicAuth{Realm: realm, Secrets: secrets} -} diff --git a/vendor/github.com/abbot/go-http-auth/digest.go b/vendor/github.com/abbot/go-http-auth/digest.go deleted file mode 100644 index 0ea5bacf9..000000000 --- a/vendor/github.com/abbot/go-http-auth/digest.go +++ /dev/null @@ -1,281 +0,0 @@ -package auth - -import ( - "crypto/subtle" - "fmt" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "sync" - "time" - - "golang.org/x/net/context" -) - -type digest_client struct { - nc uint64 - last_seen int64 -} - -type DigestAuth struct { - Realm string - Opaque string - Secrets SecretProvider - PlainTextSecrets bool - IgnoreNonceCount bool - // Headers used by authenticator. Set to ProxyHeaders to use with - // proxy server. When nil, NormalHeaders are used. - Headers *Headers - - /* - Approximate size of Client's Cache. When actual number of - tracked client nonces exceeds - ClientCacheSize+ClientCacheTolerance, ClientCacheTolerance*2 - older entries are purged. - */ - ClientCacheSize int - ClientCacheTolerance int - - clients map[string]*digest_client - mutex sync.RWMutex -} - -// check that DigestAuth implements AuthenticatorInterface -var _ = (AuthenticatorInterface)((*DigestAuth)(nil)) - -type digest_cache_entry struct { - nonce string - last_seen int64 -} - -type digest_cache []digest_cache_entry - -func (c digest_cache) Less(i, j int) bool { - return c[i].last_seen < c[j].last_seen -} - -func (c digest_cache) Len() int { - return len(c) -} - -func (c digest_cache) Swap(i, j int) { - c[i], c[j] = c[j], c[i] -} - -/* - Remove count oldest entries from DigestAuth.clients -*/ -func (a *DigestAuth) Purge(count int) { - entries := make([]digest_cache_entry, 0, len(a.clients)) - for nonce, client := range a.clients { - entries = append(entries, digest_cache_entry{nonce, client.last_seen}) - } - cache := digest_cache(entries) - sort.Sort(cache) - for _, client := range cache[:count] { - delete(a.clients, client.nonce) - } -} - -/* - http.Handler for DigestAuth which initiates the authentication process - (or requires reauthentication). -*/ -func (a *DigestAuth) RequireAuth(w http.ResponseWriter, r *http.Request) { - a.mutex.Lock() - defer a.mutex.Unlock() - if len(a.clients) > a.ClientCacheSize+a.ClientCacheTolerance { - a.Purge(a.ClientCacheTolerance * 2) - } - - nonce := RandomKey() - - a.clients[nonce] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - - w.Header().Set(contentType, a.Headers.V().UnauthContentType) - w.Header().Set(a.Headers.V().Authenticate, - fmt.Sprintf(`Digest realm="%s", nonce="%s", opaque="%s", algorithm="MD5", qop="auth"`, - a.Realm, nonce, a.Opaque)) - w.WriteHeader(a.Headers.V().UnauthCode) - w.Write([]byte(a.Headers.V().UnauthResponse)) -} - -/* - Parse Authorization header from the http.Request. Returns a map of - auth parameters or nil if the header is not a valid parsable Digest - auth header. -*/ -func DigestAuthParams(authorization string) map[string]string { - s := strings.SplitN(authorization, " ", 2) - if len(s) != 2 || s[0] != "Digest" { - return nil - } - - return ParsePairs(s[1]) -} - -/* - Check if request contains valid authentication data. Returns a pair - of username, authinfo where username is the name of the authenticated - user or an empty string and authinfo is the contents for the optional - Authentication-Info response header. -*/ -func (da *DigestAuth) CheckAuth(r *http.Request) (username string, authinfo *string) { - da.mutex.RLock() - defer da.mutex.RUnlock() - username = "" - authinfo = nil - auth := DigestAuthParams(r.Header.Get(da.Headers.V().Authorization)) - if auth == nil { - return "", nil - } - // RFC2617 Section 3.2.1 specifies that unset value of algorithm in - // WWW-Authenticate Response header should be treated as - // "MD5". According to section 3.2.2 the "algorithm" value in - // subsequent Request Authorization header must be set to whatever - // was supplied in the WWW-Authenticate Response header. This - // implementation always returns an algorithm in WWW-Authenticate - // header, however there seems to be broken clients in the wild - // which do not set the algorithm. Assume the unset algorithm in - // Authorization header to be equal to MD5. - if _, ok := auth["algorithm"]; !ok { - auth["algorithm"] = "MD5" - } - if da.Opaque != auth["opaque"] || auth["algorithm"] != "MD5" || auth["qop"] != "auth" { - return "", nil - } - - // Check if the requested URI matches auth header - if r.RequestURI != auth["uri"] { - // We allow auth["uri"] to be a full path prefix of request-uri - // for some reason lost in history, which is probably wrong, but - // used to be like that for quite some time - // (https://tools.ietf.org/html/rfc2617#section-3.2.2 explicitly - // says that auth["uri"] is the request-uri). - // - // TODO: make an option to allow only strict checking. - switch u, err := url.Parse(auth["uri"]); { - case err != nil: - return "", nil - case r.URL == nil: - return "", nil - case len(u.Path) > len(r.URL.Path): - return "", nil - case !strings.HasPrefix(r.URL.Path, u.Path): - return "", nil - } - } - - HA1 := da.Secrets(auth["username"], da.Realm) - if da.PlainTextSecrets { - HA1 = H(auth["username"] + ":" + da.Realm + ":" + HA1) - } - HA2 := H(r.Method + ":" + auth["uri"]) - KD := H(strings.Join([]string{HA1, auth["nonce"], auth["nc"], auth["cnonce"], auth["qop"], HA2}, ":")) - - if subtle.ConstantTimeCompare([]byte(KD), []byte(auth["response"])) != 1 { - return "", nil - } - - // At this point crypto checks are completed and validated. - // Now check if the session is valid. - - nc, err := strconv.ParseUint(auth["nc"], 16, 64) - if err != nil { - return "", nil - } - - if client, ok := da.clients[auth["nonce"]]; !ok { - return "", nil - } else { - if client.nc != 0 && client.nc >= nc && !da.IgnoreNonceCount { - return "", nil - } - client.nc = nc - client.last_seen = time.Now().UnixNano() - } - - resp_HA2 := H(":" + auth["uri"]) - rspauth := H(strings.Join([]string{HA1, auth["nonce"], auth["nc"], auth["cnonce"], auth["qop"], resp_HA2}, ":")) - - info := fmt.Sprintf(`qop="auth", rspauth="%s", cnonce="%s", nc="%s"`, rspauth, auth["cnonce"], auth["nc"]) - return auth["username"], &info -} - -/* - Default values for ClientCacheSize and ClientCacheTolerance for DigestAuth -*/ -const DefaultClientCacheSize = 1000 -const DefaultClientCacheTolerance = 100 - -/* - Wrap returns an Authenticator which uses HTTP Digest - authentication. Arguments: - - realm: The authentication realm. - - secrets: SecretProvider which must return HA1 digests for the same - realm as above. -*/ -func (a *DigestAuth) Wrap(wrapped AuthenticatedHandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if username, authinfo := a.CheckAuth(r); username == "" { - a.RequireAuth(w, r) - } else { - ar := &AuthenticatedRequest{Request: *r, Username: username} - if authinfo != nil { - w.Header().Set(a.Headers.V().AuthInfo, *authinfo) - } - wrapped(w, ar) - } - } -} - -/* - JustCheck returns function which converts an http.HandlerFunc into a - http.HandlerFunc which requires authentication. Username is passed as - an extra X-Authenticated-Username header. -*/ -func (a *DigestAuth) JustCheck(wrapped http.HandlerFunc) http.HandlerFunc { - return a.Wrap(func(w http.ResponseWriter, ar *AuthenticatedRequest) { - ar.Header.Set(AuthUsernameHeader, ar.Username) - wrapped(w, &ar.Request) - }) -} - -// NewContext returns a context carrying authentication information for the request. -func (a *DigestAuth) NewContext(ctx context.Context, r *http.Request) context.Context { - a.mutex.Lock() - defer a.mutex.Unlock() - username, authinfo := a.CheckAuth(r) - info := &Info{Username: username, ResponseHeaders: make(http.Header)} - if username != "" { - info.Authenticated = true - info.ResponseHeaders.Set(a.Headers.V().AuthInfo, *authinfo) - } else { - // return back digest WWW-Authenticate header - if len(a.clients) > a.ClientCacheSize+a.ClientCacheTolerance { - a.Purge(a.ClientCacheTolerance * 2) - } - nonce := RandomKey() - a.clients[nonce] = &digest_client{nc: 0, last_seen: time.Now().UnixNano()} - info.ResponseHeaders.Set(a.Headers.V().Authenticate, - fmt.Sprintf(`Digest realm="%s", nonce="%s", opaque="%s", algorithm="MD5", qop="auth"`, - a.Realm, nonce, a.Opaque)) - } - return context.WithValue(ctx, infoKey, info) -} - -func NewDigestAuthenticator(realm string, secrets SecretProvider) *DigestAuth { - da := &DigestAuth{ - Opaque: RandomKey(), - Realm: realm, - Secrets: secrets, - PlainTextSecrets: false, - ClientCacheSize: DefaultClientCacheSize, - ClientCacheTolerance: DefaultClientCacheTolerance, - clients: map[string]*digest_client{}} - return da -} diff --git a/vendor/github.com/abbot/go-http-auth/md5crypt.go b/vendor/github.com/abbot/go-http-auth/md5crypt.go deleted file mode 100644 index a7a031c41..000000000 --- a/vendor/github.com/abbot/go-http-auth/md5crypt.go +++ /dev/null @@ -1,92 +0,0 @@ -package auth - -import "crypto/md5" -import "strings" - -const itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - -var md5_crypt_swaps = [16]int{12, 6, 0, 13, 7, 1, 14, 8, 2, 15, 9, 3, 5, 10, 4, 11} - -type MD5Entry struct { - Magic, Salt, Hash []byte -} - -func NewMD5Entry(e string) *MD5Entry { - parts := strings.SplitN(e, "$", 4) - if len(parts) != 4 { - return nil - } - return &MD5Entry{ - Magic: []byte("$" + parts[1] + "$"), - Salt: []byte(parts[2]), - Hash: []byte(parts[3]), - } -} - -/* - MD5 password crypt implementation -*/ -func MD5Crypt(password, salt, magic []byte) []byte { - d := md5.New() - - d.Write(password) - d.Write(magic) - d.Write(salt) - - d2 := md5.New() - d2.Write(password) - d2.Write(salt) - d2.Write(password) - - for i, mixin := 0, d2.Sum(nil); i < len(password); i++ { - d.Write([]byte{mixin[i%16]}) - } - - for i := len(password); i != 0; i >>= 1 { - if i&1 == 0 { - d.Write([]byte{password[0]}) - } else { - d.Write([]byte{0}) - } - } - - final := d.Sum(nil) - - for i := 0; i < 1000; i++ { - d2 := md5.New() - if i&1 == 0 { - d2.Write(final) - } else { - d2.Write(password) - } - - if i%3 != 0 { - d2.Write(salt) - } - - if i%7 != 0 { - d2.Write(password) - } - - if i&1 == 0 { - d2.Write(password) - } else { - d2.Write(final) - } - final = d2.Sum(nil) - } - - result := make([]byte, 0, 22) - v := uint(0) - bits := uint(0) - for _, i := range md5_crypt_swaps { - v |= (uint(final[i]) << bits) - for bits = bits + 8; bits > 6; bits -= 6 { - result = append(result, itoa64[v&0x3f]) - v >>= 6 - } - } - result = append(result, itoa64[v&0x3f]) - - return append(append(append(magic, salt...), '$'), result...) -} diff --git a/vendor/github.com/abbot/go-http-auth/misc.go b/vendor/github.com/abbot/go-http-auth/misc.go deleted file mode 100644 index 4536ce673..000000000 --- a/vendor/github.com/abbot/go-http-auth/misc.go +++ /dev/null @@ -1,141 +0,0 @@ -package auth - -import ( - "bytes" - "crypto/md5" - "crypto/rand" - "encoding/base64" - "fmt" - "net/http" - "strings" -) - -// RandomKey returns a random 16-byte base64 alphabet string -func RandomKey() string { - k := make([]byte, 12) - for bytes := 0; bytes < len(k); { - n, err := rand.Read(k[bytes:]) - if err != nil { - panic("rand.Read() failed") - } - bytes += n - } - return base64.StdEncoding.EncodeToString(k) -} - -// H function for MD5 algorithm (returns a lower-case hex MD5 digest) -func H(data string) string { - digest := md5.New() - digest.Write([]byte(data)) - return fmt.Sprintf("%x", digest.Sum(nil)) -} - -// ParseList parses a comma-separated list of values as described by -// RFC 2068 and returns list elements. -// -// Lifted from https://code.google.com/p/gorilla/source/browse/http/parser/parser.go -// which was ported from urllib2.parse_http_list, from the Python -// standard library. -func ParseList(value string) []string { - var list []string - var escape, quote bool - b := new(bytes.Buffer) - for _, r := range value { - switch { - case escape: - b.WriteRune(r) - escape = false - case quote: - if r == '\\' { - escape = true - } else { - if r == '"' { - quote = false - } - b.WriteRune(r) - } - case r == ',': - list = append(list, strings.TrimSpace(b.String())) - b.Reset() - case r == '"': - quote = true - b.WriteRune(r) - default: - b.WriteRune(r) - } - } - // Append last part. - if s := b.String(); s != "" { - list = append(list, strings.TrimSpace(s)) - } - return list -} - -// ParsePairs extracts key/value pairs from a comma-separated list of -// values as described by RFC 2068 and returns a map[key]value. The -// resulting values are unquoted. If a list element doesn't contain a -// "=", the key is the element itself and the value is an empty -// string. -// -// Lifted from https://code.google.com/p/gorilla/source/browse/http/parser/parser.go -func ParsePairs(value string) map[string]string { - m := make(map[string]string) - for _, pair := range ParseList(strings.TrimSpace(value)) { - if i := strings.Index(pair, "="); i < 0 { - m[pair] = "" - } else { - v := pair[i+1:] - if v[0] == '"' && v[len(v)-1] == '"' { - // Unquote it. - v = v[1 : len(v)-1] - } - m[pair[:i]] = v - } - } - return m -} - -// Headers contains header and error codes used by authenticator. -type Headers struct { - Authenticate string // WWW-Authenticate - Authorization string // Authorization - AuthInfo string // Authentication-Info - UnauthCode int // 401 - UnauthContentType string // text/plain - UnauthResponse string // Unauthorized. -} - -// V returns NormalHeaders when h is nil, or h otherwise. Allows to -// use uninitialized *Headers values in structs. -func (h *Headers) V() *Headers { - if h == nil { - return NormalHeaders - } - return h -} - -var ( - // NormalHeaders are the regular Headers used by an HTTP Server for - // request authentication. - NormalHeaders = &Headers{ - Authenticate: "WWW-Authenticate", - Authorization: "Authorization", - AuthInfo: "Authentication-Info", - UnauthCode: http.StatusUnauthorized, - UnauthContentType: "text/plain", - UnauthResponse: fmt.Sprintf("%d %s\n", http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)), - } - - // ProxyHeaders are Headers used by an HTTP Proxy server for proxy - // access authentication. - ProxyHeaders = &Headers{ - Authenticate: "Proxy-Authenticate", - Authorization: "Proxy-Authorization", - AuthInfo: "Proxy-Authentication-Info", - UnauthCode: http.StatusProxyAuthRequired, - UnauthContentType: "text/plain", - UnauthResponse: fmt.Sprintf("%d %s\n", http.StatusProxyAuthRequired, http.StatusText(http.StatusProxyAuthRequired)), - } -) - -const contentType = "Content-Type" diff --git a/vendor/github.com/abbot/go-http-auth/users.go b/vendor/github.com/abbot/go-http-auth/users.go deleted file mode 100644 index 377181243..000000000 --- a/vendor/github.com/abbot/go-http-auth/users.go +++ /dev/null @@ -1,154 +0,0 @@ -package auth - -import ( - "encoding/csv" - "os" - "sync" -) - -/* - SecretProvider is used by authenticators. Takes user name and realm - as an argument, returns secret required for authentication (HA1 for - digest authentication, properly encrypted password for basic). - - Returning an empty string means failing the authentication. -*/ -type SecretProvider func(user, realm string) string - -/* - Common functions for file auto-reloading -*/ -type File struct { - Path string - Info os.FileInfo - /* must be set in inherited types during initialization */ - Reload func() - mu sync.Mutex -} - -func (f *File) ReloadIfNeeded() { - info, err := os.Stat(f.Path) - if err != nil { - panic(err) - } - f.mu.Lock() - defer f.mu.Unlock() - if f.Info == nil || f.Info.ModTime() != info.ModTime() { - f.Info = info - f.Reload() - } -} - -/* - Structure used for htdigest file authentication. Users map realms to - maps of users to their HA1 digests. -*/ -type HtdigestFile struct { - File - Users map[string]map[string]string - mu sync.RWMutex -} - -func reload_htdigest(hf *HtdigestFile) { - r, err := os.Open(hf.Path) - if err != nil { - panic(err) - } - csv_reader := csv.NewReader(r) - csv_reader.Comma = ':' - csv_reader.Comment = '#' - csv_reader.TrimLeadingSpace = true - - records, err := csv_reader.ReadAll() - if err != nil { - panic(err) - } - - hf.mu.Lock() - defer hf.mu.Unlock() - hf.Users = make(map[string]map[string]string) - for _, record := range records { - _, exists := hf.Users[record[1]] - if !exists { - hf.Users[record[1]] = make(map[string]string) - } - hf.Users[record[1]][record[0]] = record[2] - } -} - -/* - SecretProvider implementation based on htdigest-formated files. Will - reload htdigest file on changes. Will panic on syntax errors in - htdigest files. -*/ -func HtdigestFileProvider(filename string) SecretProvider { - hf := &HtdigestFile{File: File{Path: filename}} - hf.Reload = func() { reload_htdigest(hf) } - return func(user, realm string) string { - hf.ReloadIfNeeded() - hf.mu.RLock() - defer hf.mu.RUnlock() - _, exists := hf.Users[realm] - if !exists { - return "" - } - digest, exists := hf.Users[realm][user] - if !exists { - return "" - } - return digest - } -} - -/* - Structure used for htdigest file authentication. Users map users to - their salted encrypted password -*/ -type HtpasswdFile struct { - File - Users map[string]string - mu sync.RWMutex -} - -func reload_htpasswd(h *HtpasswdFile) { - r, err := os.Open(h.Path) - if err != nil { - panic(err) - } - csv_reader := csv.NewReader(r) - csv_reader.Comma = ':' - csv_reader.Comment = '#' - csv_reader.TrimLeadingSpace = true - - records, err := csv_reader.ReadAll() - if err != nil { - panic(err) - } - - h.mu.Lock() - defer h.mu.Unlock() - h.Users = make(map[string]string) - for _, record := range records { - h.Users[record[0]] = record[1] - } -} - -/* - SecretProvider implementation based on htpasswd-formated files. Will - reload htpasswd file on changes. Will panic on syntax errors in - htpasswd files. Realm argument of the SecretProvider is ignored. -*/ -func HtpasswdFileProvider(filename string) SecretProvider { - h := &HtpasswdFile{File: File{Path: filename}} - h.Reload = func() { reload_htpasswd(h) } - return func(user, realm string) string { - h.ReloadIfNeeded() - h.mu.RLock() - password, exists := h.Users[user] - h.mu.RUnlock() - if !exists { - return "" - } - return password - } -} diff --git a/vendor/github.com/abronan/valkeyrie/LICENSE.code b/vendor/github.com/abronan/valkeyrie/LICENSE.code deleted file mode 100644 index 34c4ea7c5..000000000 --- a/vendor/github.com/abronan/valkeyrie/LICENSE.code +++ /dev/null @@ -1,191 +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 - - Copyright 2014-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 - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/abronan/valkeyrie/LICENSE.docs b/vendor/github.com/abronan/valkeyrie/LICENSE.docs deleted file mode 100644 index e26cd4fc8..000000000 --- a/vendor/github.com/abronan/valkeyrie/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/abronan/valkeyrie/store/helpers.go b/vendor/github.com/abronan/valkeyrie/store/helpers.go deleted file mode 100644 index 0fb74c9ae..000000000 --- a/vendor/github.com/abronan/valkeyrie/store/helpers.go +++ /dev/null @@ -1,47 +0,0 @@ -package store - -import ( - "strings" -) - -// CreateEndpoints creates a list of endpoints given the right scheme -func CreateEndpoints(addrs []string, scheme string) (entries []string) { - for _, addr := range addrs { - entries = append(entries, scheme+"://"+addr) - } - return entries -} - -// Normalize the key for each store to the form: -// -// /path/to/key -// -func Normalize(key string) string { - return "/" + join(SplitKey(key)) -} - -// GetDirectory gets the full directory part of -// the key to the form: -// -// /path/to/ -// -func GetDirectory(key string) string { - parts := SplitKey(key) - parts = parts[:len(parts)-1] - return "/" + join(parts) -} - -// SplitKey splits the key to extract path informations -func SplitKey(key string) (path []string) { - if strings.Contains(key, "/") { - path = strings.Split(key, "/") - } else { - path = []string{key} - } - return path -} - -// join the path parts with '/' -func join(parts []string) string { - return strings.Join(parts, "/") -} diff --git a/vendor/github.com/abronan/valkeyrie/store/store.go b/vendor/github.com/abronan/valkeyrie/store/store.go deleted file mode 100644 index acc25f909..000000000 --- a/vendor/github.com/abronan/valkeyrie/store/store.go +++ /dev/null @@ -1,147 +0,0 @@ -package store - -import ( - "crypto/tls" - "errors" - "time" -) - -// Backend represents a KV Store Backend -type Backend string - -const ( - // CONSUL backend - CONSUL Backend = "consul" - // ETCD backend with v2 client (backward compatibility) - ETCD Backend = "etcd" - // ETCDV3 backend with v3 client - ETCDV3 Backend = "etcdv3" - // ZK backend - ZK Backend = "zk" - // BOLTDB backend - BOLTDB Backend = "boltdb" - // REDIS backend - REDIS Backend = "redis" -) - -var ( - // ErrBackendNotSupported is thrown when the backend k/v store is not supported by valkeyrie - ErrBackendNotSupported = errors.New("Backend storage not supported yet, please choose one of") - // ErrCallNotSupported is thrown when a method is not implemented/supported by the current backend - ErrCallNotSupported = errors.New("The current call is not supported with this backend") - // ErrNotReachable is thrown when the API cannot be reached for issuing common store operations - ErrNotReachable = errors.New("Api not reachable") - // ErrCannotLock is thrown when there is an error acquiring a lock on a key - ErrCannotLock = errors.New("Error acquiring the lock") - // ErrKeyModified is thrown during an atomic operation if the index does not match the one in the store - ErrKeyModified = errors.New("Unable to complete atomic operation, key modified") - // ErrKeyNotFound is thrown when the key is not found in the store during a Get operation - ErrKeyNotFound = errors.New("Key not found in store") - // ErrPreviousNotSpecified is thrown when the previous value is not specified for an atomic operation - ErrPreviousNotSpecified = errors.New("Previous K/V pair should be provided for the Atomic operation") - // ErrKeyExists is thrown when the previous value exists in the case of an AtomicPut - ErrKeyExists = errors.New("Previous K/V pair exists, cannot complete Atomic operation") -) - -// Config contains the options for a storage client -type Config struct { - ClientTLS *ClientTLSConfig - TLS *tls.Config - ConnectionTimeout time.Duration - SyncPeriod time.Duration - Bucket string - PersistConnection bool - Username string - Password string -} - -// ClientTLSConfig contains data for a Client TLS configuration in the form -// the etcd client wants it. Eventually we'll adapt it for ZK and Consul. -type ClientTLSConfig struct { - CertFile string - KeyFile string - CACertFile string -} - -// Store represents the backend K/V storage -// Each store should support every call listed -// here. Or it couldn't be implemented as a K/V -// backend for valkeyrie -type Store interface { - // Put a value at the specified key - Put(key string, value []byte, options *WriteOptions) error - - // Get a value given its key - Get(key string, options *ReadOptions) (*KVPair, error) - - // Delete the value at the specified key - Delete(key string) error - - // Verify if a Key exists in the store - Exists(key string, options *ReadOptions) (bool, error) - - // Watch for changes on a key - Watch(key string, stopCh <-chan struct{}, options *ReadOptions) (<-chan *KVPair, error) - - // WatchTree watches for changes on child nodes under - // a given directory - WatchTree(directory string, stopCh <-chan struct{}, options *ReadOptions) (<-chan []*KVPair, error) - - // NewLock creates a lock for a given key. - // The returned Locker is not held and must be acquired - // with `.Lock`. The Value is optional. - NewLock(key string, options *LockOptions) (Locker, error) - - // List the content of a given prefix - List(directory string, options *ReadOptions) ([]*KVPair, error) - - // DeleteTree deletes a range of keys under a given directory - DeleteTree(directory string) error - - // Atomic CAS operation on a single value. - // Pass previous = nil to create a new key. - AtomicPut(key string, value []byte, previous *KVPair, options *WriteOptions) (bool, *KVPair, error) - - // Atomic delete of a single value - AtomicDelete(key string, previous *KVPair) (bool, error) - - // Close the store connection - Close() -} - -// KVPair represents {Key, Value, Lastindex} tuple -type KVPair struct { - Key string - Value []byte - LastIndex uint64 -} - -// WriteOptions contains optional request parameters -type WriteOptions struct { - IsDir bool - TTL time.Duration -} - -// ReadOptions contains optional request parameters -type ReadOptions struct { - // Consistent defines if the behavior of a Get operation is - // linearizable or not. Linearizability allows us to 'see' - // objects based on a real-time total order as opposed to - // an arbitrary order or with stale values ('inconsistent' - // scenario). - Consistent bool -} - -// LockOptions contains optional request parameters -type LockOptions struct { - Value []byte // Optional, value to associate with the lock - TTL time.Duration // Optional, expiration ttl associated with the lock - RenewLock chan struct{} // Optional, chan used to control and stop the session ttl renewal for the lock -} - -// Locker provides locking mechanism on top of the store. -// Similar to `sync.Lock` except it may return errors. -type Locker interface { - Lock(stopChan chan struct{}) (<-chan struct{}, error) - Unlock() error -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/LICENSE b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/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/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go deleted file mode 100644 index d20ce434e..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/api.go +++ /dev/null @@ -1,36 +0,0 @@ -package client - -import ( - "encoding/json" -) - -// Resource is the "base" type for all API resources -type Resource struct { - Complete chan bool `json:"-"` -} - -// Init initializes the Complete channel, if it is necessary -// need to create a resource specific Init(), make sure to -// initialize the channel. -func (resource *Resource) Init() { - resource.Complete = make(chan bool, 1) -} - -// PostUnmarshalJSON is a default implementation of the -// PostUnmarshalJSON hook that simply calls Init() and -// sends true to the Complete channel. This is overridden -// in many resources, in particular those that represent -// collections, and have to initialize sub-resources also. -func (resource *Resource) PostUnmarshalJSON() error { - resource.Init() - resource.Complete <- true - return nil -} - -// GetJSON returns the raw (indented) JSON (as []bytes) -func (resource *Resource) GetJSON() ([]byte, error) { - return json.MarshalIndent(resource, "", " ") -} - -// JSONBody is a generic struct for temporary JSON unmarshalling. -type JSONBody map[string]interface{} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go deleted file mode 100644 index abbbcd4bb..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/client.go +++ /dev/null @@ -1,152 +0,0 @@ -// Package client is a simple library for http.Client to sign Akamai OPEN Edgegrid API requests -package client - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "mime/multipart" - "net/http" - "net/url" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1" -) - -var ( - libraryVersion = "0.6.2" - // UserAgent is the User-Agent value sent for all requests - UserAgent = "Akamai-Open-Edgegrid-golang/" + libraryVersion + " golang/" + strings.TrimPrefix(runtime.Version(), "go") - // Client is the *http.Client to use - Client = http.DefaultClient -) - -// NewRequest creates an HTTP request that can be sent to Akamai APIs. A relative URL can be provided in path, which will be resolved to the -// Host specified in Config. If body is specified, it will be sent as the request body. -func NewRequest(config edgegrid.Config, method, path string, body io.Reader) (*http.Request, error) { - var ( - baseURL *url.URL - err error - ) - - if strings.HasPrefix(config.Host, "https://") { - baseURL, err = url.Parse(config.Host) - } else { - baseURL, err = url.Parse("https://" + config.Host) - } - - if err != nil { - return nil, err - } - - rel, err := url.Parse(strings.TrimPrefix(path, "/")) - if err != nil { - return nil, err - } - - u := baseURL.ResolveReference(rel) - - req, err := http.NewRequest(method, u.String(), body) - if err != nil { - return nil, err - } - - req.Header.Add("User-Agent", UserAgent) - - return req, nil -} - -// NewJSONRequest creates an HTTP request that can be sent to the Akamai APIs with a JSON body -// The JSON body is encoded and the Content-Type/Accept headers are set automatically. -func NewJSONRequest(config edgegrid.Config, method, path string, body interface{}) (*http.Request, error) { - var req *http.Request - var err error - - if body != nil { - jsonBody, err := jsonhooks.Marshal(body) - if err != nil { - return nil, err - } - - buf := bytes.NewReader(jsonBody) - req, err = NewRequest(config, method, path, buf) - } else { - req, err = NewRequest(config, method, path, nil) - } - - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Accept", "application/json,*/*") - - return req, nil -} - -// NewMultiPartFormDataRequest creates an HTTP request that uploads a file to the Akamai API -func NewMultiPartFormDataRequest(config edgegrid.Config, uriPath, filePath string, otherFormParams map[string]string) (*http.Request, error) { - file, err := os.Open(filePath) - if err != nil { - return nil, err - } - defer file.Close() - - body := &bytes.Buffer{} - writer := multipart.NewWriter(body) - // TODO: make this field name configurable - part, err := writer.CreateFormFile("importFile", filepath.Base(filePath)) - if err != nil { - return nil, err - } - _, err = io.Copy(part, file) - - for key, val := range otherFormParams { - _ = writer.WriteField(key, val) - } - err = writer.Close() - if err != nil { - return nil, err - } - - req, err := NewRequest(config, "POST", uriPath, body) - req.Header.Set("Content-Type", writer.FormDataContentType()) - return req, err -} - -// Do performs a given HTTP Request, signed with the Akamai OPEN Edgegrid -// Authorization header. An edgegrid.Response or an error is returned. -func Do(config edgegrid.Config, req *http.Request) (*http.Response, error) { - Client.CheckRedirect = func(req *http.Request, via []*http.Request) error { - req = edgegrid.AddRequestHeader(config, req) - return nil - } - - req = edgegrid.AddRequestHeader(config, req) - res, err := Client.Do(req) - if err != nil { - return nil, err - } - - return res, nil -} - -// BodyJSON unmarshals the Response.Body into a given data structure -func BodyJSON(r *http.Response, data interface{}) error { - if data == nil { - return errors.New("You must pass in an interface{}") - } - - body, err := ioutil.ReadAll(r.Body) - if err != nil { - return err - } - err = jsonhooks.Unmarshal(body, data) - - return err -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go deleted file mode 100644 index 05b852473..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1/errors.go +++ /dev/null @@ -1,107 +0,0 @@ -package client - -import ( - "fmt" - "io/ioutil" - "net/http" - "strings" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1" -) - -// APIError exposes an Akamai OPEN Edgegrid Error -type APIError struct { - error - Type string `json:"type"` - Title string `json:"title"` - Status int `json:"status"` - Detail string `json:"detail"` - Errors []APIErrorDetail `json:"errors"` - Problems []APIErrorDetail `json:"problems"` - Instance string `json:"instance"` - Method string `json:"method"` - ServerIP string `json:"serverIp"` - ClientIP string `json:"clientIp"` - RequestID string `json:"requestId"` - RequestTime string `json:"requestTime"` - Response *http.Response `json:"-"` - RawBody string `json:"-"` -} - -type APIErrorDetail struct { - Type string `json:"type"` - Title string `json:"title"` - Detail string `json:"detail"` - RejectedValue string `json:"rejectedValue"` -} - -func (error APIError) Error() string { - var errorDetails string - if len(error.Errors) > 0 { - for _, e := range error.Errors { - errorDetails = fmt.Sprintf("%s \n %s", errorDetails, e) - } - } - if len(error.Problems) > 0 { - for _, e := range error.Problems { - errorDetails = fmt.Sprintf("%s \n %s", errorDetails, e) - } - } - return strings.TrimSpace(fmt.Sprintf("API Error: %d %s %s More Info %s\n %s", error.Status, error.Title, error.Detail, error.Type, errorDetails)) -} - -// NewAPIError creates a new API error based on a Response, -// or http.Response-like. -func NewAPIError(response *http.Response) APIError { - // TODO: handle this error - body, _ := ioutil.ReadAll(response.Body) - - return NewAPIErrorFromBody(response, body) -} - -// NewAPIErrorFromBody creates a new API error, allowing you to pass in a body -// -// This function is intended to be used after the body has already been read for -// other purposes. -func NewAPIErrorFromBody(response *http.Response, body []byte) APIError { - error := APIError{} - if err := jsonhooks.Unmarshal(body, &error); err == nil { - error.Status = response.StatusCode - error.Title = response.Status - } - - error.Response = response - error.RawBody = string(body) - - return error -} - -// IsInformational determines if a response was informational (1XX status) -func IsInformational(r *http.Response) bool { - return r.StatusCode > 99 && r.StatusCode < 200 -} - -// IsSuccess determines if a response was successful (2XX status) -func IsSuccess(r *http.Response) bool { - return r.StatusCode > 199 && r.StatusCode < 300 -} - -// IsRedirection determines if a response was a redirect (3XX status) -func IsRedirection(r *http.Response) bool { - return r.StatusCode > 299 && r.StatusCode < 400 -} - -// IsClientError determines if a response was a client error (4XX status) -func IsClientError(r *http.Response) bool { - return r.StatusCode > 399 && r.StatusCode < 500 -} - -// IsServerError determines if a response was a server error (5XX status) -func IsServerError(r *http.Response) bool { - return r.StatusCode > 499 && r.StatusCode < 600 -} - -// IsError determines if the response was a client or server error (4XX or 5XX status) -func IsError(r *http.Response) bool { - return r.StatusCode > 399 && r.StatusCode < 600 -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go deleted file mode 100644 index 06eed5daa..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/errors.go +++ /dev/null @@ -1,125 +0,0 @@ -package dns - -import ( - "fmt" -) - -type ConfigDNSError interface { - error - Network() bool - NotFound() bool - FailedToSave() bool - ValidationFailed() bool -} - -func IsConfigDNSError(e error) bool { - _, ok := e.(ConfigDNSError) - return ok -} - -type ZoneError struct { - zoneName string - httpErrorMessage string - apiErrorMessage string - err error -} - -func (e *ZoneError) Network() bool { - if e.httpErrorMessage != "" { - return true - } - return false -} - -func (e *ZoneError) NotFound() bool { - if e.err == nil && e.httpErrorMessage == "" && e.apiErrorMessage == "" { - return true - } - return false -} - -func (e *ZoneError) FailedToSave() bool { - return false -} - -func (e *ZoneError) ValidationFailed() bool { - if e.apiErrorMessage != "" { - return true - } - return false -} - -func (e *ZoneError) Error() string { - if e.Network() { - return fmt.Sprintf("Zone \"%s\" network error: [%s]", e.zoneName, e.httpErrorMessage) - } - - if e.NotFound() { - return fmt.Sprintf("Zone \"%s\" not found.", e.zoneName) - } - - if e.FailedToSave() { - return fmt.Sprintf("Zone \"%s\" failed to save: [%s]", e.zoneName, e.err.Error()) - } - - if e.ValidationFailed() { - return fmt.Sprintf("Zone \"%s\" validation failed: [%s]", e.zoneName, e.apiErrorMessage) - } - - if e.err != nil { - return e.err.Error() - } - - return "" -} - -type RecordError struct { - fieldName string - httpErrorMessage string - err error -} - -func (e *RecordError) Network() bool { - if e.httpErrorMessage != "" { - return true - } - return false -} - -func (e *RecordError) NotFound() bool { - return false -} - -func (e *RecordError) FailedToSave() bool { - if e.fieldName == "" { - return true - } - return false -} - -func (e *RecordError) ValidationFailed() bool { - if e.fieldName != "" { - return true - } - return false -} - -func (e *RecordError) Error() string { - if e.Network() { - return fmt.Sprintf("Record network error: [%s]", e.httpErrorMessage) - } - - if e.NotFound() { - return fmt.Sprintf("Record not found.") - } - - if e.FailedToSave() { - return fmt.Sprintf("Record failed to save: [%s]", e.err.Error()) - } - - if e.ValidationFailed() { - return fmt.Sprintf("Record validation failed for field [%s]", e.fieldName) - } - - return "" -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go deleted file mode 100644 index 7a32fe6b7..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/record.go +++ /dev/null @@ -1,1739 +0,0 @@ -package dns - -import ( - "strings" - "time" -) - -// All record types (below) must implement the DNSRecord interface -// This allows the record to be used dynamically in slices - see the Zone struct definition in zone.go -// -// The record types implemented and their fields are as defined here -// https://developer.akamai.com/api/luna/config-dns/data.html -type DNSRecord interface { - // Get the list of allowed fields for this type - GetAllowedFields() []string - // Set a field on the struct, which check for valid fields - SetField(name string, value interface{}) error - // Translate struct properties to a map - ToMap() map[string]interface{} -} - -type ARecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewARecord() *ARecord { - return &ARecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *ARecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *ARecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *ARecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type AaaaRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewAaaaRecord() *AaaaRecord { - return &AaaaRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *AaaaRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *AaaaRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *AaaaRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type AfsdbRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Subtype int `json:"subtype,omitempty"` -} - -func NewAfsdbRecord() *AfsdbRecord { - return &AfsdbRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "subtype", - }, - } -} - -func (record *AfsdbRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *AfsdbRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "subtype": - v, ok := value.(int) - if ok { - record.Subtype = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *AfsdbRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "subtype": record.Subtype, - } -} - -type CnameRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewCnameRecord() *CnameRecord { - return &CnameRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *CnameRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *CnameRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *CnameRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type DnskeyRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Flags int `json:"flags,omitempty"` - Protocol int `json:"protocol,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Key string `json:"key,omitempty"` -} - -func NewDnskeyRecord() *DnskeyRecord { - return &DnskeyRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "flags", - "protocol", - "algorithm", - "key", - }, - } -} - -func (record *DnskeyRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *DnskeyRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "protocol": - v, ok := value.(int) - if ok { - record.Protocol = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "key": - v, ok := value.(string) - if ok { - record.Key = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *DnskeyRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "flags": record.Flags, - "protocol": record.Protocol, - "algorithm": record.Algorithm, - "key": record.Key, - } -} - -type DsRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Keytag int `json:"keytag,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - DigestType int `json:"digest_type,omitempty"` - Digest string `json:"digest,omitempty"` -} - -func NewDsRecord() *DsRecord { - return &DsRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "keytag", - "algorithm", - "digesttype", - "digest", - }, - } -} - -func (record *DsRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *DsRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "keytag": - v, ok := value.(int) - if ok { - record.Keytag = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "digesttype": - v, ok := value.(int) - if ok { - record.DigestType = v - return nil - } - case "digest": - v, ok := value.(string) - if ok { - record.Digest = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *DsRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "keytag": record.Keytag, - "algorithm": record.Algorithm, - "digesttype": record.DigestType, - "digest": record.DigestType, - } -} - -type HinfoRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Hardware string `json:"hardware,omitempty"` - Software string `json:"software,omitempty"` -} - -func NewHinfoRecord() *HinfoRecord { - return &HinfoRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "hardware", - "software", - }, - } -} - -func (record *HinfoRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *HinfoRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "hardware": - v, ok := value.(string) - if ok { - record.Hardware = v - return nil - } - case "software": - v, ok := value.(string) - if ok { - record.Software = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *HinfoRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "hardware": record.Hardware, - "software": record.Software, - } -} - -type LocRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewLocRecord() *LocRecord { - return &LocRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *LocRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *LocRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *LocRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type MxRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Priority int `json:"priority,omitempty"` -} - -func NewMxRecord() *MxRecord { - return &MxRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "priority", - }, - } -} - -func (record *MxRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *MxRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "priority": - v, ok := value.(int) - if ok { - record.Priority = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *MxRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "priority": record.Priority, - } -} - -type NaptrRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Order uint16 `json:"order,omitempty"` - Preference uint16 `json:"preference,omitempty"` - Flags string `json:"flags,omitempty"` - Service string `json:"service,omitempty"` - Regexp string `json:"regexp,omitempty"` - Replacement string `json:"replacement,omitempty"` -} - -func NewNaptrRecord() *NaptrRecord { - return &NaptrRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "order", - "preference", - "flags", - "service", - "regexp", - "replacement", - }, - } -} - -func (record *NaptrRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *NaptrRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "order": - v, ok := value.(uint16) - if ok { - record.Order = v - return nil - } - case "preference": - v, ok := value.(uint16) - if ok { - record.Preference = v - return nil - } - case "flags": - v, ok := value.(string) - if ok { - record.Flags = v - return nil - } - case "service": - v, ok := value.(string) - if ok { - record.Service = v - return nil - } - case "regexp": - v, ok := value.(string) - if ok { - record.Regexp = v - return nil - } - case "replacement": - v, ok := value.(string) - if ok { - record.Replacement = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *NaptrRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "order": record.Order, - "preference": record.Preference, - "flags": record.Flags, - "service": record.Service, - "regexp": record.Regexp, - "replacement": record.Replacement, - } -} - -type NsRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewNsRecord() *NsRecord { - return &NsRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *NsRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *NsRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *NsRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type Nsec3Record struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Flags int `json:"flags,omitempty"` - Iterations int `json:"iterations,omitempty"` - Salt string `json:"salt,omitempty"` - NextHashedOwnerName string `json:"next_hashed_owner_name,omitempty"` - TypeBitmaps string `json:"type_bitmaps,omitempty"` -} - -func NewNsec3Record() *Nsec3Record { - return &Nsec3Record{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "flags", - "iterations", - "salt", - "nexthashedownername", - "typebitmaps", - }, - } -} - -func (record *Nsec3Record) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *Nsec3Record) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "iterations": - v, ok := value.(int) - if ok { - record.Iterations = v - return nil - } - case "salt": - v, ok := value.(string) - if ok { - record.Salt = v - return nil - } - case "nexthashedownername": - v, ok := value.(string) - if ok { - record.NextHashedOwnerName = v - return nil - } - case "typebitmaps": - v, ok := value.(string) - if ok { - record.TypeBitmaps = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *Nsec3Record) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "flags": record.Flags, - "iterations": record.Iterations, - "salt": record.Salt, - "nexthashedownername": record.NextHashedOwnerName, - "typebitmaps": record.TypeBitmaps, - } -} - -type Nsec3paramRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - Flags int `json:"flags,omitempty"` - Iterations int `json:"iterations,omitempty"` - Salt string `json:"salt,omitempty"` -} - -func NewNsec3paramRecord() *Nsec3paramRecord { - return &Nsec3paramRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "flags", - "iterations", - "salt", - }, - } -} - -func (record *Nsec3paramRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *Nsec3paramRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "flags": - v, ok := value.(int) - if ok { - record.Flags = v - return nil - } - case "iterations": - v, ok := value.(int) - if ok { - record.Iterations = v - return nil - } - case "salt": - v, ok := value.(string) - if ok { - record.Salt = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *Nsec3paramRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "flags": record.Flags, - "iterations": record.Iterations, - "salt": record.Salt, - } -} - -type PtrRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewPtrRecord() *PtrRecord { - return &PtrRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *PtrRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *PtrRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *PtrRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type RpRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Mailbox string `json:"mailbox,omitempty"` - Txt string `json:"txt,omitempty"` -} - -func NewRpRecord() *RpRecord { - return &RpRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "mailbox", - "txt", - }, - } -} - -func (record *RpRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *RpRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "mailbox": - v, ok := value.(string) - if ok { - record.Mailbox = v - return nil - } - case "txt": - v, ok := value.(string) - if ok { - record.Txt = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *RpRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "mailbox": record.Mailbox, - "txt": record.Txt, - } -} - -type RrsigRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - TypeCovered string `json:"type_covered,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - OriginalTTL int `json:"original_ttl,omitempty"` - Expiration string `json:"expiration,omitempty"` - Inception string `json:"inception,omitempty"` - Keytag int `json:"keytag,omitempty"` - Signer string `json:"signer,omitempty"` - Signature string `json:"signature,omitempty"` - Labels int `json:"labels,omitempty"` -} - -func NewRrsigRecord() *RrsigRecord { - return &RrsigRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "typecovered", - "algorithm", - "originalttl", - "expiration", - "inception", - "keytag", - "signer", - "signature", - "labels", - }, - } -} - -func (record *RrsigRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *RrsigRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "typecovered": - v, ok := value.(string) - if ok { - record.TypeCovered = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "originalttl": - v, ok := value.(int) - if ok { - record.OriginalTTL = v - return nil - } - case "expiration": - v, ok := value.(string) - if ok { - record.Expiration = v - return nil - } - case "inception": - v, ok := value.(string) - if ok { - record.Inception = v - return nil - } - case "keytag": - v, ok := value.(int) - if ok { - record.Keytag = v - return nil - } - case "signer": - v, ok := value.(string) - if ok { - record.Signer = v - return nil - } - case "signature": - v, ok := value.(string) - if ok { - record.Signature = v - return nil - } - case "labels": - v, ok := value.(int) - if ok { - record.Labels = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *RrsigRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "typecovered": record.TypeCovered, - "algorithm": record.Algorithm, - "originalttl": record.OriginalTTL, - "expiration": record.Expiration, - "inception": record.Inception, - "keytag": record.Keytag, - "signer": record.Signer, - "signature": record.Signature, - "labels": record.Labels, - } -} - -type SoaRecord struct { - fieldMap []string `json:"-"` - originalSerial uint `json:"-"` - TTL int `json:"ttl,omitempty"` - Originserver string `json:"originserver,omitempty"` - Contact string `json:"contact,omitempty"` - Serial uint `json:"serial,omitempty"` - Refresh int `json:"refresh,omitempty"` - Retry int `json:"retry,omitempty"` - Expire int `json:"expire,omitempty"` - Minimum uint `json:"minimum,omitempty"` -} - -func NewSoaRecord() *SoaRecord { - r := &SoaRecord{ - fieldMap: []string{ - "ttl", - "originserver", - "contact", - "serial", - "refresh", - "retry", - "expire", - "minimum", - }, - } - r.SetField("serial", int(time.Now().Unix())) - return r -} - -func (record *SoaRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SoaRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "originserver": - v, ok := value.(string) - if ok { - record.Originserver = v - return nil - } - case "contact": - v, ok := value.(string) - if ok { - record.Contact = v - return nil - } - case "serial": - v, ok := value.(uint) - if ok { - record.Serial = v - return nil - } - case "refresh": - v, ok := value.(int) - if ok { - record.Refresh = v - return nil - } - case "retry": - v, ok := value.(int) - if ok { - record.Retry = v - return nil - } - case "expire": - v, ok := value.(int) - if ok { - record.Expire = v - return nil - } - case "minimum": - v, ok := value.(uint) - if ok { - record.Minimum = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SoaRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "ttl": record.TTL, - "originserver": record.Originserver, - "contact": record.Contact, - "serial": record.Serial, - "refresh": record.Refresh, - "retry": record.Retry, - "expire": record.Expire, - "minimum": record.Minimum, - } -} - -type SpfRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewSpfRecord() *SpfRecord { - return &SpfRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *SpfRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SpfRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SpfRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -type SrvRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` - Priority int `json:"priority,omitempty"` - Weight uint16 `json:"weight,omitempty"` - Port uint16 `json:"port,omitempty"` -} - -func NewSrvRecord() *SrvRecord { - return &SrvRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - "priority", - "weight", - "port", - }, - } -} - -func (record *SrvRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SrvRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - case "priority": - v, ok := value.(int) - if ok { - record.Priority = v - return nil - } - case "weight": - v, ok := value.(uint16) - if ok { - record.Weight = v - return nil - } - case "port": - v, ok := value.(uint16) - if ok { - record.Port = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SrvRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - "priority": record.Priority, - "weight": record.Weight, - "port": record.Port, - } -} - -type SshfpRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Algorithm int `json:"algorithm,omitempty"` - FingerprintType int `json:"fingerprint_type,omitempty"` - Fingerprint string `json:"fingerprint,omitempty"` -} - -func NewSshfpRecord() *SshfpRecord { - return &SshfpRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "algorithm", - "fingerprinttype", - "fingerprint", - }, - } -} - -func (record *SshfpRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *SshfpRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "algorithm": - v, ok := value.(int) - if ok { - record.Algorithm = v - return nil - } - case "fingerprinttype": - v, ok := value.(int) - if ok { - record.FingerprintType = v - return nil - } - case "fingerprint": - v, ok := value.(string) - if ok { - record.Fingerprint = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *SshfpRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "algorithm": record.Algorithm, - "fingerprinttype": record.FingerprintType, - "fingerprint": record.Fingerprint, - } -} - -type TxtRecord struct { - fieldMap []string `json:"-"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - Active bool `json:"active,omitempty"` - Target string `json:"target,omitempty"` -} - -func NewTxtRecord() *TxtRecord { - return &TxtRecord{ - fieldMap: []string{ - "name", - "ttl", - "active", - "target", - }, - } -} - -func (record *TxtRecord) GetAllowedFields() []string { - return record.fieldMap -} - -func (record *TxtRecord) SetField(name string, value interface{}) error { - if contains(record.fieldMap, name) { - switch name { - case "name": - v, ok := value.(string) - if ok { - record.Name = v - return nil - } - case "ttl": - v, ok := value.(int) - if ok { - record.TTL = v - return nil - } - case "active": - v, ok := value.(bool) - if ok { - record.Active = v - return nil - } - case "target": - v, ok := value.(string) - if ok { - record.Target = v - return nil - } - } - } - return &RecordError{fieldName: name} -} - -func (record *TxtRecord) ToMap() map[string]interface{} { - return map[string]interface{}{ - "name": record.Name, - "ttl": record.TTL, - "active": record.Active, - "target": record.Target, - } -} - -func contains(fieldMap []string, field string) bool { - field = strings.ToLower(field) - - for _, r := range fieldMap { - if r == field { - return true - } - } - - return false -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go deleted file mode 100644 index 7f8ff80b6..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/service.go +++ /dev/null @@ -1,16 +0,0 @@ -package dns - -import ( - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" -) - -var ( - // Config contains the Akamai OPEN Edgegrid API credentials - // for automatic signing of requests - Config edgegrid.Config -) - -// Init sets the FastDNS edgegrid Config -func Init(config edgegrid.Config) { - Config = config -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go deleted file mode 100644 index 65da7bc78..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1/zone.go +++ /dev/null @@ -1,1567 +0,0 @@ -package dns - -import ( - "errors" - "fmt" - "reflect" - "strings" - "sync" - "time" - - "github.com/akamai/AkamaiOPEN-edgegrid-golang/client-v1" -) - -type name struct { - recordType string - name string -} - -var ( - cnameNames []name - nonCnameNames []name - zoneWriteLock sync.Mutex -) - -// Zone represents a DNS zone -type Zone struct { - Token string `json:"token"` - Zone struct { - Name string `json:"name,omitempty"` - A []*ARecord `json:"a,omitempty"` - Aaaa []*AaaaRecord `json:"aaaa,omitempty"` - Afsdb []*AfsdbRecord `json:"afsdb,omitempty"` - Cname []*CnameRecord `json:"cname,omitempty"` - Dnskey []*DnskeyRecord `json:"dnskey,omitempty"` - Ds []*DsRecord `json:"ds,omitempty"` - Hinfo []*HinfoRecord `json:"hinfo,omitempty"` - Loc []*LocRecord `json:"loc,omitempty"` - Mx []*MxRecord `json:"mx,omitempty"` - Naptr []*NaptrRecord `json:"naptr,omitempty"` - Ns []*NsRecord `json:"ns,omitempty"` - Nsec3 []*Nsec3Record `json:"nsec3,omitempty"` - Nsec3param []*Nsec3paramRecord `json:"nsec3param,omitempty"` - Ptr []*PtrRecord `json:"ptr,omitempty"` - Rp []*RpRecord `json:"rp,omitempty"` - Rrsig []*RrsigRecord `json:"rrsig,omitempty"` - Soa *SoaRecord `json:"soa,omitempty"` - Spf []*SpfRecord `json:"spf,omitempty"` - Srv []*SrvRecord `json:"srv,omitempty"` - Sshfp []*SshfpRecord `json:"sshfp,omitempty"` - Txt []*TxtRecord `json:"txt,omitempty"` - } `json:"zone"` -} - -// NewZone creates a new Zone -func NewZone(hostname string) *Zone { - zone := &Zone{Token: "new"} - zone.Zone.Soa = NewSoaRecord() - zone.Zone.Name = hostname - return zone -} - -// GetZone retrieves a DNS Zone for a given hostname -func GetZone(hostname string) (*Zone, error) { - zone := NewZone(hostname) - req, err := client.NewRequest( - Config, - "GET", - "/config-dns/v1/zones/"+hostname, - nil, - ) - if err != nil { - return nil, err - } - - res, err := client.Do(Config, req) - if err != nil { - return nil, err - } - - if client.IsError(res) && res.StatusCode != 404 { - return nil, client.NewAPIError(res) - } else if res.StatusCode == 404 { - return nil, &ZoneError{zoneName: hostname} - } else { - err = client.BodyJSON(res, zone) - if err != nil { - return nil, err - } - - return zone, nil - } -} - -// Save updates the Zone -func (zone *Zone) Save() error { - // This lock will restrict the concurrency of API calls - // to 1 save request at a time. This is needed for the Soa.Serial value which - // is required to be incremented for every subsequent update to a zone - // so we have to save just one request at a time to ensure this is always - // incremented properly - zoneWriteLock.Lock() - defer zoneWriteLock.Unlock() - - valid, f := zone.validateCnames() - if valid == false { - var msg string - for _, v := range f { - msg = msg + fmt.Sprintf("\n%s Record '%s' conflicts with CNAME", v.recordType, v.name) - } - return &ZoneError{ - zoneName: zone.Zone.Name, - apiErrorMessage: "All CNAMEs must be unique in the zone" + msg, - } - } - - req, err := client.NewJSONRequest( - Config, - "POST", - "/config-dns/v1/zones/"+zone.Zone.Name, - zone, - ) - if err != nil { - return err - } - - res, err := client.Do(Config, req) - - // Network error - if err != nil { - return &ZoneError{ - zoneName: zone.Zone.Name, - httpErrorMessage: err.Error(), - err: err, - } - } - - // API error - if client.IsError(res) { - err := client.NewAPIError(res) - return &ZoneError{zoneName: zone.Zone.Name, apiErrorMessage: err.Detail, err: err} - } - - for { - updatedZone, err := GetZone(zone.Zone.Name) - if err != nil { - return err - } - - if updatedZone.Token != zone.Token { - *zone = *updatedZone - break - } - time.Sleep(time.Second) - } - - return nil -} - -func (zone *Zone) Delete() error { - // remove all the records except for SOA - // which is required and save the zone - zone.Zone.A = nil - zone.Zone.Aaaa = nil - zone.Zone.Afsdb = nil - zone.Zone.Cname = nil - zone.Zone.Dnskey = nil - zone.Zone.Ds = nil - zone.Zone.Hinfo = nil - zone.Zone.Loc = nil - zone.Zone.Mx = nil - zone.Zone.Naptr = nil - zone.Zone.Ns = nil - zone.Zone.Nsec3 = nil - zone.Zone.Nsec3param = nil - zone.Zone.Ptr = nil - zone.Zone.Rp = nil - zone.Zone.Rrsig = nil - zone.Zone.Spf = nil - zone.Zone.Srv = nil - zone.Zone.Sshfp = nil - zone.Zone.Txt = nil - - return zone.Save() -} - -func (zone *Zone) AddRecord(recordPtr interface{}) error { - switch recordPtr.(type) { - case *ARecord: - zone.addARecord(recordPtr.(*ARecord)) - case *AaaaRecord: - zone.addAaaaRecord(recordPtr.(*AaaaRecord)) - case *AfsdbRecord: - zone.addAfsdbRecord(recordPtr.(*AfsdbRecord)) - case *CnameRecord: - zone.addCnameRecord(recordPtr.(*CnameRecord)) - case *DnskeyRecord: - zone.addDnskeyRecord(recordPtr.(*DnskeyRecord)) - case *DsRecord: - zone.addDsRecord(recordPtr.(*DsRecord)) - case *HinfoRecord: - zone.addHinfoRecord(recordPtr.(*HinfoRecord)) - case *LocRecord: - zone.addLocRecord(recordPtr.(*LocRecord)) - case *MxRecord: - zone.addMxRecord(recordPtr.(*MxRecord)) - case *NaptrRecord: - zone.addNaptrRecord(recordPtr.(*NaptrRecord)) - case *NsRecord: - zone.addNsRecord(recordPtr.(*NsRecord)) - case *Nsec3Record: - zone.addNsec3Record(recordPtr.(*Nsec3Record)) - case *Nsec3paramRecord: - zone.addNsec3paramRecord(recordPtr.(*Nsec3paramRecord)) - case *PtrRecord: - zone.addPtrRecord(recordPtr.(*PtrRecord)) - case *RpRecord: - zone.addRpRecord(recordPtr.(*RpRecord)) - case *RrsigRecord: - zone.addRrsigRecord(recordPtr.(*RrsigRecord)) - case *SoaRecord: - zone.addSoaRecord(recordPtr.(*SoaRecord)) - case *SpfRecord: - zone.addSpfRecord(recordPtr.(*SpfRecord)) - case *SrvRecord: - zone.addSrvRecord(recordPtr.(*SrvRecord)) - case *SshfpRecord: - zone.addSshfpRecord(recordPtr.(*SshfpRecord)) - case *TxtRecord: - zone.addTxtRecord(recordPtr.(*TxtRecord)) - } - - return nil -} - -func (zone *Zone) RemoveRecord(recordPtr interface{}) error { - switch recordPtr.(type) { - case *ARecord: - return zone.removeARecord(recordPtr.(*ARecord)) - case *AaaaRecord: - return zone.removeAaaaRecord(recordPtr.(*AaaaRecord)) - case *AfsdbRecord: - return zone.removeAfsdbRecord(recordPtr.(*AfsdbRecord)) - case *CnameRecord: - return zone.removeCnameRecord(recordPtr.(*CnameRecord)) - case *DnskeyRecord: - return zone.removeDnskeyRecord(recordPtr.(*DnskeyRecord)) - case *DsRecord: - return zone.removeDsRecord(recordPtr.(*DsRecord)) - case *HinfoRecord: - return zone.removeHinfoRecord(recordPtr.(*HinfoRecord)) - case *LocRecord: - return zone.removeLocRecord(recordPtr.(*LocRecord)) - case *MxRecord: - return zone.removeMxRecord(recordPtr.(*MxRecord)) - case *NaptrRecord: - return zone.removeNaptrRecord(recordPtr.(*NaptrRecord)) - case *NsRecord: - return zone.removeNsRecord(recordPtr.(*NsRecord)) - case *Nsec3Record: - return zone.removeNsec3Record(recordPtr.(*Nsec3Record)) - case *Nsec3paramRecord: - return zone.removeNsec3paramRecord(recordPtr.(*Nsec3paramRecord)) - case *PtrRecord: - return zone.removePtrRecord(recordPtr.(*PtrRecord)) - case *RpRecord: - return zone.removeRpRecord(recordPtr.(*RpRecord)) - case *RrsigRecord: - return zone.removeRrsigRecord(recordPtr.(*RrsigRecord)) - case *SoaRecord: - return zone.removeSoaRecord(recordPtr.(*SoaRecord)) - case *SpfRecord: - return zone.removeSpfRecord(recordPtr.(*SpfRecord)) - case *SrvRecord: - return zone.removeSrvRecord(recordPtr.(*SrvRecord)) - case *SshfpRecord: - return zone.removeSshfpRecord(recordPtr.(*SshfpRecord)) - case *TxtRecord: - return zone.removeTxtRecord(recordPtr.(*TxtRecord)) - } - - return nil -} - -func (zone *Zone) addARecord(record *ARecord) { - zone.Zone.A = append(zone.Zone.A, record) - nonCnameNames = append(nonCnameNames, name{recordType: "A", name: record.Name}) -} - -func (zone *Zone) addAaaaRecord(record *AaaaRecord) { - zone.Zone.Aaaa = append(zone.Zone.Aaaa, record) - nonCnameNames = append(nonCnameNames, name{recordType: "AAAA", name: record.Name}) -} - -func (zone *Zone) addAfsdbRecord(record *AfsdbRecord) { - zone.Zone.Afsdb = append(zone.Zone.Afsdb, record) - nonCnameNames = append(nonCnameNames, name{recordType: "AFSDB", name: record.Name}) -} - -func (zone *Zone) addCnameRecord(record *CnameRecord) { - zone.Zone.Cname = append(zone.Zone.Cname, record) - cnameNames = append(cnameNames, name{recordType: "CNAME", name: record.Name}) -} - -func (zone *Zone) addDnskeyRecord(record *DnskeyRecord) { - zone.Zone.Dnskey = append(zone.Zone.Dnskey, record) - nonCnameNames = append(nonCnameNames, name{recordType: "DNSKEY", name: record.Name}) -} - -func (zone *Zone) addDsRecord(record *DsRecord) { - zone.Zone.Ds = append(zone.Zone.Ds, record) - nonCnameNames = append(nonCnameNames, name{recordType: "DS", name: record.Name}) -} - -func (zone *Zone) addHinfoRecord(record *HinfoRecord) { - zone.Zone.Hinfo = append(zone.Zone.Hinfo, record) - nonCnameNames = append(nonCnameNames, name{recordType: "HINFO", name: record.Name}) -} - -func (zone *Zone) addLocRecord(record *LocRecord) { - zone.Zone.Loc = append(zone.Zone.Loc, record) - nonCnameNames = append(nonCnameNames, name{recordType: "LOC", name: record.Name}) -} - -func (zone *Zone) addMxRecord(record *MxRecord) { - zone.Zone.Mx = append(zone.Zone.Mx, record) - nonCnameNames = append(nonCnameNames, name{recordType: "MX", name: record.Name}) -} - -func (zone *Zone) addNaptrRecord(record *NaptrRecord) { - zone.Zone.Naptr = append(zone.Zone.Naptr, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NAPTR", name: record.Name}) -} - -func (zone *Zone) addNsRecord(record *NsRecord) { - zone.Zone.Ns = append(zone.Zone.Ns, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NS", name: record.Name}) -} - -func (zone *Zone) addNsec3Record(record *Nsec3Record) { - zone.Zone.Nsec3 = append(zone.Zone.Nsec3, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NSEC3", name: record.Name}) -} - -func (zone *Zone) addNsec3paramRecord(record *Nsec3paramRecord) { - zone.Zone.Nsec3param = append(zone.Zone.Nsec3param, record) - nonCnameNames = append(nonCnameNames, name{recordType: "NSEC3PARAM", name: record.Name}) -} - -func (zone *Zone) addPtrRecord(record *PtrRecord) { - zone.Zone.Ptr = append(zone.Zone.Ptr, record) - nonCnameNames = append(nonCnameNames, name{recordType: "PTR", name: record.Name}) -} - -func (zone *Zone) addRpRecord(record *RpRecord) { - zone.Zone.Rp = append(zone.Zone.Rp, record) - nonCnameNames = append(nonCnameNames, name{recordType: "RP", name: record.Name}) -} - -func (zone *Zone) addRrsigRecord(record *RrsigRecord) { - zone.Zone.Rrsig = append(zone.Zone.Rrsig, record) - nonCnameNames = append(nonCnameNames, name{recordType: "RRSIG", name: record.Name}) -} - -func (zone *Zone) addSoaRecord(record *SoaRecord) { - // Only one SOA records is allowed - zone.Zone.Soa = record -} - -func (zone *Zone) addSpfRecord(record *SpfRecord) { - zone.Zone.Spf = append(zone.Zone.Spf, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SPF", name: record.Name}) -} - -func (zone *Zone) addSrvRecord(record *SrvRecord) { - zone.Zone.Srv = append(zone.Zone.Srv, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SRV", name: record.Name}) -} - -func (zone *Zone) addSshfpRecord(record *SshfpRecord) { - zone.Zone.Sshfp = append(zone.Zone.Sshfp, record) - nonCnameNames = append(nonCnameNames, name{recordType: "SSHFP", name: record.Name}) -} - -func (zone *Zone) addTxtRecord(record *TxtRecord) { - zone.Zone.Txt = append(zone.Zone.Txt, record) - nonCnameNames = append(nonCnameNames, name{recordType: "TXT", name: record.Name}) -} - -func (zone *Zone) removeARecord(record *ARecord) error { - for key, r := range zone.Zone.A { - if reflect.DeepEqual(r, record) { - records := zone.Zone.A[:key] - if len(zone.Zone.A) > key { - if len(zone.Zone.A) > key { - zone.Zone.A = append(records, zone.Zone.A[key+1:]...) - } else { - zone.Zone.A = records - } - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("A Record not found") -} - -func (zone *Zone) removeAaaaRecord(record *AaaaRecord) error { - for key, r := range zone.Zone.Aaaa { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Aaaa[:key] - if len(zone.Zone.Aaaa) > key { - zone.Zone.Aaaa = append(records, zone.Zone.Aaaa[key+1:]...) - } else { - zone.Zone.Aaaa = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("AAAA Record not found") -} - -func (zone *Zone) removeAfsdbRecord(record *AfsdbRecord) error { - for key, r := range zone.Zone.Afsdb { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Afsdb[:key] - if len(zone.Zone.Afsdb) > key { - zone.Zone.Afsdb = append(records, zone.Zone.Afsdb[key+1:]...) - } else { - zone.Zone.Afsdb = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Afsdb Record not found") -} - -func (zone *Zone) removeCnameRecord(record *CnameRecord) error { - for key, r := range zone.Zone.Cname { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Cname[:key] - if len(zone.Zone.Cname) > key { - zone.Zone.Cname = append(records, zone.Zone.Cname[key+1:]...) - } else { - zone.Zone.Cname = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Cname Record not found") - - zone.removeCnameName(record.Name) - - return nil -} - -func (zone *Zone) removeDnskeyRecord(record *DnskeyRecord) error { - for key, r := range zone.Zone.Dnskey { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Dnskey[:key] - if len(zone.Zone.Dnskey) > key { - zone.Zone.Dnskey = append(records, zone.Zone.Dnskey[key+1:]...) - } else { - zone.Zone.Dnskey = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Dnskey Record not found") -} - -func (zone *Zone) removeDsRecord(record *DsRecord) error { - for key, r := range zone.Zone.Ds { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ds[:key] - if len(zone.Zone.Ds) > key { - zone.Zone.Ds = append(records, zone.Zone.Ds[key+1:]...) - } else { - zone.Zone.Ds = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ds Record not found") -} - -func (zone *Zone) removeHinfoRecord(record *HinfoRecord) error { - for key, r := range zone.Zone.Hinfo { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Hinfo[:key] - if len(zone.Zone.Hinfo) > key { - zone.Zone.Hinfo = append(records, zone.Zone.Hinfo[key+1:]...) - } else { - zone.Zone.Hinfo = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Hinfo Record not found") -} - -func (zone *Zone) removeLocRecord(record *LocRecord) error { - for key, r := range zone.Zone.Loc { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Loc[:key] - if len(zone.Zone.Loc) > key { - zone.Zone.Loc = append(records, zone.Zone.Loc[key+1:]...) - } else { - zone.Zone.Loc = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Loc Record not found") -} - -func (zone *Zone) removeMxRecord(record *MxRecord) error { - for key, r := range zone.Zone.Mx { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Mx[:key] - if len(zone.Zone.Mx) > key { - zone.Zone.Mx = append(records, zone.Zone.Mx[key+1:]...) - } else { - zone.Zone.Mx = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Mx Record not found") -} - -func (zone *Zone) removeNaptrRecord(record *NaptrRecord) error { - for key, r := range zone.Zone.Naptr { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Naptr[:key] - if len(zone.Zone.Naptr) > key { - zone.Zone.Naptr = append(records, zone.Zone.Naptr[key+1:]...) - } else { - zone.Zone.Naptr = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Naptr Record not found") -} - -func (zone *Zone) removeNsRecord(record *NsRecord) error { - for key, r := range zone.Zone.Ns { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ns[:key] - if len(zone.Zone.Ns) > key { - zone.Zone.Ns = append(records, zone.Zone.Ns[key+1:]...) - } else { - zone.Zone.Ns = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ns Record not found") -} - -func (zone *Zone) removeNsec3Record(record *Nsec3Record) error { - for key, r := range zone.Zone.Nsec3 { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Nsec3[:key] - if len(zone.Zone.Nsec3) > key { - zone.Zone.Nsec3 = append(records, zone.Zone.Nsec3[key+1:]...) - } else { - zone.Zone.Nsec3 = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Nsec3 Record not found") -} - -func (zone *Zone) removeNsec3paramRecord(record *Nsec3paramRecord) error { - for key, r := range zone.Zone.Nsec3param { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Nsec3param[:key] - if len(zone.Zone.Nsec3param) > key { - zone.Zone.Nsec3param = append(records, zone.Zone.Nsec3param[key+1:]...) - } else { - zone.Zone.Nsec3param = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Nsec3param Record not found") -} - -func (zone *Zone) removePtrRecord(record *PtrRecord) error { - for key, r := range zone.Zone.Ptr { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Ptr[:key] - if len(zone.Zone.Ptr) > key { - zone.Zone.Ptr = append(records, zone.Zone.Ptr[key+1:]...) - } else { - zone.Zone.Ptr = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Ptr Record not found") -} - -func (zone *Zone) removeRpRecord(record *RpRecord) error { - for key, r := range zone.Zone.Rp { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Rp[:key] - if len(zone.Zone.Rp) > key { - zone.Zone.Rp = append(records, zone.Zone.Rp[key+1:]...) - } else { - zone.Zone.Rp = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Rp Record not found") -} - -func (zone *Zone) removeRrsigRecord(record *RrsigRecord) error { - for key, r := range zone.Zone.Rrsig { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Rrsig[:key] - if len(zone.Zone.Rrsig) > key { - zone.Zone.Rrsig = append(records, zone.Zone.Rrsig[key+1:]...) - } else { - zone.Zone.Rrsig = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Rrsig Record not found") -} - -func (zone *Zone) removeSoaRecord(record *SoaRecord) error { - if reflect.DeepEqual(zone.Zone.Soa, record) { - zone.Zone.Soa = nil - - return nil - } - - return errors.New("SOA Record does not match") -} - -func (zone *Zone) removeSpfRecord(record *SpfRecord) error { - for key, r := range zone.Zone.Spf { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Spf[:key] - if len(zone.Zone.Spf) > key { - zone.Zone.Spf = append(records, zone.Zone.Spf[key+1:]...) - } else { - zone.Zone.Spf = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Spf Record not found") -} - -func (zone *Zone) removeSrvRecord(record *SrvRecord) error { - for key, r := range zone.Zone.Srv { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Srv[:key] - if len(zone.Zone.Srv) > key { - zone.Zone.Srv = append(records, zone.Zone.Srv[key+1:]...) - } else { - zone.Zone.Srv = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Srv Record not found") -} - -func (zone *Zone) removeSshfpRecord(record *SshfpRecord) error { - for key, r := range zone.Zone.Sshfp { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Sshfp[:key] - if len(zone.Zone.Sshfp) > key { - zone.Zone.Sshfp = append(records, zone.Zone.Sshfp[key+1:]...) - } else { - zone.Zone.Sshfp = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Sshfp Record not found") -} - -func (zone *Zone) removeTxtRecord(record *TxtRecord) error { - for key, r := range zone.Zone.Txt { - if reflect.DeepEqual(r, record) { - records := zone.Zone.Txt[:key] - if len(zone.Zone.Txt) > key { - zone.Zone.Txt = append(records, zone.Zone.Txt[key+1:]...) - } else { - zone.Zone.Txt = records - } - zone.removeNonCnameName(record.Name) - - return nil - } - } - - return errors.New("Txt Record not found") -} - -func (zone *Zone) PostUnmarshalJSON() error { - if zone.Zone.Soa.Serial > 0 { - zone.Zone.Soa.originalSerial = zone.Zone.Soa.Serial - } - return nil -} - -func (zone *Zone) PreMarshalJSON() error { - if zone.Zone.Soa.Serial == 0 { - zone.Zone.Soa.Serial = uint(time.Now().Unix()) - } else if zone.Zone.Soa.Serial == zone.Zone.Soa.originalSerial { - zone.Zone.Soa.Serial = zone.Zone.Soa.Serial + 1 - } - return nil -} - -func (zone *Zone) validateCnames() (bool, []name) { - var valid bool = true - var failedRecords []name - for _, v := range cnameNames { - for _, vv := range nonCnameNames { - if v.name == vv.name { - valid = false - failedRecords = append(failedRecords, vv) - } - } - } - return valid, failedRecords -} - -func (zone *Zone) removeCnameName(host string) { - var ncn []name - for _, v := range cnameNames { - if v.name != host { - ncn =append(ncn, v) - } - } - cnameNames = ncn -} - - -func (zone *Zone) removeNonCnameName(host string) { - var ncn []name - for _, v := range nonCnameNames { - if v.name != host { - ncn =append(ncn, v) - } - } - nonCnameNames = ncn -} - -func (zone *Zone) FindRecords(recordType string, options map[string]interface{}) []DNSRecord { - switch strings.ToUpper(recordType) { - case "A": - return zone.findARecord(options) - case "AAAA": - return zone.findAaaaRecord(options) - case "AFSDB": - return zone.findAfsdbRecord(options) - case "CNAME": - return zone.findCnameRecord(options) - case "DNSKEY": - return zone.findDnskeyRecord(options) - case "DS": - return zone.findDsRecord(options) - case "HINFO": - return zone.findHinfoRecord(options) - case "LOC": - return zone.findLocRecord(options) - case "MX": - return zone.findMxRecord(options) - case "NAPTR": - return zone.findNaptrRecord(options) - case "NS": - return zone.findNsRecord(options) - case "NSEC3": - return zone.findNsec3Record(options) - case "NSEC3PARAM": - return zone.findNsec3paramRecord(options) - case "PTR": - return zone.findPtrRecord(options) - case "RP": - return zone.findRpRecord(options) - case "RRSIG": - return zone.findRrsigRecord(options) - case "SPF": - return zone.findSpfRecord(options) - case "SRV": - return zone.findSrvRecord(options) - case "SSHFP": - return zone.findSshfpRecord(options) - case "TXT": - return zone.findTxtRecord(options) - } - - return make([]DNSRecord, 0) -} - -func (zone *Zone) findARecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.A { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - - return found -} - -func (zone *Zone) findAaaaRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Aaaa { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - - return found -} - -func (zone *Zone) findAfsdbRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Afsdb { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if subtype, ok := options["subtype"]; ok && record.Subtype == subtype.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findCnameRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Cname { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findDnskeyRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Dnskey { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if protocol, ok := options["protocol"]; ok && record.Protocol == protocol.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if key, ok := options["key"]; ok && record.Key == key.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findDsRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ds { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if keytag, ok := options["keytag"]; ok && record.Keytag == keytag.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if digesttype, ok := options["digesttype"]; ok && record.DigestType == digesttype.(int) { - matchCounter++ - } - - if digest, ok := options["digest"]; ok && record.Digest == digest.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findHinfoRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Hinfo { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if hardware, ok := options["hardware"]; ok && record.Hardware == hardware.(string) { - matchCounter++ - } - - if software, ok := options["software"]; ok && record.Software == software.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findLocRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Loc { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findMxRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Mx { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if priority, ok := options["priority"]; ok && record.Priority == priority.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNaptrRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Naptr { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if order, ok := options["order"]; ok && record.Order == order.(uint16) { - matchCounter++ - } - - if preference, ok := options["preference"]; ok && record.Preference == preference.(uint16) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(string) { - matchCounter++ - } - - if service, ok := options["service"]; ok && record.Service == service.(string) { - matchCounter++ - } - - if regexp, ok := options["regexp"]; ok && record.Regexp == regexp.(string) { - matchCounter++ - } - - if replacement, ok := options["replacement"]; ok && record.Replacement == replacement.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ns { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsec3Record(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Nsec3 { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if iterations, ok := options["iterations"]; ok && record.Iterations == iterations.(int) { - matchCounter++ - } - - if salt, ok := options["salt"]; ok && record.Salt == salt.(string) { - matchCounter++ - } - - if nextHashedOwnerName, ok := options["nextHashedOwnerName"]; ok && record.NextHashedOwnerName == nextHashedOwnerName.(string) { - matchCounter++ - } - - if typeBitmaps, ok := options["typeBitmaps"]; ok && record.TypeBitmaps == typeBitmaps.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findNsec3paramRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Nsec3param { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if flags, ok := options["flags"]; ok && record.Flags == flags.(int) { - matchCounter++ - } - - if iterations, ok := options["iterations"]; ok && record.Iterations == iterations.(int) { - matchCounter++ - } - - if salt, ok := options["salt"]; ok && record.Salt == salt.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findPtrRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Ptr { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findRpRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Rp { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if mailbox, ok := options["mailbox"]; ok && record.Mailbox == mailbox.(string) { - matchCounter++ - } - - if txt, ok := options["txt"]; ok && record.Txt == txt.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findRrsigRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Rrsig { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if typeCovered, ok := options["typeCovered"]; ok && record.TypeCovered == typeCovered.(string) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if originalTTL, ok := options["originalTTL"]; ok && record.OriginalTTL == originalTTL.(int) { - matchCounter++ - } - - if expiration, ok := options["expiration"]; ok && record.Expiration == expiration.(string) { - matchCounter++ - } - - if inception, ok := options["inception"]; ok && record.Inception == inception.(string) { - matchCounter++ - } - - if keytag, ok := options["keytag"]; ok && record.Keytag == keytag.(int) { - matchCounter++ - } - - if signer, ok := options["signer"]; ok && record.Signer == signer.(string) { - matchCounter++ - } - - if signature, ok := options["signature"]; ok && record.Signature == signature.(string) { - matchCounter++ - } - - if labels, ok := options["labels"]; ok && record.Labels == labels.(int) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSpfRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Spf { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSrvRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Srv { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if priority, ok := options["priority"]; ok && record.Priority == priority.(int) { - matchCounter++ - } - - if weight, ok := options["weight"]; ok && record.Weight == weight.(uint16) { - matchCounter++ - } - - if port, ok := options["port"]; ok && record.Port == port.(uint16) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findSshfpRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Sshfp { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if algorithm, ok := options["algorithm"]; ok && record.Algorithm == algorithm.(int) { - matchCounter++ - } - - if fingerprintType, ok := options["fingerprintType"]; ok && record.FingerprintType == fingerprintType.(int) { - matchCounter++ - } - - if fingerprint, ok := options["fingerprint"]; ok && record.Fingerprint == fingerprint.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} - -func (zone *Zone) findTxtRecord(options map[string]interface{}) []DNSRecord { - found := make([]DNSRecord, 0) - matchesNeeded := len(options) - for _, record := range zone.Zone.Txt { - matchCounter := 0 - if name, ok := options["name"]; ok && record.Name == name.(string) { - matchCounter++ - } - - if active, ok := options["active"]; ok && record.Active == active.(bool) { - matchCounter++ - } - - if ttl, ok := options["ttl"]; ok && record.TTL == ttl.(int) { - matchCounter++ - } - - if target, ok := options["target"]; ok && record.Target == target.(string) { - matchCounter++ - } - - if matchCounter >= matchesNeeded { - found = append(found, record) - } - } - return found -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go deleted file mode 100644 index 35a6719c4..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/config.go +++ /dev/null @@ -1,181 +0,0 @@ -package edgegrid - -import ( - "fmt" - "os" - "strconv" - "strings" - - "github.com/go-ini/ini" - "github.com/mitchellh/go-homedir" -) - -// Config struct provides all the necessary fields to -// create authorization header, debug is optional -type Config struct { - Host string `ini:"host"` - ClientToken string `ini:"client_token"` - ClientSecret string `ini:"client_secret"` - AccessToken string `ini:"access_token"` - HeaderToSign []string `ini:"headers_to_sign"` - MaxBody int `ini:"max_body"` - Debug bool `ini:"debug"` -} - -// Init initializes by first attempting to use ENV vars, with .edgerc as a fallback -// -// See: InitEnv() -// See: InitEdgeRc() -func Init(filepath string, section string) (Config, error) { - if section == "" { - section = defaultSection - } else { - section = strings.ToUpper(section) - } - - _, exists := os.LookupEnv("AKAMAI_" + section + "_HOST") - if !exists && section == defaultSection { - _, exists := os.LookupEnv("AKAMAI_HOST") - - if exists { - return InitEnv("") - } - } - - if exists { - return InitEnv(section) - } - - c, err := InitEdgeRc(filepath, strings.ToLower(section)) - - if err == nil { - return c, nil - } - - if section != defaultSection { - _, ok := os.LookupEnv("AKAMAI_HOST") - if ok { - return InitEnv("") - } - } - - return c, fmt.Errorf("Unable to create instance using environment or .edgerc file") -} - -// InitEdgeRc initializes using a configuration file in standard INI format -// -// By default, it uses the .edgerc found in the users home directory, and the -// "default" section. -func InitEdgeRc(filepath string, section string) (Config, error) { - var ( - c Config - requiredOptions = []string{"host", "client_token", "client_secret", "access_token"} - missing []string - ) - - // Check if filepath is empty - if filepath == "" { - filepath = "~/.edgerc" - } - - // Check if section is empty - if section == "" { - section = "default" - } - - // Tilde seems to be not working when passing ~/.edgerc as file - // Takes current user and use home dir instead - - path, err := homedir.Expand(filepath) - - if err != nil { - return c, fmt.Errorf(errorMap[ErrHomeDirNotFound], err) - } - - edgerc, err := ini.Load(path) - if err != nil { - return c, fmt.Errorf(errorMap[ErrConfigFile], err) - } - err = edgerc.Section(section).MapTo(&c) - if err != nil { - return c, fmt.Errorf(errorMap[ErrConfigFileSection], err) - } - for _, opt := range requiredOptions { - if !(edgerc.Section(section).HasKey(opt)) { - missing = append(missing, opt) - } - } - if len(missing) > 0 { - return c, fmt.Errorf(errorMap[ErrConfigMissingOptions], missing) - } - if c.MaxBody == 0 { - c.MaxBody = 131072 - } - return c, nil -} - -// InitEnv initializes using the Environment (ENV) -// -// By default, it uses AKAMAI_HOST, AKAMAI_CLIENT_TOKEN, AKAMAI_CLIENT_SECRET, -// AKAMAI_ACCESS_TOKEN, and AKAMAI_MAX_BODY variables. -// -// You can define multiple configurations by prefixing with the section name specified, e.g. -// passing "ccu" will cause it to look for AKAMAI_CCU_HOST, etc. -// -// If AKAMAI_{SECTION} does not exist, it will fall back to just AKAMAI_. -func InitEnv(section string) (Config, error) { - var ( - c Config - requiredOptions = []string{"HOST", "CLIENT_TOKEN", "CLIENT_SECRET", "ACCESS_TOKEN"} - missing []string - prefix string - ) - - // Check if section is empty - if section == "" { - section = defaultSection - } else { - section = strings.ToUpper(section) - } - - prefix = "AKAMAI_" - _, ok := os.LookupEnv("AKAMAI_" + section + "_HOST") - if ok { - prefix = "AKAMAI_" + section + "_" - } - - for _, opt := range requiredOptions { - val, ok := os.LookupEnv(prefix + opt) - if !ok { - missing = append(missing, prefix+opt) - } else { - switch { - case opt == "HOST": - c.Host = val - case opt == "CLIENT_TOKEN": - c.ClientToken = val - case opt == "CLIENT_SECRET": - c.ClientSecret = val - case opt == "ACCESS_TOKEN": - c.AccessToken = val - } - } - } - - if len(missing) > 0 { - return c, fmt.Errorf(errorMap[ErrMissingEnvVariables], missing) - } - - c.MaxBody = 0 - - val, ok := os.LookupEnv(prefix + "MAX_BODY") - if i, err := strconv.Atoi(val); err == nil { - c.MaxBody = i - } - - if !ok || c.MaxBody == 0 { - c.MaxBody = 131072 - } - - return c, nil -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go deleted file mode 100644 index d5448aeae..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/errors.go +++ /dev/null @@ -1,22 +0,0 @@ -package edgegrid - -// Error constants -const ( - ErrUUIDGenerateFailed = 500 - ErrHomeDirNotFound = 501 - ErrConfigFile = 502 - ErrConfigFileSection = 503 - ErrConfigMissingOptions = 504 - ErrMissingEnvVariables = 505 -) - -var ( - errorMap = map[int]string{ - ErrUUIDGenerateFailed: "Generate UUID failed: %s", - ErrHomeDirNotFound: "Fatal could not find home dir from user: %s", - ErrConfigFile: "Fatal error edgegrid file: %s", - ErrConfigFileSection: "Could not map section: %s", - ErrConfigMissingOptions: "Fatal missing required options: %s", - ErrMissingEnvVariables: "Fatal missing required environment variables: %s", - } -) diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go deleted file mode 100644 index 27e6d0659..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid/signer.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package edgegrid allows you to sign http.Request's using the Akamai OPEN Edgegrid Signing Scheme -package edgegrid - -import ( - "bytes" - "crypto/hmac" - "crypto/sha256" - "encoding/base64" - "fmt" - "io/ioutil" - "net/http" - "sort" - "strings" - "time" - "unicode" - - "github.com/google/uuid" - log "github.com/sirupsen/logrus" -) - -const defaultSection = "DEFAULT" - -// AddRequestHeader sets the Authorization header to use Akamai Open API -func AddRequestHeader(config Config, req *http.Request) *http.Request { - if config.Debug { - log.SetLevel(log.DebugLevel) - } - timestamp := makeEdgeTimeStamp() - nonce := createNonce() - - if req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "application/json") - } - - req.Header.Set("Authorization", createAuthHeader(config, req, timestamp, nonce)) - return req -} - -// Must be assigned the UTC time when the request is signed. -// Format of “yyyyMMddTHH:mm:ss+0000” -func makeEdgeTimeStamp() string { - local := time.FixedZone("GMT", 0) - t := time.Now().In(local) - return fmt.Sprintf("%d%02d%02dT%02d:%02d:%02d+0000", - t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second()) -} - -// Must be assigned a nonce (number used once) for the request. -// It is a random string used to detect replayed request messages. -// A GUID is recommended. -func createNonce() string { - uuid, err := uuid.NewRandom() - if err != nil { - log.Errorf(errorMap[ErrUUIDGenerateFailed], err) - return "" - } - return uuid.String() -} - -func stringMinifier(in string) (out string) { - white := false - for _, c := range in { - if unicode.IsSpace(c) { - if !white { - out = out + " " - } - white = true - } else { - out = out + string(c) - white = false - } - } - return -} - -func concatPathQuery(path, query string) string { - if query == "" { - return path - } - return fmt.Sprintf("%s?%s", path, query) -} - -// createSignature is the base64-encoding of the SHA–256 HMAC of the data to sign with the signing key. -func createSignature(message string, secret string) string { - key := []byte(secret) - h := hmac.New(sha256.New, key) - h.Write([]byte(message)) - return base64.StdEncoding.EncodeToString(h.Sum(nil)) -} - -func createHash(data string) string { - h := sha256.Sum256([]byte(data)) - return base64.StdEncoding.EncodeToString(h[:]) -} - -func canonicalizeHeaders(config Config, req *http.Request) string { - var unsortedHeader []string - var sortedHeader []string - for k := range req.Header { - unsortedHeader = append(unsortedHeader, k) - } - sort.Strings(unsortedHeader) - for _, k := range unsortedHeader { - for _, sign := range config.HeaderToSign { - if sign == k { - v := strings.TrimSpace(req.Header.Get(k)) - sortedHeader = append(sortedHeader, fmt.Sprintf("%s:%s", strings.ToLower(k), strings.ToLower(stringMinifier(v)))) - } - } - } - return strings.Join(sortedHeader, "\t") - -} - -// signingKey is derived from the client secret. -// The signing key is computed as the base64 encoding of the SHA–256 HMAC of the timestamp string -// (the field value included in the HTTP authorization header described above) with the client secret as the key. -func signingKey(config Config, timestamp string) string { - key := createSignature(timestamp, config.ClientSecret) - return key -} - -// The content hash is the base64-encoded SHA–256 hash of the POST body. -// For any other request methods, this field is empty. But the tac separator (\t) must be included. -// The size of the POST body must be less than or equal to the value specified by the service. -// Any request that does not meet this criteria SHOULD be rejected during the signing process, -// as the request will be rejected by EdgeGrid. -func createContentHash(config Config, req *http.Request) string { - var ( - contentHash string - preparedBody string - bodyBytes []byte - ) - if req.Body != nil { - bodyBytes, _ = ioutil.ReadAll(req.Body) - req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes)) - preparedBody = string(bodyBytes) - } - - log.Debugf("Body is %s", preparedBody) - if req.Method == "POST" && len(preparedBody) > 0 { - log.Debugf("Signing content: %s", preparedBody) - if len(preparedBody) > config.MaxBody { - log.Debugf("Data length %d is larger than maximum %d", - len(preparedBody), config.MaxBody) - - preparedBody = preparedBody[0:config.MaxBody] - log.Debugf("Data truncated to %d for computing the hash", len(preparedBody)) - } - contentHash = createHash(preparedBody) - } - log.Debugf("Content hash is '%s'", contentHash) - return contentHash -} - -// The data to sign includes the information from the HTTP request that is relevant to ensuring that the request is authentic. -// This data set comprised of the request data combined with the authorization header value (excluding the signature field, -// but including the ; right before the signature field). -func signingData(config Config, req *http.Request, authHeader string) string { - - dataSign := []string{ - req.Method, - req.URL.Scheme, - req.URL.Host, - concatPathQuery(req.URL.Path, req.URL.RawQuery), - canonicalizeHeaders(config, req), - createContentHash(config, req), - authHeader, - } - log.Debugf("Data to sign %s", strings.Join(dataSign, "\t")) - return strings.Join(dataSign, "\t") -} - -func signingRequest(config Config, req *http.Request, authHeader string, timestamp string) string { - return createSignature(signingData(config, req, authHeader), - signingKey(config, timestamp)) -} - -// The Authorization header starts with the signing algorithm moniker (name of the algorithm) used to sign the request. -// The moniker below identifies EdgeGrid V1, hash message authentication code, SHA–256 as the hash standard. -// This moniker is then followed by a space and an ordered list of name value pairs with each field separated by a semicolon. -func createAuthHeader(config Config, req *http.Request, timestamp string, nonce string) string { - authHeader := fmt.Sprintf("EG1-HMAC-SHA256 client_token=%s;access_token=%s;timestamp=%s;nonce=%s;", - config.ClientToken, - config.AccessToken, - timestamp, - nonce, - ) - log.Debugf("Unsigned authorization header: '%s'", authHeader) - - signedAuthHeader := fmt.Sprintf("%ssignature=%s", authHeader, signingRequest(config, req, authHeader, timestamp)) - - log.Debugf("Signed authorization header: '%s'", signedAuthHeader) - return signedAuthHeader -} diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go deleted file mode 100644 index 594c04e41..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/errors.go +++ /dev/null @@ -1 +0,0 @@ -package jsonhooks diff --git a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go b/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go deleted file mode 100644 index 24c5b8bb8..000000000 --- a/vendor/github.com/akamai/AkamaiOPEN-edgegrid-golang/jsonhooks-v1/jsonhooks.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package jsonhooks adds hooks that are automatically called before JSON marshaling (PreMarshalJSON) and -// after JSON unmarshaling (PostUnmarshalJSON). It does not do so recursively. -package jsonhooks - -import ( - "encoding/json" - "reflect" -) - -// Marshal wraps encoding/json.Marshal, calls v.PreMarshalJSON() if it exists -func Marshal(v interface{}) ([]byte, error) { - if ImplementsPreJSONMarshaler(v) { - err := v.(PreJSONMarshaler).PreMarshalJSON() - if err != nil { - return nil, err - } - } - - return json.Marshal(v) -} - -// Unmarshal wraps encoding/json.Unmarshal, calls v.PostUnmarshalJSON() if it exists -func Unmarshal(data []byte, v interface{}) error { - err := json.Unmarshal(data, v) - if err != nil { - return err - } - - if ImplementsPostJSONUnmarshaler(v) { - err := v.(PostJSONUnmarshaler).PostUnmarshalJSON() - if err != nil { - return err - } - } - - return nil -} - -// PreJSONMarshaler infers support for the PreMarshalJSON pre-hook -type PreJSONMarshaler interface { - PreMarshalJSON() error -} - -// ImplementsPreJSONMarshaler checks for support for the PreMarshalJSON pre-hook -func ImplementsPreJSONMarshaler(v interface{}) bool { - value := reflect.ValueOf(v) - if !value.IsValid() { - return false - } - - _, ok := value.Interface().(PreJSONMarshaler) - return ok -} - -// PostJSONUnmarshaler infers support for the PostUnmarshalJSON post-hook -type PostJSONUnmarshaler interface { - PostUnmarshalJSON() error -} - -// ImplementsPostJSONUnmarshaler checks for support for the PostUnmarshalJSON post-hook -func ImplementsPostJSONUnmarshaler(v interface{}) bool { - value := reflect.ValueOf(v) - if value.Kind() == reflect.Ptr && value.IsNil() { - return false - } - - _, ok := value.Interface().(PostJSONUnmarshaler) - return ok -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/LICENSE deleted file mode 100644 index 261eeb9e9..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/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/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go deleted file mode 100644 index 7f20b7a40..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credential.go +++ /dev/null @@ -1,18 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -type Credential interface { -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go deleted file mode 100644 index 68f822633..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/access_key_credential.go +++ /dev/null @@ -1,34 +0,0 @@ -package credentials - -// Deprecated: Use AccessKeyCredential in this package instead. -type BaseCredential struct { - AccessKeyId string - AccessKeySecret string -} - -type AccessKeyCredential struct { - AccessKeyId string - AccessKeySecret string -} - -// Deprecated: Use NewAccessKeyCredential in this package instead. -func NewBaseCredential(accessKeyId, accessKeySecret string) *BaseCredential { - return &BaseCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} - -func (baseCred *BaseCredential) ToAccessKeyCredential() *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: baseCred.AccessKeyId, - AccessKeySecret: baseCred.AccessKeySecret, - } -} - -func NewAccessKeyCredential(accessKeyId, accessKeySecret string) *AccessKeyCredential { - return &AccessKeyCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go deleted file mode 100644 index 1e1f73ae4..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/ecs_ram_role.go +++ /dev/null @@ -1,29 +0,0 @@ -package credentials - -// Deprecated: Use EcsRamRoleCredential in this package instead. -type StsRoleNameOnEcsCredential struct { - RoleName string -} - -// Deprecated: Use NewEcsRamRoleCredential in this package instead. -func NewStsRoleNameOnEcsCredential(roleName string) *StsRoleNameOnEcsCredential { - return &StsRoleNameOnEcsCredential{ - RoleName: roleName, - } -} - -func (oldCred *StsRoleNameOnEcsCredential) ToEcsRamRoleCredential() *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: oldCred.RoleName, - } -} - -type EcsRamRoleCredential struct { - RoleName string -} - -func NewEcsRamRoleCredential(roleName string) *EcsRamRoleCredential { - return &EcsRamRoleCredential{ - RoleName: roleName, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go deleted file mode 100644 index 00d688eb8..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/rsa_key_pair_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type RsaKeyPairCredential struct { - PrivateKey string - PublicKeyId string - SessionExpiration int -} - -func NewRsaKeyPairCredential(privateKey, publicKeyId string, sessionExpiration int) *RsaKeyPairCredential { - return &RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go deleted file mode 100644 index 554431ff0..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_credential.go +++ /dev/null @@ -1,15 +0,0 @@ -package credentials - -type StsTokenCredential struct { - AccessKeyId string - AccessKeySecret string - AccessKeyStsToken string -} - -func NewStsTokenCredential(accessKeyId, accessKeySecret, accessKeyStsToken string) *StsTokenCredential { - return &StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: accessKeyStsToken, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go deleted file mode 100644 index 7a9db75d2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials/sts_role_arn_credential.go +++ /dev/null @@ -1,49 +0,0 @@ -package credentials - -// Deprecated: Use RamRoleArnCredential in this package instead. -type StsRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int -} - -type RamRoleArnCredential struct { - AccessKeyId string - AccessKeySecret string - RoleArn string - RoleSessionName string - RoleSessionExpiration int -} - -// Deprecated: Use RamRoleArnCredential in this package instead. -func NewStsRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *StsRoleArnCredential { - return &StsRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} - -func (oldCred *StsRoleArnCredential) ToRamRoleArnCredential() *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: oldCred.AccessKeyId, - AccessKeySecret: oldCred.AccessKeySecret, - RoleArn: oldCred.RoleArn, - RoleSessionName: oldCred.RoleSessionName, - RoleSessionExpiration: oldCred.RoleSessionExpiration, - } -} - -func NewRamRoleArnCredential(accessKeyId, accessKeySecret, roleArn, roleSessionName string, roleSessionExpiration int) *RamRoleArnCredential { - return &RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - RoleSessionExpiration: roleSessionExpiration, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go deleted file mode 100644 index 8666dd064..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/roa_signature_composer.go +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "bytes" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "sort" - "strings" -) - -func signRoaRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - completeROASignParams(request, signer, regionId) - stringToSign := buildRoaStringToSign(request) - request.SetStringToSign(stringToSign) - signature := signer.Sign(stringToSign, "") - accessKeyId, err := signer.GetAccessKeyId() - if err != nil { - return nil - } - - request.GetHeaders()["Authorization"] = "acs " + accessKeyId + ":" + signature - - return -} - -func completeROASignParams(request requests.AcsRequest, signer Signer, regionId string) { - headerParams := request.GetHeaders() - - // complete query params - queryParams := request.GetQueryParams() - //if _, ok := queryParams["RegionId"]; !ok { - // queryParams["RegionId"] = regionId - //} - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - if key == "SecurityToken" { - headerParams["x-acs-security-token"] = value - continue - } - - queryParams[key] = value - } - } - - // complete header params - headerParams["Date"] = utils.GetTimeInFormatRFC2616() - headerParams["x-acs-signature-method"] = signer.GetName() - headerParams["x-acs-signature-version"] = signer.GetVersion() - if request.GetFormParams() != nil && len(request.GetFormParams()) > 0 { - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - headerParams["Content-Type"] = requests.Form - } - contentMD5 := utils.GetMD5Base64(request.GetContent()) - headerParams["Content-MD5"] = contentMD5 - if _, contains := headerParams["Content-Type"]; !contains { - headerParams["Content-Type"] = requests.Raw - } - switch format := request.GetAcceptFormat(); format { - case "JSON": - headerParams["Accept"] = requests.Json - case "XML": - headerParams["Accept"] = requests.Xml - default: - headerParams["Accept"] = requests.Raw - } -} - -func buildRoaStringToSign(request requests.AcsRequest) (stringToSign string) { - - headers := request.GetHeaders() - - stringToSignBuilder := bytes.Buffer{} - stringToSignBuilder.WriteString(request.GetMethod()) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - - // append header keys for sign - appendIfContain(headers, &stringToSignBuilder, "Accept", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-MD5", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Content-Type", requests.HeaderSeparator) - appendIfContain(headers, &stringToSignBuilder, "Date", requests.HeaderSeparator) - - // sort and append headers witch starts with 'x-acs-' - var acsHeaders []string - for key := range headers { - if strings.HasPrefix(key, "x-acs-") { - acsHeaders = append(acsHeaders, key) - } - } - sort.Strings(acsHeaders) - for _, key := range acsHeaders { - stringToSignBuilder.WriteString(key + ":" + headers[key]) - stringToSignBuilder.WriteString(requests.HeaderSeparator) - } - - // append query params - stringToSignBuilder.WriteString(request.BuildQueries()) - stringToSign = stringToSignBuilder.String() - return -} - -func appendIfContain(sourceMap map[string]string, target *bytes.Buffer, key, separator string) { - if value, contain := sourceMap[key]; contain && len(value) > 0 { - target.WriteString(sourceMap[key]) - target.WriteString(separator) - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go deleted file mode 100644 index 0c6f6d111..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/rpc_signature_composer.go +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "net/url" - "sort" - "strings" -) - -func signRpcRequest(request requests.AcsRequest, signer Signer, regionId string) (err error) { - err = completeRpcSignParams(request, signer, regionId) - if err != nil { - return - } - // remove while retry - if _, containsSign := request.GetQueryParams()["Signature"]; containsSign { - delete(request.GetQueryParams(), "Signature") - } - stringToSign := buildRpcStringToSign(request) - request.SetStringToSign(stringToSign) - signature := signer.Sign(stringToSign, "&") - request.GetQueryParams()["Signature"] = signature - - return -} - -func completeRpcSignParams(request requests.AcsRequest, signer Signer, regionId string) (err error) { - queryParams := request.GetQueryParams() - queryParams["Version"] = request.GetVersion() - queryParams["Action"] = request.GetActionName() - queryParams["Format"] = request.GetAcceptFormat() - queryParams["Timestamp"] = utils.GetTimeInFormatISO8601() - queryParams["SignatureMethod"] = signer.GetName() - queryParams["SignatureType"] = signer.GetType() - queryParams["SignatureVersion"] = signer.GetVersion() - queryParams["SignatureNonce"] = utils.GetUUIDV4() - queryParams["AccessKeyId"], err = signer.GetAccessKeyId() - - if err != nil { - return - } - - if _, contains := queryParams["RegionId"]; !contains { - queryParams["RegionId"] = regionId - } - if extraParam := signer.GetExtraParam(); extraParam != nil { - for key, value := range extraParam { - queryParams[key] = value - } - } - - request.GetHeaders()["Content-Type"] = requests.Form - formString := utils.GetUrlFormedMap(request.GetFormParams()) - request.SetContent([]byte(formString)) - - return -} - -func buildRpcStringToSign(request requests.AcsRequest) (stringToSign string) { - signParams := make(map[string]string) - for key, value := range request.GetQueryParams() { - signParams[key] = value - } - for key, value := range request.GetFormParams() { - signParams[key] = value - } - - // sort params by key - var paramKeySlice []string - for key := range signParams { - paramKeySlice = append(paramKeySlice, key) - } - sort.Strings(paramKeySlice) - stringToSign = utils.GetUrlFormedMap(signParams) - stringToSign = strings.Replace(stringToSign, "+", "%20", -1) - stringToSign = strings.Replace(stringToSign, "*", "%2A", -1) - stringToSign = strings.Replace(stringToSign, "%7E", "~", -1) - stringToSign = url.QueryEscape(stringToSign) - stringToSign = request.GetMethod() + "&%2F&" + stringToSign - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go deleted file mode 100644 index ba946d0fd..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signer.go +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package auth - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "reflect" -) - -type Signer interface { - GetName() string - GetType() string - GetVersion() string - GetAccessKeyId() (string, error) - GetExtraParam() map[string]string - Sign(stringToSign, secretSuffix string) string - Shutdown() -} - -func NewSignerWithCredential(credential Credential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer Signer, err error) { - switch instance := credential.(type) { - case *credentials.AccessKeyCredential: - { - signer, err = signers.NewAccessKeySigner(instance) - } - case *credentials.StsTokenCredential: - { - signer, err = signers.NewStsTokenSigner(instance) - } - - case *credentials.RamRoleArnCredential: - { - signer, err = signers.NewRamRoleArnSigner(instance, commonApi) - } - case *credentials.RsaKeyPairCredential: - { - signer, err = signers.NewSignerKeyPair(instance, commonApi) - } - case *credentials.EcsRamRoleCredential: - { - signer, err = signers.NewEcsRamRoleSigner(instance, commonApi) - } - case *credentials.BaseCredential: // deprecated user interface - { - signer, err = signers.NewAccessKeySigner(instance.ToAccessKeyCredential()) - } - case *credentials.StsRoleArnCredential: // deprecated user interface - { - signer, err = signers.NewRamRoleArnSigner(instance.ToRamRoleArnCredential(), commonApi) - } - case *credentials.StsRoleNameOnEcsCredential: // deprecated user interface - { - signer, err = signers.NewEcsRamRoleSigner(instance.ToEcsRamRoleCredential(), commonApi) - } - default: - message := fmt.Sprintf(errors.UnsupportedCredentialErrorMessage, reflect.TypeOf(credential)) - err = errors.NewClientError(errors.UnsupportedCredentialErrorCode, message, nil) - } - return -} - -func Sign(request requests.AcsRequest, signer Signer, regionId string) (err error) { - switch request.GetStyle() { - case requests.ROA: - { - signRoaRequest(request, signer, regionId) - } - case requests.RPC: - { - err = signRpcRequest(request, signer, regionId) - } - default: - message := fmt.Sprintf(errors.UnknownRequestTypeErrorMessage, reflect.TypeOf(request)) - err = errors.NewClientError(errors.UnknownRequestTypeErrorCode, message, nil) - } - - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go deleted file mode 100644 index 975e985b9..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/algorithms.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "crypto" - "crypto/hmac" - "crypto/rand" - "crypto/rsa" - "crypto/sha1" - "crypto/x509" - "encoding/base64" - "fmt" - /*"encoding/pem" - "io/ioutil" - "os/user" - "crypto/sha256"*/) - -func ShaHmac1(source, secret string) string { - key := []byte(secret) - hmac := hmac.New(sha1.New, key) - hmac.Write([]byte(source)) - signedBytes := hmac.Sum(nil) - signedString := base64.StdEncoding.EncodeToString(signedBytes) - return signedString -} - -func Sha256WithRsa(source, secret string) string { - decodeString, err := base64.StdEncoding.DecodeString(secret) - if err != nil { - fmt.Println("DecodeString err", err) - } - private, err := x509.ParsePKCS8PrivateKey(decodeString) - if err != nil { - fmt.Println("ParsePKCS8PrivateKey err", err) - } - - h := crypto.Hash.New(crypto.SHA256) - h.Write([]byte(source)) - hashed := h.Sum(nil) - signature, err := rsa.SignPKCS1v15(rand.Reader, private.(*rsa.PrivateKey), - crypto.SHA256, hashed) - if err != nil { - fmt.Println("Error from signing:", err) - return "" - } - - signedString := base64.StdEncoding.EncodeToString(signature) - //fmt.Printf("Encoded: %v\n", signedString) - return signedString -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go deleted file mode 100644 index bb73d2441..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/credential_updater.go +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "time" -) - -const defaultInAdvanceScale = 0.8 - -type credentialUpdater struct { - credentialExpiration int - lastUpdateTimestamp int64 - inAdvanceScale float64 - buildRequestMethod func() (*requests.CommonRequest, error) - responseCallBack func(response *responses.CommonResponse) error - refreshApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) -} - -func (updater *credentialUpdater) needUpdateCredential() (result bool) { - if updater.inAdvanceScale == 0 { - updater.inAdvanceScale = defaultInAdvanceScale - } - return time.Now().Unix()-updater.lastUpdateTimestamp >= int64(float64(updater.credentialExpiration)*updater.inAdvanceScale) -} - -func (updater *credentialUpdater) updateCredential() (err error) { - request, err := updater.buildRequestMethod() - if err != nil { - return - } - response, err := updater.refreshApi(request) - if err != nil { - return - } - updater.lastUpdateTimestamp = time.Now().Unix() - err = updater.responseCallBack(response) - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go deleted file mode 100644 index 99c624c88..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/session_credential.go +++ /dev/null @@ -1,7 +0,0 @@ -package signers - -type SessionCredential struct { - AccessKeyId string - AccessKeySecret string - StsToken string -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go deleted file mode 100644 index 92466ea55..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_access_key.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type AccessKeySigner struct { - credential *credentials.AccessKeyCredential -} - -func (signer *AccessKeySigner) GetExtraParam() map[string]string { - return nil -} - -func NewAccessKeySigner(credential *credentials.AccessKeyCredential) (*AccessKeySigner, error) { - return &AccessKeySigner{ - credential: credential, - }, nil -} - -func (*AccessKeySigner) GetName() string { - return "HMAC-SHA1" -} - -func (*AccessKeySigner) GetType() string { - return "" -} - -func (*AccessKeySigner) GetVersion() string { - return "1.0" -} - -func (signer *AccessKeySigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *AccessKeySigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *AccessKeySigner) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go deleted file mode 100644 index 6cacc140d..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ecs_ram_role.go +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strings" - "time" -) - -type EcsRamRoleSigner struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.EcsRamRoleCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewEcsRamRoleSigner(credential *credentials.EcsRamRoleCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *EcsRamRoleSigner, err error) { - signer = &EcsRamRoleSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: defaultDurationSeconds / 60, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - return -} - -func (*EcsRamRoleSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*EcsRamRoleSigner) GetType() string { - return "" -} - -func (*EcsRamRoleSigner) GetVersion() string { - return "1.0" -} - -func (signer *EcsRamRoleSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *EcsRamRoleSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil { - return make(map[string]string) - } - if len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *EcsRamRoleSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeyId + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *EcsRamRoleSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - return -} - -func (signer *EcsRamRoleSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - requestUrl := "http://100.100.100.200/latest/meta-data/ram/security-credentials/" + signer.credential.RoleName - httpRequest, err := http.NewRequest(requests.GET, requestUrl, strings.NewReader("")) - if err != nil { - fmt.Println("refresh Ecs sts token err", err) - return - } - httpClient := &http.Client{} - httpResponse, err := httpClient.Do(httpRequest) - if err != nil { - fmt.Println("refresh Ecs sts token err", err) - return - } - - response = responses.NewCommonResponse() - err = responses.Unmarshal(response, httpResponse, "") - - return -} - -func (signer *EcsRamRoleSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - fmt.Println("refresh Ecs sts token err, httpStatus: " + string(response.GetHttpStatus()) + ", message = " + response.GetHttpContentString()) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh Ecs sts token err, json.Unmarshal fail", err) - return - } - code, err := jmespath.Search("Code", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get Code", err) - return - } - if code.(string) != "Success" { - fmt.Println("refresh Ecs sts token err, Code is not Success", err) - return - } - accessKeyId, err := jmespath.Search("AccessKeyId", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get AccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("AccessKeySecret", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get AccessKeySecret", err) - return - } - securityToken, err := jmespath.Search("SecurityToken", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get SecurityToken", err) - return - } - expiration, err := jmespath.Search("Expiration", data) - if err != nil { - fmt.Println("refresh Ecs sts token err, fail to get Expiration", err) - return - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil { - return - } - - expirationTime, err := time.Parse("2006-01-02T15:04:05Z", expiration.(string)) - signer.credentialExpiration = int(expirationTime.Unix() - time.Now().Unix()) - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - - return -} - -func (signer *EcsRamRoleSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} - -func (signer *EcsRamRoleSigner) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go deleted file mode 100644 index c5fe39456..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_key_pair.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strconv" -) - -type SignerKeyPair struct { - *credentialUpdater - sessionCredential *SessionCredential - credential *credentials.RsaKeyPairCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewSignerKeyPair(credential *credentials.RsaKeyPairCredential, commonApi func(*requests.CommonRequest, interface{}) (response *responses.CommonResponse, err error)) (signer *SignerKeyPair, err error) { - signer = &SignerKeyPair{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.SessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if credential.SessionExpiration > 0 { - if credential.SessionExpiration >= 900 && credential.SessionExpiration <= 3600 { - signer.credentialExpiration = credential.SessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Key Pair session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*SignerKeyPair) GetName() string { - return "HMAC-SHA1" -} - -func (*SignerKeyPair) GetType() string { - return "" -} - -func (*SignerKeyPair) GetVersion() string { - return "1.0" -} - -func (signer *SignerKeyPair) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, err -} - -func (signer *SignerKeyPair) GetExtraParam() map[string]string { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - signer.updateCredential() - } - if signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0 { - return make(map[string]string) - } - return make(map[string]string) -} - -func (signer *SignerKeyPair) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeyId + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *SignerKeyPair) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "GenerateSessionAccessKey" - request.Scheme = requests.HTTPS - request.QueryParams["PublicKeyId"] = signer.credential.PublicKeyId - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signerKeyPair *SignerKeyPair) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - signerV2, err := NewSignerV2(signerKeyPair.credential) - return signerKeyPair.commonApi(request, signerV2) -} - -func (signer *SignerKeyPair) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session AccessKey failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh KeyPair err, json.Unmarshal fail", err) - return - } - accessKeyId, err := jmespath.Search("SessionAccessKey.SessionAccessKeyId", data) - if err != nil { - fmt.Println("refresh KeyPair err, fail to get SessionAccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("SessionAccessKey.SessionAccessKeySecret", data) - if err != nil { - fmt.Println("refresh KeyPair err, fail to get SessionAccessKeySecret", err) - return - } - if accessKeyId == nil || accessKeySecret == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - } - return -} - -func (signer *SignerKeyPair) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go deleted file mode 100644 index bfcaa9573..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_ram_role_arn.go +++ /dev/null @@ -1,174 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "github.com/jmespath/go-jmespath" - "net/http" - "strconv" - "time" -) - -const ( - defaultDurationSeconds = 3600 -) - -type RamRoleArnSigner struct { - *credentialUpdater - roleSessionName string - sessionCredential *SessionCredential - credential *credentials.RamRoleArnCredential - commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error) -} - -func NewRamRoleArnSigner(credential *credentials.RamRoleArnCredential, commonApi func(request *requests.CommonRequest, signer interface{}) (response *responses.CommonResponse, err error)) (signer *RamRoleArnSigner, err error) { - signer = &RamRoleArnSigner{ - credential: credential, - commonApi: commonApi, - } - - signer.credentialUpdater = &credentialUpdater{ - credentialExpiration: credential.RoleSessionExpiration, - buildRequestMethod: signer.buildCommonRequest, - responseCallBack: signer.refreshCredential, - refreshApi: signer.refreshApi, - } - - if len(credential.RoleSessionName) > 0 { - signer.roleSessionName = credential.RoleSessionName - } else { - signer.roleSessionName = "aliyun-go-sdk-" + strconv.FormatInt(time.Now().UnixNano()/1000, 10) - } - if credential.RoleSessionExpiration > 0 { - if credential.RoleSessionExpiration >= 900 && credential.RoleSessionExpiration <= 3600 { - signer.credentialExpiration = credential.RoleSessionExpiration - } else { - err = errors.NewClientError(errors.InvalidParamErrorCode, "Assume Role session duration should be in the range of 15min - 1Hr", nil) - } - } else { - signer.credentialExpiration = defaultDurationSeconds - } - return -} - -func (*RamRoleArnSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*RamRoleArnSigner) GetType() string { - return "" -} - -func (*RamRoleArnSigner) GetVersion() string { - return "1.0" -} - -func (signer *RamRoleArnSigner) GetAccessKeyId() (accessKeyId string, err error) { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - err = signer.updateCredential() - } - if err != nil && (signer.sessionCredential == nil || len(signer.sessionCredential.AccessKeyId) <= 0) { - return "", err - } - return signer.sessionCredential.AccessKeyId, nil -} - -func (signer *RamRoleArnSigner) GetExtraParam() map[string]string { - if signer.sessionCredential == nil || signer.needUpdateCredential() { - signer.updateCredential() - } - if signer.sessionCredential == nil || len(signer.sessionCredential.StsToken) <= 0 { - return make(map[string]string) - } - return map[string]string{"SecurityToken": signer.sessionCredential.StsToken} -} - -func (signer *RamRoleArnSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.sessionCredential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *RamRoleArnSigner) buildCommonRequest() (request *requests.CommonRequest, err error) { - request = requests.NewCommonRequest() - request.Product = "Sts" - request.Version = "2015-04-01" - request.ApiName = "AssumeRole" - request.Scheme = requests.HTTPS - request.QueryParams["RoleArn"] = signer.credential.RoleArn - request.QueryParams["RoleSessionName"] = signer.credential.RoleSessionName - request.QueryParams["DurationSeconds"] = strconv.Itoa(signer.credentialExpiration) - return -} - -func (signer *RamRoleArnSigner) refreshApi(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - credential := &credentials.AccessKeyCredential{ - AccessKeyId: signer.credential.AccessKeyId, - AccessKeySecret: signer.credential.AccessKeySecret, - } - signerV1, err := NewAccessKeySigner(credential) - return signer.commonApi(request, signerV1) -} - -func (signer *RamRoleArnSigner) refreshCredential(response *responses.CommonResponse) (err error) { - if response.GetHttpStatus() != http.StatusOK { - message := "refresh session token failed" - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), message) - return - } - var data interface{} - err = json.Unmarshal(response.GetHttpContentBytes(), &data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, json.Unmarshal fail", err) - return - } - accessKeyId, err := jmespath.Search("Credentials.AccessKeyId", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get AccessKeyId", err) - return - } - accessKeySecret, err := jmespath.Search("Credentials.AccessKeySecret", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get AccessKeySecret", err) - return - } - securityToken, err := jmespath.Search("Credentials.SecurityToken", data) - if err != nil { - fmt.Println("refresh RoleArn sts token err, fail to get SecurityToken", err) - return - } - if accessKeyId == nil || accessKeySecret == nil || securityToken == nil { - return - } - signer.sessionCredential = &SessionCredential{ - AccessKeyId: accessKeyId.(string), - AccessKeySecret: accessKeySecret.(string), - StsToken: securityToken.(string), - } - return -} - -func (signer *RamRoleArnSigner) GetSessionCredential() *SessionCredential { - return signer.sessionCredential -} - -func (signer *RamRoleArnSigner) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go deleted file mode 100644 index 9e178d0fb..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_sts_token.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type StsTokenSigner struct { - credential *credentials.StsTokenCredential -} - -func NewStsTokenSigner(credential *credentials.StsTokenCredential) (*StsTokenSigner, error) { - return &StsTokenSigner{ - credential: credential, - }, nil -} - -func (*StsTokenSigner) GetName() string { - return "HMAC-SHA1" -} - -func (*StsTokenSigner) GetType() string { - return "" -} - -func (*StsTokenSigner) GetVersion() string { - return "1.0" -} - -func (signer *StsTokenSigner) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.AccessKeyId, nil -} - -func (signer *StsTokenSigner) GetExtraParam() map[string]string { - return map[string]string{"SecurityToken": signer.credential.AccessKeyStsToken} -} - -func (signer *StsTokenSigner) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.AccessKeySecret + secretSuffix - return ShaHmac1(stringToSign, secret) -} - -func (signer *StsTokenSigner) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go deleted file mode 100644 index 1814fe7bd..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/signers/signer_v2.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package signers - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" -) - -type SignerV2 struct { - credential *credentials.RsaKeyPairCredential -} - -func (signer *SignerV2) GetExtraParam() map[string]string { - return nil -} - -func NewSignerV2(credential *credentials.RsaKeyPairCredential) (*SignerV2, error) { - return &SignerV2{ - credential: credential, - }, nil -} - -func (*SignerV2) GetName() string { - return "SHA256withRSA" -} - -func (*SignerV2) GetType() string { - return "PRIVATEKEY" -} - -func (*SignerV2) GetVersion() string { - return "1.0" -} - -func (signer *SignerV2) GetAccessKeyId() (accessKeyId string, err error) { - return signer.credential.PublicKeyId, err -} - -func (signer *SignerV2) Sign(stringToSign, secretSuffix string) string { - secret := signer.credential.PrivateKey - return Sha256WithRsa(stringToSign, secret) -} - -func (signer *SignerV2) Shutdown() { - -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go deleted file mode 100644 index e204676ba..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/client.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sdk - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "net" - "net/http" - "strconv" - "sync" -) - -// this value will be replaced while build: -ldflags="-X sdk.version=x.x.x" -var Version = "0.0.1" - -type Client struct { - regionId string - config *Config - signer auth.Signer - httpClient *http.Client - asyncTaskQueue chan func() - - debug bool - isRunning bool - // void "panic(write to close channel)" cause of addAsync() after Shutdown() - asyncChanLock *sync.RWMutex -} - -func (client *Client) Init() (err error) { - panic("not support yet") -} - -func (client *Client) InitWithOptions(regionId string, config *Config, credential auth.Credential) (err error) { - client.isRunning = true - client.asyncChanLock = new(sync.RWMutex) - client.regionId = regionId - client.config = config - if err != nil { - return - } - client.httpClient = &http.Client{} - - if config.HttpTransport != nil { - client.httpClient.Transport = config.HttpTransport - } - - if config.Timeout > 0 { - client.httpClient.Timeout = config.Timeout - } - - if config.EnableAsync { - client.EnableAsync(config.GoRoutinePoolSize, config.MaxTaskQueueSize) - } - - client.signer, err = auth.NewSignerWithCredential(credential, client.ProcessCommonRequestWithSigner) - - return -} - -func (client *Client) EnableAsync(routinePoolSize, maxTaskQueueSize int) { - client.asyncTaskQueue = make(chan func(), maxTaskQueueSize) - for i := 0; i < routinePoolSize; i++ { - go func() { - for client.isRunning { - select { - case task, notClosed := <-client.asyncTaskQueue: - if notClosed { - task() - } - } - } - }() - } -} - -func (client *Client) InitWithAccessKey(regionId, accessKeyId, accessKeySecret string) (err error) { - config := client.InitClientConfig() - credential := &credentials.BaseCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithStsToken(regionId, accessKeyId, accessKeySecret, securityToken string) (err error) { - config := client.InitClientConfig() - credential := &credentials.StsTokenCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - AccessKeyStsToken: securityToken, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.RamRoleArnCredential{ - AccessKeyId: accessKeyId, - AccessKeySecret: accessKeySecret, - RoleArn: roleArn, - RoleSessionName: roleSessionName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithRsaKeyPair(regionId, publicKeyId, privateKey string, sessionExpiration int) (err error) { - config := client.InitClientConfig() - credential := &credentials.RsaKeyPairCredential{ - PrivateKey: privateKey, - PublicKeyId: publicKeyId, - SessionExpiration: sessionExpiration, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitWithEcsRamRole(regionId, roleName string) (err error) { - config := client.InitClientConfig() - credential := &credentials.EcsRamRoleCredential{ - RoleName: roleName, - } - return client.InitWithOptions(regionId, config, credential) -} - -func (client *Client) InitClientConfig() (config *Config) { - if client.config != nil { - return client.config - } else { - return NewConfig() - } -} - -func (client *Client) DoAction(request requests.AcsRequest, response responses.AcsResponse) (err error) { - return client.DoActionWithSigner(request, response, nil) -} - -func (client *Client) BuildRequestWithSigner(request requests.AcsRequest, signer auth.Signer) (err error) { - // add clientVersion - request.GetHeaders()["x-sdk-core-version"] = Version - - regionId := client.regionId - if len(request.GetRegionId()) > 0 { - regionId = request.GetRegionId() - } - - // resolve endpoint - resolveParam := &endpoints.ResolveParam{ - Domain: request.GetDomain(), - Product: request.GetProduct(), - RegionId: regionId, - LocationProduct: request.GetLocationServiceCode(), - LocationEndpointType: request.GetLocationEndpointType(), - CommonApi: client.ProcessCommonRequest, - } - endpoint, err := endpoints.Resolve(resolveParam) - if err != nil { - return - } - request.SetDomain(endpoint) - - // init request params - err = requests.InitParams(request) - if err != nil { - return - } - - // signature - var finalSigner auth.Signer - if signer != nil { - finalSigner = signer - } else { - finalSigner = client.signer - } - httpRequest, err := buildHttpRequest(request, finalSigner, regionId) - if client.config.UserAgent != "" { - httpRequest.Header.Set("User-Agent", client.config.UserAgent) - } - return err -} - -func (client *Client) DoActionWithSigner(request requests.AcsRequest, response responses.AcsResponse, signer auth.Signer) (err error) { - - // add clientVersion - request.GetHeaders()["x-sdk-core-version"] = Version - - regionId := client.regionId - if len(request.GetRegionId()) > 0 { - regionId = request.GetRegionId() - } - - // resolve endpoint - resolveParam := &endpoints.ResolveParam{ - Domain: request.GetDomain(), - Product: request.GetProduct(), - RegionId: regionId, - LocationProduct: request.GetLocationServiceCode(), - LocationEndpointType: request.GetLocationEndpointType(), - CommonApi: client.ProcessCommonRequest, - } - endpoint, err := endpoints.Resolve(resolveParam) - if err != nil { - return - } - request.SetDomain(endpoint) - - if request.GetScheme() == "" { - request.SetScheme(client.config.Scheme) - } - // init request params - err = requests.InitParams(request) - if err != nil { - return - } - - // signature - var finalSigner auth.Signer - if signer != nil { - finalSigner = signer - } else { - finalSigner = client.signer - } - httpRequest, err := buildHttpRequest(request, finalSigner, regionId) - if client.config.UserAgent != "" { - httpRequest.Header.Set("User-Agent", client.config.UserAgent) - } - if err != nil { - return - } - var httpResponse *http.Response - for retryTimes := 0; retryTimes <= client.config.MaxRetryTime; retryTimes++ { - httpResponse, err = client.httpClient.Do(httpRequest) - - var timeout bool - // receive error - if err != nil { - if !client.config.AutoRetry { - return - } else if timeout = isTimeout(err); !timeout { - // if not timeout error, return - return - } else if retryTimes >= client.config.MaxRetryTime { - // timeout but reached the max retry times, return - timeoutErrorMsg := fmt.Sprintf(errors.TimeoutErrorMessage, strconv.Itoa(retryTimes+1), strconv.Itoa(retryTimes+1)) - err = errors.NewClientError(errors.TimeoutErrorCode, timeoutErrorMsg, err) - return - } - } - // if status code >= 500 or timeout, will trigger retry - if client.config.AutoRetry && (timeout || isServerError(httpResponse)) { - // rewrite signatureNonce and signature - httpRequest, err = buildHttpRequest(request, finalSigner, regionId) - if err != nil { - return - } - continue - } - break - } - err = responses.Unmarshal(response, httpResponse, request.GetAcceptFormat()) - // wrap server errors - if serverErr, ok := err.(*errors.ServerError); ok { - var wrapInfo = map[string]string{} - wrapInfo["StringToSign"] = request.GetStringToSign() - err = errors.WrapServerError(serverErr, wrapInfo) - } - return -} - -func buildHttpRequest(request requests.AcsRequest, singer auth.Signer, regionId string) (httpRequest *http.Request, err error) { - err = auth.Sign(request, singer, regionId) - if err != nil { - return - } - requestMethod := request.GetMethod() - requestUrl := request.BuildUrl() - body := request.GetBodyReader() - httpRequest, err = http.NewRequest(requestMethod, requestUrl, body) - if err != nil { - return - } - for key, value := range request.GetHeaders() { - httpRequest.Header[key] = []string{value} - } - // host is a special case - if host, containsHost := request.GetHeaders()["Host"]; containsHost { - httpRequest.Host = host - } - return -} - -func isTimeout(err error) bool { - if err == nil { - return false - } - netErr, isNetError := err.(net.Error) - return isNetError && netErr.Timeout() -} - -func isServerError(httpResponse *http.Response) bool { - return httpResponse.StatusCode >= http.StatusInternalServerError -} - -/** -only block when any one of the following occurs: -1. the asyncTaskQueue is full, increase the queue size to avoid this -2. Shutdown() in progressing, the client is being closed -**/ -func (client *Client) AddAsyncTask(task func()) (err error) { - if client.asyncTaskQueue != nil { - client.asyncChanLock.RLock() - defer client.asyncChanLock.RUnlock() - if client.isRunning { - client.asyncTaskQueue <- task - } - } else { - err = errors.NewClientError(errors.AsyncFunctionNotEnabledCode, errors.AsyncFunctionNotEnabledMessage, nil) - } - return -} - -func (client *Client) GetConfig() *Config { - return client.config -} - -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - return -} - -func NewClientWithOptions(regionId string, config *Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - return -} - -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - return -} - -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - return -} - -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - return -} - -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - return -} - -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - return -} - -// Deprecated: Use NewClientWithRamRoleArn in this package instead. -func NewClientWithStsRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - return NewClientWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) -} - -// Deprecated: Use NewClientWithEcsRamRole in this package instead. -func NewClientWithStsRoleNameOnEcs(regionId string, roleName string) (client *Client, err error) { - return NewClientWithEcsRamRole(regionId, roleName) -} - -func (client *Client) ProcessCommonRequest(request *requests.CommonRequest) (response *responses.CommonResponse, err error) { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoAction(request, response) - return -} - -func (client *Client) ProcessCommonRequestWithSigner(request *requests.CommonRequest, signerInterface interface{}) (response *responses.CommonResponse, err error) { - if signer, isSigner := signerInterface.(auth.Signer); isSigner { - request.TransToAcsRequest() - response = responses.NewCommonResponse() - err = client.DoActionWithSigner(request, response, signer) - return - } else { - panic("should not be here") - } -} - -func (client *Client) Shutdown() { - client.signer.Shutdown() - // lock the addAsync() - client.asyncChanLock.Lock() - defer client.asyncChanLock.Unlock() - client.isRunning = false - close(client.asyncTaskQueue) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go deleted file mode 100644 index c67c2ad09..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/config.go +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package sdk - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "net/http" - "time" -) - -type Config struct { - AutoRetry bool `default:"true"` - MaxRetryTime int `default:"3"` - UserAgent string `default:""` - Debug bool `default:"false"` - Timeout time.Duration `default:"10000000000"` - HttpTransport *http.Transport `default:""` - EnableAsync bool `default:"false"` - MaxTaskQueueSize int `default:"1000"` - GoRoutinePoolSize int `default:"5"` - Scheme string `default:"HTTP"` -} - -func NewConfig() (config *Config) { - config = &Config{} - utils.InitStructWithDefaultTag(config) - return -} - -func (c *Config) WithTimeout(timeout time.Duration) *Config { - c.Timeout = timeout - return c -} - -func (c *Config) WithAutoRetry(isAutoRetry bool) *Config { - c.AutoRetry = isAutoRetry - return c -} - -func (c *Config) WithMaxRetryTime(maxRetryTime int) *Config { - c.MaxRetryTime = maxRetryTime - return c -} - -func (c *Config) WithUserAgent(userAgent string) *Config { - c.UserAgent = userAgent - return c -} - -func (c *Config) WithHttpTransport(httpTransport *http.Transport) *Config { - c.HttpTransport = httpTransport - return c -} - -func (c *Config) WithEnableAsync(isEnableAsync bool) *Config { - c.EnableAsync = isEnableAsync - return c -} - -func (c *Config) WithMaxTaskQueueSize(maxTaskQueueSize int) *Config { - c.MaxTaskQueueSize = maxTaskQueueSize - return c -} - -func (c *Config) WithGoRoutinePoolSize(goRoutinePoolSize int) *Config { - c.GoRoutinePoolSize = goRoutinePoolSize - return c -} - -func (c *Config) WithDebug(isDebug bool) *Config { - c.Debug = isDebug - return c -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go deleted file mode 100644 index ec0d56f60..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/endpoints_config.go +++ /dev/null @@ -1,505 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "sync" -) - -const endpointsJson = "{" + - " \"products\":[" + - " {" + - " \"code\": \"aegis\"," + - " \"document_id\": \"28449\"," + - " \"location_service_code\": \"vipaegis\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"aegis.cn-hangzhou.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"alidns\"," + - " \"document_id\": \"29739\"," + - " \"location_service_code\": \"alidns\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"alidns.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"arms\"," + - " \"document_id\": \"42924\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"arms.ap-southeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"arms.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"arms.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hongkong\"," + - " \"endpoint\": \"arms.cn-hongkong.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"arms.cn-qingdao.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"arms.cn-shanghai.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"arms.cn-shenzhen.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"arms.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"batchcompute\"," + - " \"document_id\": \"44717\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"batchcompute.ap-southeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"batchcompute.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"batchcompute.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-huhehaote\"," + - " \"endpoint\": \"batchcompute.cn-huhehaote.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"batchcompute.cn-qingdao.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"batchcompute.cn-shanghai.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"batchcompute.cn-shenzhen.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-zhangjiakou\"," + - " \"endpoint\": \"batchcompute.cn-zhangjiakou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"batchcompute.us-west-1.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"batchcompute.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ccc\"," + - " \"document_id\": \"63027\"," + - " \"location_service_code\": \"ccc\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"ccc.cn-hangzhou.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"ccc.cn-shanghai.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"ccc.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cdn\"," + - " \"document_id\": \"27148\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cdn.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cds\"," + - " \"document_id\": \"62887\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cds.cn-beijing.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"chatbot\"," + - " \"document_id\": \"60760\"," + - " \"location_service_code\": \"beebot\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"chatbot.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudapi\"," + - " \"document_id\": \"43590\"," + - " \"location_service_code\": \"apigateway\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-northeast-1\"," + - " \"endpoint\": \"apigateway.ap-northeast-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"apigateway.us-west-1.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"apigateway.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudauth\"," + - " \"document_id\": \"60687\"," + - " \"location_service_code\": \"cloudauth\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudauth.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cloudphoto\"," + - " \"document_id\": \"59902\"," + - " \"location_service_code\": \"cloudphoto\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"cloudphoto.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"cloudwf\"," + - " \"document_id\": \"58111\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudwf.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cms\"," + - " \"document_id\": \"28615\"," + - " \"location_service_code\": \"cms\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cr\"," + - " \"document_id\": \"60716\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cr.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"cs\"," + - " \"document_id\": \"26043\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cs.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"csb\"," + - " \"document_id\": \"64837\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"csb.cn-beijing.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"csb.cn-hangzhou.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"csb.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"dds\"," + - " \"document_id\": \"61715\"," + - " \"location_service_code\": \"dds\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"mongodb.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"mongodb.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"dm\"," + - " \"document_id\": \"29434\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-southeast-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"ap-southeast-2\"," + - " \"endpoint\": \"dm.ap-southeast-2.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-beijing\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-hongkong\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-qingdao\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shanghai\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"cn-shenzhen\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-east-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }, {" + - " \"region\": \"us-west-1\"," + - " \"endpoint\": \"dm.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"dm.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"dm.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"domain\"," + - " \"document_id\": \"42875\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"domain.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"domain.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"domain-intl\"," + - " \"document_id\": \"\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"domain-intl.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"domain-intl.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"drds\"," + - " \"document_id\": \"51111\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"drds.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"drds.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ecs\"," + - " \"document_id\": \"25484\"," + - " \"location_service_code\": \"ecs\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"emr\"," + - " \"document_id\": \"28140\"," + - " \"location_service_code\": \"emr\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"emr.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"ess\"," + - " \"document_id\": \"25925\"," + - " \"location_service_code\": \"ess\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"ess.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"green\"," + - " \"document_id\": \"28427\"," + - " \"location_service_code\": \"green\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"green.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"hpc\"," + - " \"document_id\": \"35201\"," + - " \"location_service_code\": \"hpc\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"hpc.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"httpdns\"," + - " \"document_id\": \"52679\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"httpdns-api.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"iot\"," + - " \"document_id\": \"30557\"," + - " \"location_service_code\": \"iot\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"iot.[RegionId].aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"itaas\"," + - " \"document_id\": \"55759\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"itaas.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"jaq\"," + - " \"document_id\": \"35037\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"jaq.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"live\"," + - " \"document_id\": \"48207\"," + - " \"location_service_code\": \"live\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"live.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"mts\"," + - " \"document_id\": \"29212\"," + - " \"location_service_code\": \"mts\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"nas\"," + - " \"document_id\": \"62598\"," + - " \"location_service_code\": \"nas\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ons\"," + - " \"document_id\": \"44416\"," + - " \"location_service_code\": \"ons\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"polardb\"," + - " \"document_id\": \"58764\"," + - " \"location_service_code\": \"polardb\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"ap-south-1\"," + - " \"endpoint\": \"polardb.ap-south-1.aliyuncs.com\"" + - " }, {" + - " \"region\": \"ap-southeast-5\"," + - " \"endpoint\": \"polardb.ap-southeast-5.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"polardb.aliyuncs.com\"" + - " }," + - " {" + - " \"code\": \"push\"," + - " \"document_id\": \"30074\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"cloudpush.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"qualitycheck\"," + - " \"document_id\": \"50807\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": [ {" + - " \"region\": \"cn-hangzhou\"," + - " \"endpoint\": \"qualitycheck.cn-hangzhou.aliyuncs.com\"" + - " }]," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"r-kvstore\"," + - " \"document_id\": \"60831\"," + - " \"location_service_code\": \"redisa\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ram\"," + - " \"document_id\": \"28672\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"ram.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"rds\"," + - " \"document_id\": \"26223\"," + - " \"location_service_code\": \"rds\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"ros\"," + - " \"document_id\": \"28899\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"ros.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"sas-api\"," + - " \"document_id\": \"28498\"," + - " \"location_service_code\": \"sas\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"slb\"," + - " \"document_id\": \"27565\"," + - " \"location_service_code\": \"slb\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"sts\"," + - " \"document_id\": \"28756\"," + - " \"location_service_code\": \"\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"sts.aliyuncs.com\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"vod\"," + - " \"document_id\": \"60574\"," + - " \"location_service_code\": \"vod\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"vpc\"," + - " \"document_id\": \"34962\"," + - " \"location_service_code\": \"vpc\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }," + - " {" + - " \"code\": \"waf\"," + - " \"document_id\": \"62847\"," + - " \"location_service_code\": \"waf\"," + - " \"regional_endpoints\": []," + - " \"global_endpoint\": \"\"," + - " \"regional_endpoint_pattern\": \"\"" + - " }]" + - "}" - -var initOnce sync.Once -var data interface{} - -func getEndpointConfigData() interface{} { - initOnce.Do(func() { - err := json.Unmarshal([]byte(endpointsJson), &data) - if err != nil { - fmt.Println("init endpoint config data failed.", err) - } - }) - return data -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go deleted file mode 100644 index 864b7cc4c..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_global_resolver.go +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "github.com/jmespath/go-jmespath" - "strings" -) - -type LocalGlobalResolver struct { -} - -func (resolver *LocalGlobalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the global endpoints configs - endpointExpression := fmt.Sprintf("products[?code=='%s'].global_endpoint", strings.ToLower(param.Product)) - endpointData, err := jmespath.Search(endpointExpression, getEndpointConfigData()) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return endpoint, support, nil - } - support = false - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go deleted file mode 100644 index f8aa0f92a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/local_regional_resolver.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "github.com/jmespath/go-jmespath" - "strings" -) - -type LocalRegionalResolver struct { -} - -func (resolver *LocalRegionalResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - // get the regional endpoints configs - regionalExpression := fmt.Sprintf("products[?code=='%s'].regional_endpoints", strings.ToLower(param.Product)) - regionalData, err := jmespath.Search(regionalExpression, getEndpointConfigData()) - if err == nil && regionalData != nil && len(regionalData.([]interface{})) > 0 { - endpointExpression := fmt.Sprintf("[0][?region=='%s'].endpoint", strings.ToLower(param.RegionId)) - endpointData, err := jmespath.Search(endpointExpression, regionalData) - if err == nil && endpointData != nil && len(endpointData.([]interface{})) > 0 { - endpoint = endpointData.([]interface{})[0].(string) - support = len(endpoint) > 0 - return endpoint, support, nil - } - } - support = false - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go deleted file mode 100644 index 803bc57d5..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/location_resolver.go +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package endpoints - -import ( - "encoding/json" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "sync" - "time" -) - -const ( - EndpointCacheExpireTime = 3600 //Seconds -) - -var lastClearTimePerProduct = struct { - sync.RWMutex - cache map[string]int64 -}{cache: make(map[string]int64)} - -var endpointCache = struct { - sync.RWMutex - cache map[string]string -}{cache: make(map[string]string)} - -type LocationResolver struct { -} - -func (resolver *LocationResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - if len(param.LocationProduct) <= 0 { - support = false - return - } - - //get from cache - cacheKey := param.Product + "#" + param.RegionId - if endpointCache.cache != nil && len(endpointCache.cache[cacheKey]) > 0 && !CheckCacheIsExpire(cacheKey) { - endpoint = endpointCache.cache[cacheKey] - support = true - return - } - - //get from remote - getEndpointRequest := requests.NewCommonRequest() - - getEndpointRequest.Product = "Location" - getEndpointRequest.Version = "2015-06-12" - getEndpointRequest.ApiName = "DescribeEndpoints" - getEndpointRequest.Domain = "location.aliyuncs.com" - getEndpointRequest.Method = "GET" - getEndpointRequest.Scheme = requests.HTTPS - - getEndpointRequest.QueryParams["Id"] = param.RegionId - getEndpointRequest.QueryParams["ServiceCode"] = param.LocationProduct - if len(param.LocationEndpointType) > 0 { - getEndpointRequest.QueryParams["Type"] = param.LocationEndpointType - } else { - getEndpointRequest.QueryParams["Type"] = "openAPI" - } - - response, err := param.CommonApi(getEndpointRequest) - var getEndpointResponse GetEndpointResponse - if !response.IsSuccess() { - support = false - return - } - - json.Unmarshal([]byte(response.GetHttpContentString()), &getEndpointResponse) - if !getEndpointResponse.Success || getEndpointResponse.Endpoints == nil { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint) <= 0 { - support = false - return - } - if len(getEndpointResponse.Endpoints.Endpoint[0].Endpoint) > 0 { - endpoint = getEndpointResponse.Endpoints.Endpoint[0].Endpoint - endpointCache.Lock() - endpointCache.cache[cacheKey] = endpoint - endpointCache.Unlock() - lastClearTimePerProduct.Lock() - lastClearTimePerProduct.cache[cacheKey] = time.Now().Unix() - lastClearTimePerProduct.Unlock() - support = true - return - } - - support = false - return -} - -func CheckCacheIsExpire(cacheKey string) bool { - lastClearTime := lastClearTimePerProduct.cache[cacheKey] - if lastClearTime <= 0 { - lastClearTime = time.Now().Unix() - lastClearTimePerProduct.Lock() - lastClearTimePerProduct.cache[cacheKey] = lastClearTime - lastClearTimePerProduct.Unlock() - } - - now := time.Now().Unix() - elapsedTime := now - lastClearTime - if elapsedTime > EndpointCacheExpireTime { - return true - } - - return false -} - -type GetEndpointResponse struct { - Endpoints *EndpointsObj - RequestId string - Success bool -} - -type EndpointsObj struct { - Endpoint []EndpointObj -} - -type EndpointObj struct { - Protocols map[string]string - Type string - Namespace string - Id string - SerivceCode string - Endpoint string -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go deleted file mode 100644 index f7b5a1aa2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/mapping_resolver.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "fmt" - "strings" -) - -const keyFormatter = "%s::%s" - -var endpointMapping = make(map[string]string) - -func AddEndpointMapping(regionId, productId, endpoint string) (err error) { - key := fmt.Sprintf(keyFormatter, strings.ToLower(regionId), strings.ToLower(productId)) - endpointMapping[key] = endpoint - return nil -} - -type MappingResolver struct { -} - -func (resolver *MappingResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - key := fmt.Sprintf(keyFormatter, strings.ToLower(param.RegionId), strings.ToLower(param.Product)) - endpoint, contains := endpointMapping[key] - return endpoint, contains, nil -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go deleted file mode 100644 index e58cfbf28..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/resolver.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -import ( - "encoding/json" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" - "sync" -) - -const ( - ResolveEndpointUserGuideLink = "" -) - -var once sync.Once -var resolvers []Resolver - -type Resolver interface { - TryResolve(param *ResolveParam) (endpoint string, support bool, err error) -} - -func Resolve(param *ResolveParam) (endpoint string, err error) { - supportedResolvers := getAllResolvers() - for _, resolver := range supportedResolvers { - endpoint, supported, err := resolver.TryResolve(param) - if supported { - return endpoint, err - } - } - - // not support - errorMsg := fmt.Sprintf(errors.CanNotResolveEndpointErrorMessage, param, ResolveEndpointUserGuideLink) - err = errors.NewClientError(errors.CanNotResolveEndpointErrorCode, errorMsg, nil) - return -} - -func getAllResolvers() []Resolver { - once.Do(func() { - resolvers = []Resolver{ - &SimpleHostResolver{}, - &MappingResolver{}, - &LocationResolver{}, - &LocalRegionalResolver{}, - &LocalGlobalResolver{}, - } - }) - return resolvers -} - -type ResolveParam struct { - Domain string - Product string - RegionId string - LocationProduct string - LocationEndpointType string - CommonApi func(request *requests.CommonRequest) (response *responses.CommonResponse, err error) `json:"-"` -} - -func (param *ResolveParam) String() string { - jsonBytes, err := json.Marshal(param) - if err != nil { - return fmt.Sprint("ResolveParam.String() process error:", err) - } - return string(jsonBytes) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go deleted file mode 100644 index 3e2e731ea..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/endpoints/simple_host_resolver.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package endpoints - -type SimpleHostResolver struct { -} - -func (resolver *SimpleHostResolver) TryResolve(param *ResolveParam) (endpoint string, support bool, err error) { - if support = len(param.Domain) > 0; support { - endpoint = param.Domain - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go deleted file mode 100644 index 3d4048b4e..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/client_error.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -import "fmt" - -const ( - DefaultClientErrorStatus = 400 - DefaultClientErrorCode = "SDK.ClientError" - - UnsupportedCredentialErrorCode = "SDK.UnsupportedCredential" - UnsupportedCredentialErrorMessage = "Specified credential (type = %s) is not supported, please check" - - CanNotResolveEndpointErrorCode = "SDK.CanNotResolveEndpoint" - CanNotResolveEndpointErrorMessage = "Can not resolve endpoint(param = %s), please check your accessKey with secret, and read the user guide\n %s" - - UnsupportedParamPositionErrorCode = "SDK.UnsupportedParamPosition" - UnsupportedParamPositionErrorMessage = "Specified param position (%s) is not supported, please upgrade sdk and retry" - - AsyncFunctionNotEnabledCode = "SDK.AsyncFunctionNotEnabled" - AsyncFunctionNotEnabledMessage = "Async function is not enabled in client, please invoke 'client.EnableAsync' function" - - UnknownRequestTypeErrorCode = "SDK.UnknownRequestType" - UnknownRequestTypeErrorMessage = "Unknown Request Type: %s" - - MissingParamErrorCode = "SDK.MissingParam" - InvalidParamErrorCode = "SDK.InvalidParam" - - JsonUnmarshalErrorCode = "SDK.JsonUnmarshalError" - JsonUnmarshalErrorMessage = "Failed to unmarshal response, but you can get the data via response.GetHttpStatusCode() and response.GetHttpContentString()" - - TimeoutErrorCode = "SDK.TimeoutError" - TimeoutErrorMessage = "The request timed out %s times(%s for retry), perhaps we should have the threshold raised a little?" -) - -type ClientError struct { - errorCode string - message string - originError error -} - -func NewClientError(errorCode, message string, originErr error) Error { - return &ClientError{ - errorCode: errorCode, - message: message, - originError: originErr, - } -} - -func (err *ClientError) Error() string { - clientErrMsg := fmt.Sprintf("[%s] %s", err.errorCode, err.message) - if err.originError != nil { - return clientErrMsg + "\ncaused by:\n" + err.originError.Error() - } - return clientErrMsg -} - -func (err *ClientError) OriginError() error { - return err.originError -} - -func (*ClientError) HttpStatus() int { - return DefaultClientErrorStatus -} - -func (err *ClientError) ErrorCode() string { - if err.errorCode == "" { - return DefaultClientErrorCode - } else { - return err.errorCode - } -} - -func (err *ClientError) Message() string { - return err.message -} - -func (err *ClientError) String() string { - return err.Error() -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go deleted file mode 100644 index 49962f3b5..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/error.go +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -type Error interface { - error - HttpStatus() int - ErrorCode() string - Message() string - OriginError() error -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go deleted file mode 100644 index d90638c0a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/server_error.go +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package errors - -import ( - "encoding/json" - "fmt" - "github.com/jmespath/go-jmespath" -) - -var wrapperList = []ServerErrorWrapper{ - &SignatureDostNotMatchWrapper{}, -} - -type ServerError struct { - httpStatus int - requestId string - hostId string - errorCode string - recommend string - message string - comment string -} - -type ServerErrorWrapper interface { - tryWrap(error *ServerError, wrapInfo map[string]string) (bool, *ServerError) -} - -func (err *ServerError) Error() string { - return fmt.Sprintf("SDK.ServerError\nErrorCode: %s\nRecommend: %s\nRequestId: %s\nMessage: %s", - err.errorCode, err.comment+err.recommend, err.requestId, err.message) -} - -func NewServerError(httpStatus int, responseContent, comment string) Error { - result := &ServerError{ - httpStatus: httpStatus, - message: responseContent, - comment: comment, - } - - var data interface{} - err := json.Unmarshal([]byte(responseContent), &data) - if err == nil { - requestId, _ := jmespath.Search("RequestId", data) - hostId, _ := jmespath.Search("HostId", data) - errorCode, _ := jmespath.Search("Code", data) - recommend, _ := jmespath.Search("Recommend", data) - message, _ := jmespath.Search("Message", data) - - if requestId != nil { - result.requestId = requestId.(string) - } - if hostId != nil { - result.hostId = hostId.(string) - } - if errorCode != nil { - result.errorCode = errorCode.(string) - } - if recommend != nil { - result.recommend = recommend.(string) - } - if message != nil { - result.message = message.(string) - } - } - - return result -} - -func WrapServerError(originError *ServerError, wrapInfo map[string]string) *ServerError { - for _, wrapper := range wrapperList { - ok, newError := wrapper.tryWrap(originError, wrapInfo) - if ok { - return newError - } - } - return originError -} - -func (err *ServerError) HttpStatus() int { - return err.httpStatus -} - -func (err *ServerError) ErrorCode() string { - return err.errorCode -} - -func (err *ServerError) Message() string { - return err.message -} - -func (err *ServerError) OriginError() error { - return nil -} - -func (err *ServerError) HostId() string { - return err.hostId -} - -func (err *ServerError) RequestId() string { - return err.requestId -} - -func (err *ServerError) Recommend() string { - return err.recommend -} - -func (err *ServerError) Comment() string { - return err.comment -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go deleted file mode 100644 index 33b3e4c44..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors/signature_does_not_match_wrapper.go +++ /dev/null @@ -1,29 +0,0 @@ -package errors - -import "strings" - -const SignatureDostNotMatchErrorCode = "SignatureDoesNotMatch" -const MessagePrefix = "Specified signature is not matched with our calculation. server string to sign is:" - -type SignatureDostNotMatchWrapper struct { -} - -func (*SignatureDostNotMatchWrapper) tryWrap(error *ServerError, wrapInfo map[string]string) (bool, *ServerError) { - clientStringToSign := wrapInfo["StringToSign"] - if error.errorCode == SignatureDostNotMatchErrorCode && clientStringToSign != "" { - message := error.message - if strings.HasPrefix(message, MessagePrefix) { - serverStringToSign := message[len(MessagePrefix):] - if clientStringToSign == serverStringToSign { - // user secret is error - error.recommend = "Please check you AccessKeySecret" - } else { - error.recommend = "This may be a bug with the SDK and we hope you can submit this question in the " + - "github issue(https://github.com/aliyun/alibaba-cloud-sdk-go/issues), thanks very much" - } - } - return true, error - } else { - return false, nil - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go deleted file mode 100644 index 5f4a42bb4..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/acs_reqeust.go +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io" - "reflect" - "strconv" -) - -const ( - RPC = "RPC" - ROA = "ROA" - - HTTP = "HTTP" - HTTPS = "HTTPS" - - DefaultHttpPort = "80" - - GET = "GET" - PUT = "PUT" - POST = "POST" - DELETE = "DELETE" - HEAD = "HEAD" - OPTIONS = "OPTIONS" - - Json = "application/json" - Xml = "application/xml" - Raw = "application/octet-stream" - Form = "application/x-www-form-urlencoded" - - Header = "Header" - Query = "Query" - Body = "Body" - Path = "Path" - - HeaderSeparator = "\n" -) - -// interface -type AcsRequest interface { - GetScheme() string - GetMethod() string - GetDomain() string - GetPort() string - GetRegionId() string - GetUrl() string - GetQueries() string - GetHeaders() map[string]string - GetQueryParams() map[string]string - GetFormParams() map[string]string - GetContent() []byte - GetBodyReader() io.Reader - GetStyle() string - GetProduct() string - GetVersion() string - GetActionName() string - GetAcceptFormat() string - GetLocationServiceCode() string - GetLocationEndpointType() string - - SetStringToSign(stringToSign string) - GetStringToSign() string - - SetDomain(domain string) - SetContent(content []byte) - SetScheme(scheme string) - BuildUrl() string - BuildQueries() string - - addHeaderParam(key, value string) - addQueryParam(key, value string) - addFormParam(key, value string) - addPathParam(key, value string) -} - -// base class -type baseRequest struct { - Scheme string - Method string - Domain string - Port string - RegionId string - - product string - version string - - actionName string - - AcceptFormat string - - QueryParams map[string]string - Headers map[string]string - FormParams map[string]string - Content []byte - - locationServiceCode string - locationEndpointType string - - queries string - - stringToSign string -} - -func (request *baseRequest) GetQueryParams() map[string]string { - return request.QueryParams -} - -func (request *baseRequest) GetFormParams() map[string]string { - return request.FormParams -} - -func (request *baseRequest) GetContent() []byte { - return request.Content -} - -func (request *baseRequest) GetVersion() string { - return request.version -} - -func (request *baseRequest) GetActionName() string { - return request.actionName -} - -func (request *baseRequest) SetContent(content []byte) { - request.Content = content -} - -func (request *baseRequest) addHeaderParam(key, value string) { - request.Headers[key] = value -} - -func (request *baseRequest) addQueryParam(key, value string) { - request.QueryParams[key] = value -} - -func (request *baseRequest) addFormParam(key, value string) { - request.FormParams[key] = value -} - -func (request *baseRequest) GetAcceptFormat() string { - return request.AcceptFormat -} - -func (request *baseRequest) GetLocationServiceCode() string { - return request.locationServiceCode -} - -func (request *baseRequest) GetLocationEndpointType() string { - return request.locationEndpointType -} - -func (request *baseRequest) GetProduct() string { - return request.product -} - -func (request *baseRequest) GetScheme() string { - return request.Scheme -} - -func (request *baseRequest) SetScheme(scheme string) { - request.Scheme = scheme -} - -func (request *baseRequest) GetMethod() string { - return request.Method -} - -func (request *baseRequest) GetDomain() string { - return request.Domain -} - -func (request *baseRequest) SetDomain(host string) { - request.Domain = host -} - -func (request *baseRequest) GetPort() string { - return request.Port -} - -func (request *baseRequest) GetRegionId() string { - return request.RegionId -} - -func (request *baseRequest) GetHeaders() map[string]string { - return request.Headers -} - -func (request *baseRequest) SetContentType(contentType string) { - request.Headers["Content-Type"] = contentType -} - -func (request *baseRequest) GetContentType() (contentType string, contains bool) { - contentType, contains = request.Headers["Content-Type"] - return -} - -func (request *baseRequest) SetStringToSign(stringToSign string) { - request.stringToSign = stringToSign -} - -func (request *baseRequest) GetStringToSign() string { - return request.stringToSign -} - -func defaultBaseRequest() (request *baseRequest) { - request = &baseRequest{ - Scheme: "", - AcceptFormat: "JSON", - Method: GET, - QueryParams: make(map[string]string), - Headers: map[string]string{ - "x-sdk-client": "golang/1.0.0", - "x-sdk-invoke-type": "normal", - "Accept-Encoding": "identity", - }, - FormParams: make(map[string]string), - } - return -} - -func InitParams(request AcsRequest) (err error) { - requestValue := reflect.ValueOf(request).Elem() - err = flatRepeatedList(requestValue, request, "", "") - return -} - -func flatRepeatedList(dataValue reflect.Value, request AcsRequest, position, prefix string) (err error) { - dataType := dataValue.Type() - for i := 0; i < dataType.NumField(); i++ { - field := dataType.Field(i) - name, containsNameTag := field.Tag.Lookup("name") - fieldPosition := position - if fieldPosition == "" { - fieldPosition, _ = field.Tag.Lookup("position") - } - typeTag, containsTypeTag := field.Tag.Lookup("type") - if containsNameTag { - if !containsTypeTag { - // simple param - key := prefix + name - value := dataValue.Field(i).String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else if typeTag == "Repeated" { - // repeated param - repeatedFieldValue := dataValue.Field(i) - if repeatedFieldValue.Kind() != reflect.Slice { - // possible value: {"[]string", "*[]struct"}, we must call Elem() in the last condition - repeatedFieldValue = repeatedFieldValue.Elem() - } - if repeatedFieldValue.IsValid() && !repeatedFieldValue.IsNil() { - for m := 0; m < repeatedFieldValue.Len(); m++ { - elementValue := repeatedFieldValue.Index(m) - key := prefix + name + "." + strconv.Itoa(m+1) - if elementValue.Type().String() == "string" { - value := elementValue.String() - err = addParam(request, fieldPosition, key, value) - if err != nil { - return - } - } else { - err = flatRepeatedList(elementValue, request, fieldPosition, key+".") - if err != nil { - return - } - } - } - } - } - } - } - return -} - -func addParam(request AcsRequest, position, name, value string) (err error) { - if len(value) > 0 { - switch position { - case Header: - request.addHeaderParam(name, value) - case Query: - request.addQueryParam(name, value) - case Path: - request.addPathParam(name, value) - case Body: - request.addFormParam(name, value) - default: - errMsg := fmt.Sprintf(errors.UnsupportedParamPositionErrorMessage, position) - err = errors.NewClientError(errors.UnsupportedParamPositionErrorCode, errMsg, nil) - } - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go deleted file mode 100644 index d5d841b42..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/common_request.go +++ /dev/null @@ -1,128 +0,0 @@ -package requests - -import ( - "bytes" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io" - "strings" -) - -type CommonRequest struct { - *baseRequest - - Version string - ApiName string - Product string - - // roa params - PathPattern string - PathParams map[string]string - - Ontology AcsRequest -} - -func NewCommonRequest() (request *CommonRequest) { - request = &CommonRequest{ - baseRequest: defaultBaseRequest(), - } - request.Headers["x-sdk-invoke-type"] = "common" - request.PathParams = make(map[string]string) - return -} - -func (request *CommonRequest) String() string { - request.TransToAcsRequest() - request.BuildQueries() - request.BuildUrl() - - resultBuilder := bytes.Buffer{} - - mapOutput := func(m map[string]string) { - if len(m) > 0 { - for key, value := range m { - resultBuilder.WriteString(key + ": " + value + "\n") - } - } - } - - // Request Line - resultBuilder.WriteString("\n") - resultBuilder.WriteString(fmt.Sprintf("%s %s %s/1.1\n", request.Method, request.GetQueries(), strings.ToUpper(request.Scheme))) - - // Headers - resultBuilder.WriteString("Host" + ": " + request.Domain + "\n") - mapOutput(request.Headers) - - resultBuilder.WriteString("\n") - // Body - if len(request.Content) > 0 { - resultBuilder.WriteString(string(request.Content) + "\n") - } else { - mapOutput(request.FormParams) - } - - return resultBuilder.String() -} - -func (request *CommonRequest) TransToAcsRequest() { - if len(request.Version) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "Common request [version] is required", nil) - } - if len(request.ApiName) == 0 && len(request.PathPattern) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "At least one of [ApiName] and [PathPattern] should has a value", nil) - } - if len(request.Domain) == 0 && len(request.Product) == 0 { - errors.NewClientError(errors.MissingParamErrorCode, "At least one of [Domain] and [Product] should has a value", nil) - } - - if len(request.PathPattern) > 0 { - roaRequest := &RoaRequest{} - roaRequest.initWithCommonRequest(request) - request.Ontology = roaRequest - } else { - rpcRequest := &RpcRequest{} - rpcRequest.baseRequest = request.baseRequest - rpcRequest.product = request.Product - rpcRequest.version = request.Version - rpcRequest.actionName = request.ApiName - request.Ontology = rpcRequest - } - -} - -func (request *CommonRequest) BuildUrl() string { - if len(request.Port) > 0 { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.BuildQueries() - } - - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.BuildQueries() -} - -func (request *CommonRequest) BuildQueries() string { - return request.Ontology.BuildQueries() -} - -func (request *CommonRequest) GetUrl() string { - if len(request.Port) > 0 { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.GetQueries() - } - - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.GetQueries() -} - -func (request *CommonRequest) GetQueries() string { - return request.Ontology.GetQueries() -} - -func (request *CommonRequest) GetBodyReader() io.Reader { - return request.Ontology.GetBodyReader() -} - -func (request *CommonRequest) GetStyle() string { - return request.Ontology.GetStyle() -} - -func (request *CommonRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go deleted file mode 100644 index cd1ab178f..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/roa_request.go +++ /dev/null @@ -1,146 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "bytes" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "io" - "net/url" - "sort" - "strings" -) - -type RoaRequest struct { - *baseRequest - pathPattern string - PathParams map[string]string -} - -func (*RoaRequest) GetStyle() string { - return ROA -} - -func (request *RoaRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else if len(request.Content) > 0 { - return bytes.NewReader(request.Content) - } else { - return nil - } -} - -func (request *RoaRequest) GetQueries() string { - return request.queries -} - -// for sign method, need not url encoded -func (request *RoaRequest) BuildQueries() string { - return request.buildQueries(false) -} - -func (request *RoaRequest) buildQueries(needParamEncode bool) string { - // replace path params with value - path := request.pathPattern - for key, value := range request.PathParams { - path = strings.Replace(path, "["+key+"]", value, 1) - } - - queryParams := request.QueryParams - // check if path contains params - splitArray := strings.Split(path, "?") - path = splitArray[0] - if len(splitArray) > 1 && len(splitArray[1]) > 0 { - queryParams[splitArray[1]] = "" - } - // sort QueryParams by key - var queryKeys []string - for key := range queryParams { - queryKeys = append(queryKeys, key) - } - sort.Strings(queryKeys) - - // append urlBuilder - urlBuilder := bytes.Buffer{} - urlBuilder.WriteString(path) - if len(queryKeys) > 0 { - urlBuilder.WriteString("?") - } - for i := 0; i < len(queryKeys); i++ { - queryKey := queryKeys[i] - urlBuilder.WriteString(queryKey) - if value := queryParams[queryKey]; len(value) > 0 { - urlBuilder.WriteString("=") - if needParamEncode { - urlBuilder.WriteString(url.QueryEscape(value)) - } else { - urlBuilder.WriteString(value) - } - } - if i < len(queryKeys)-1 { - urlBuilder.WriteString("&") - } - } - result := urlBuilder.String() - result = popStandardUrlencode(result) - request.queries = result - return request.queries -} - -func popStandardUrlencode(stringToSign string) (result string) { - result = strings.Replace(stringToSign, "+", "%20", -1) - result = strings.Replace(result, "*", "%2A", -1) - result = strings.Replace(result, "%7E", "~", -1) - return -} - -func (request *RoaRequest) GetUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.GetQueries() -} - -func (request *RoaRequest) BuildUrl() string { - // for network trans, need url encoded - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.buildQueries(true) -} - -func (request *RoaRequest) addPathParam(key, value string) { - request.PathParams[key] = value -} - -func (request *RoaRequest) InitWithApiInfo(product, version, action, uriPattern, serviceCode, endpointType string) { - request.baseRequest = defaultBaseRequest() - request.PathParams = make(map[string]string) - request.Headers["x-acs-version"] = version - request.pathPattern = uriPattern - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType - //request.product = product - //request.version = version - //request.actionName = action -} - -func (request *RoaRequest) initWithCommonRequest(commonRequest *CommonRequest) { - request.baseRequest = commonRequest.baseRequest - request.PathParams = commonRequest.PathParams - //request.product = commonRequest.Product - //request.version = commonRequest.Version - request.Headers["x-acs-version"] = commonRequest.Version - //request.actionName = commonRequest.ApiName - request.pathPattern = commonRequest.PathPattern - request.locationServiceCode = "" - request.locationEndpointType = "" -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go deleted file mode 100644 index 7a61c19f4..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/rpc_request.go +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package requests - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils" - "io" - "strings" -) - -type RpcRequest struct { - *baseRequest -} - -func (request *RpcRequest) init() { - request.baseRequest = defaultBaseRequest() - request.Method = POST -} - -func (*RpcRequest) GetStyle() string { - return RPC -} - -func (request *RpcRequest) GetBodyReader() io.Reader { - if request.FormParams != nil && len(request.FormParams) > 0 { - formString := utils.GetUrlFormedMap(request.FormParams) - return strings.NewReader(formString) - } else { - return strings.NewReader("") - } -} - -func (request *RpcRequest) BuildQueries() string { - request.queries = "/?" + utils.GetUrlFormedMap(request.QueryParams) - return request.queries -} - -func (request *RpcRequest) GetQueries() string { - return request.queries -} - -func (request *RpcRequest) BuildUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + ":" + request.Port + request.BuildQueries() -} - -func (request *RpcRequest) GetUrl() string { - return strings.ToLower(request.Scheme) + "://" + request.Domain + request.GetQueries() -} - -func (request *RpcRequest) GetVersion() string { - return request.version -} - -func (request *RpcRequest) GetActionName() string { - return request.actionName -} - -func (request *RpcRequest) addPathParam(key, value string) { - panic("not support") -} - -func (request *RpcRequest) InitWithApiInfo(product, version, action, serviceCode, endpointType string) { - request.init() - request.product = product - request.version = version - request.actionName = action - request.locationServiceCode = serviceCode - request.locationEndpointType = endpointType -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go deleted file mode 100644 index 28af63ea1..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests/types.go +++ /dev/null @@ -1,53 +0,0 @@ -package requests - -import "strconv" - -type Integer string - -func NewInteger(integer int) Integer { - return Integer(strconv.Itoa(integer)) -} - -func (integer Integer) HasValue() bool { - return integer != "" -} - -func (integer Integer) GetValue() (int, error) { - return strconv.Atoi(string(integer)) -} - -func NewInteger64(integer int64) Integer { - return Integer(strconv.FormatInt(integer, 10)) -} - -func (integer Integer) GetValue64() (int64, error) { - return strconv.ParseInt(string(integer), 10, 0) -} - -type Boolean string - -func NewBoolean(bool bool) Boolean { - return Boolean(strconv.FormatBool(bool)) -} - -func (boolean Boolean) HasValue() bool { - return boolean != "" -} - -func (boolean Boolean) GetValue() (bool, error) { - return strconv.ParseBool(string(boolean)) -} - -type Float string - -func NewFloat(f float64) Float { - return Float(strconv.FormatFloat(f, 'f', 6, 64)) -} - -func (float Float) HasValue() bool { - return float != "" -} - -func (float Float) GetValue() (float64, error) { - return strconv.ParseFloat(string(float), 64) -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go deleted file mode 100644 index 43ba6fc26..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/json_parser.go +++ /dev/null @@ -1,341 +0,0 @@ -package responses - -import ( - "encoding/json" - "github.com/json-iterator/go" - "io" - "math" - "strconv" - "strings" - "sync" - "unsafe" -) - -const maxUint = ^uint(0) -const maxInt = int(maxUint >> 1) -const minInt = -maxInt - 1 - -var jsonParser jsoniter.API -var initJson = &sync.Once{} - -func initJsonParserOnce() { - initJson.Do(func() { - registerBetterFuzzyDecoder() - jsonParser = jsoniter.ConfigCompatibleWithStandardLibrary - }) -} - -func registerBetterFuzzyDecoder() { - jsoniter.RegisterTypeDecoder("string", &nullableFuzzyStringDecoder{}) - jsoniter.RegisterTypeDecoder("bool", &fuzzyBoolDecoder{}) - jsoniter.RegisterTypeDecoder("float32", &nullableFuzzyFloat32Decoder{}) - jsoniter.RegisterTypeDecoder("float64", &nullableFuzzyFloat64Decoder{}) - jsoniter.RegisterTypeDecoder("int", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxInt) || val < float64(minInt) { - iter.ReportError("fuzzy decode int", "exceed range") - return - } - *((*int)(ptr)) = int(val) - } else { - *((*int)(ptr)) = iter.ReadInt() - } - }}) - jsoniter.RegisterTypeDecoder("uint", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(maxUint) || val < 0 { - iter.ReportError("fuzzy decode uint", "exceed range") - return - } - *((*uint)(ptr)) = uint(val) - } else { - *((*uint)(ptr)) = iter.ReadUint() - } - }}) - jsoniter.RegisterTypeDecoder("int8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt8) || val < float64(math.MinInt8) { - iter.ReportError("fuzzy decode int8", "exceed range") - return - } - *((*int8)(ptr)) = int8(val) - } else { - *((*int8)(ptr)) = iter.ReadInt8() - } - }}) - jsoniter.RegisterTypeDecoder("uint8", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint8) || val < 0 { - iter.ReportError("fuzzy decode uint8", "exceed range") - return - } - *((*uint8)(ptr)) = uint8(val) - } else { - *((*uint8)(ptr)) = iter.ReadUint8() - } - }}) - jsoniter.RegisterTypeDecoder("int16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt16) || val < float64(math.MinInt16) { - iter.ReportError("fuzzy decode int16", "exceed range") - return - } - *((*int16)(ptr)) = int16(val) - } else { - *((*int16)(ptr)) = iter.ReadInt16() - } - }}) - jsoniter.RegisterTypeDecoder("uint16", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint16) || val < 0 { - iter.ReportError("fuzzy decode uint16", "exceed range") - return - } - *((*uint16)(ptr)) = uint16(val) - } else { - *((*uint16)(ptr)) = iter.ReadUint16() - } - }}) - jsoniter.RegisterTypeDecoder("int32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt32) || val < float64(math.MinInt32) { - iter.ReportError("fuzzy decode int32", "exceed range") - return - } - *((*int32)(ptr)) = int32(val) - } else { - *((*int32)(ptr)) = iter.ReadInt32() - } - }}) - jsoniter.RegisterTypeDecoder("uint32", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint32) || val < 0 { - iter.ReportError("fuzzy decode uint32", "exceed range") - return - } - *((*uint32)(ptr)) = uint32(val) - } else { - *((*uint32)(ptr)) = iter.ReadUint32() - } - }}) - jsoniter.RegisterTypeDecoder("int64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxInt64) || val < float64(math.MinInt64) { - iter.ReportError("fuzzy decode int64", "exceed range") - return - } - *((*int64)(ptr)) = int64(val) - } else { - *((*int64)(ptr)) = iter.ReadInt64() - } - }}) - jsoniter.RegisterTypeDecoder("uint64", &nullableFuzzyIntegerDecoder{func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if isFloat { - val := iter.ReadFloat64() - if val > float64(math.MaxUint64) || val < 0 { - iter.ReportError("fuzzy decode uint64", "exceed range") - return - } - *((*uint64)(ptr)) = uint64(val) - } else { - *((*uint64)(ptr)) = iter.ReadUint64() - } - }}) -} - -type nullableFuzzyStringDecoder struct { -} - -func (decoder *nullableFuzzyStringDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - *((*string)(ptr)) = string(number) - case jsoniter.StringValue: - *((*string)(ptr)) = iter.ReadString() - case jsoniter.BoolValue: - *((*string)(ptr)) = strconv.FormatBool(iter.ReadBool()) - case jsoniter.NilValue: - iter.ReadNil() - *((*string)(ptr)) = "" - default: - iter.ReportError("fuzzyStringDecoder", "not number or string or bool") - } -} - -type fuzzyBoolDecoder struct { -} - -func (decoder *fuzzyBoolDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - switch valueType { - case jsoniter.BoolValue: - *((*bool)(ptr)) = iter.ReadBool() - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - num, err := number.Int64() - if err != nil { - iter.ReportError("fuzzyBoolDecoder", "get value from json.number failed") - } - if num == 0 { - *((*bool)(ptr)) = false - } else { - *((*bool)(ptr)) = true - } - case jsoniter.StringValue: - strValue := strings.ToLower(iter.ReadString()) - if strValue == "true" { - *((*bool)(ptr)) = true - } else if strValue == "false" || strValue == "" { - *((*bool)(ptr)) = false - } else { - iter.ReportError("fuzzyBoolDecoder", "unsupported bool value: "+strValue) - } - case jsoniter.NilValue: - iter.ReadNil() - *((*bool)(ptr)) = false - default: - iter.ReportError("fuzzyBoolDecoder", "not number or string or nil") - } -} - -type tolerateEmptyArrayDecoder struct { - valDecoder jsoniter.ValDecoder -} - -func (decoder *tolerateEmptyArrayDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - if iter.WhatIsNext() == jsoniter.ArrayValue { - iter.Skip() - newIter := iter.Pool().BorrowIterator([]byte("{}")) - defer iter.Pool().ReturnIterator(newIter) - decoder.valDecoder.Decode(ptr, newIter) - } else { - decoder.valDecoder.Decode(ptr, iter) - } -} - -type nullableFuzzyIntegerDecoder struct { - fun func(isFloat bool, ptr unsafe.Pointer, iter *jsoniter.Iterator) -} - -func (decoder *nullableFuzzyIntegerDecoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - var number json.Number - iter.ReadVal(&number) - str = string(number) - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - str = "0" - } - case jsoniter.BoolValue: - if iter.ReadBool() { - str = "1" - } else { - str = "0" - } - case jsoniter.NilValue: - iter.ReadNil() - str = "0" - default: - iter.ReportError("fuzzyIntegerDecoder", "not number or string") - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - isFloat := strings.IndexByte(str, '.') != -1 - decoder.fun(isFloat, ptr, newIter) - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } -} - -type nullableFuzzyFloat32Decoder struct { -} - -func (decoder *nullableFuzzyFloat32Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float32)(ptr)) = iter.ReadFloat32() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float32)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float32)(ptr)) = newIter.ReadFloat32() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float32 - if iter.ReadBool() { - *((*float32)(ptr)) = 1 - } else { - *((*float32)(ptr)) = 0 - } - case jsoniter.NilValue: - iter.ReadNil() - *((*float32)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string") - } -} - -type nullableFuzzyFloat64Decoder struct { -} - -func (decoder *nullableFuzzyFloat64Decoder) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) { - valueType := iter.WhatIsNext() - var str string - switch valueType { - case jsoniter.NumberValue: - *((*float64)(ptr)) = iter.ReadFloat64() - case jsoniter.StringValue: - str = iter.ReadString() - // support empty string - if str == "" { - *((*float64)(ptr)) = 0 - return - } - newIter := iter.Pool().BorrowIterator([]byte(str)) - defer iter.Pool().ReturnIterator(newIter) - *((*float64)(ptr)) = newIter.ReadFloat64() - if newIter.Error != nil && newIter.Error != io.EOF { - iter.Error = newIter.Error - } - case jsoniter.BoolValue: - // support bool to float64 - if iter.ReadBool() { - *((*float64)(ptr)) = 1 - } else { - *((*float64)(ptr)) = 0 - } - case jsoniter.NilValue: - // support empty string - iter.ReadNil() - *((*float64)(ptr)) = 0 - default: - iter.ReportError("nullableFuzzyFloat32Decoder", "not number or string") - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go deleted file mode 100644 index 8780f26f2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses/response.go +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package responses - -import ( - "bytes" - "encoding/xml" - "fmt" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/errors" - "io/ioutil" - "net/http" - "strings" -) - -type AcsResponse interface { - IsSuccess() bool - GetHttpStatus() int - GetHttpHeaders() map[string][]string - GetHttpContentString() string - GetHttpContentBytes() []byte - GetOriginHttpResponse() *http.Response - parseFromHttpResponse(httpResponse *http.Response) error -} - -func Unmarshal(response AcsResponse, httpResponse *http.Response, format string) (err error) { - err = response.parseFromHttpResponse(httpResponse) - if err != nil { - return - } - if !response.IsSuccess() { - err = errors.NewServerError(response.GetHttpStatus(), response.GetHttpContentString(), "") - return - } - if _, isCommonResponse := response.(CommonResponse); isCommonResponse { - // common response need not unmarshal - return - } - - if len(response.GetHttpContentBytes()) == 0 { - return - } - - if strings.ToUpper(format) == "JSON" { - initJsonParserOnce() - err = jsonParser.Unmarshal(response.GetHttpContentBytes(), response) - if err != nil { - err = errors.NewClientError(errors.JsonUnmarshalErrorCode, errors.JsonUnmarshalErrorMessage, err) - } - } else if strings.ToUpper(format) == "XML" { - err = xml.Unmarshal(response.GetHttpContentBytes(), response) - } - return -} - -type BaseResponse struct { - httpStatus int - httpHeaders map[string][]string - httpContentString string - httpContentBytes []byte - originHttpResponse *http.Response -} - -func (baseResponse *BaseResponse) GetHttpStatus() int { - return baseResponse.httpStatus -} - -func (baseResponse *BaseResponse) GetHttpHeaders() map[string][]string { - return baseResponse.httpHeaders -} - -func (baseResponse *BaseResponse) GetHttpContentString() string { - return baseResponse.httpContentString -} - -func (baseResponse *BaseResponse) GetHttpContentBytes() []byte { - return baseResponse.httpContentBytes -} - -func (baseResponse *BaseResponse) GetOriginHttpResponse() *http.Response { - return baseResponse.originHttpResponse -} - -func (baseResponse *BaseResponse) IsSuccess() bool { - if baseResponse.GetHttpStatus() >= 200 && baseResponse.GetHttpStatus() < 300 { - return true - } - - return false -} - -func (baseResponse *BaseResponse) parseFromHttpResponse(httpResponse *http.Response) (err error) { - defer httpResponse.Body.Close() - body, err := ioutil.ReadAll(httpResponse.Body) - if err != nil { - return - } - baseResponse.httpStatus = httpResponse.StatusCode - baseResponse.httpHeaders = httpResponse.Header - baseResponse.httpContentBytes = body - baseResponse.httpContentString = string(body) - baseResponse.originHttpResponse = httpResponse - return -} - -func (baseResponse *BaseResponse) String() string { - resultBuilder := bytes.Buffer{} - // statusCode - resultBuilder.WriteString("\n") - resultBuilder.WriteString(fmt.Sprintf("%s %s\n", baseResponse.originHttpResponse.Proto, baseResponse.originHttpResponse.Status)) - // httpHeaders - //resultBuilder.WriteString("Headers:\n") - for key, value := range baseResponse.httpHeaders { - resultBuilder.WriteString(key + ": " + strings.Join(value, ";") + "\n") - } - resultBuilder.WriteString("\n") - // content - //resultBuilder.WriteString("Content:\n") - resultBuilder.WriteString(baseResponse.httpContentString + "\n") - return resultBuilder.String() -} - -type CommonResponse struct { - *BaseResponse -} - -func NewCommonResponse() (response *CommonResponse) { - return &CommonResponse{ - BaseResponse: &BaseResponse{}, - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go deleted file mode 100644 index a00c775c2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/sdk/utils/utils.go +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package utils - -import ( - "crypto/md5" - "encoding/base64" - "encoding/hex" - "encoding/json" - "fmt" - "github.com/satori/go.uuid" - "net/url" - "reflect" - "strconv" - "time" -) - -// if you use go 1.10 or higher, you can hack this util by these to avoid "TimeZone.zip not found" on Windows -var LoadLocationFromTZData func(name string, data []byte) (*time.Location, error) = nil -var TZData []byte = nil - -func GetUUIDV4() (uuidHex string) { - uuidV4 := uuid.NewV4() - uuidHex = hex.EncodeToString(uuidV4.Bytes()) - return -} - -func GetMD5Base64(bytes []byte) (base64Value string) { - md5Ctx := md5.New() - md5Ctx.Write(bytes) - md5Value := md5Ctx.Sum(nil) - base64Value = base64.StdEncoding.EncodeToString(md5Value) - return -} - -func GetGMTLocation() (*time.Location, error) { - if LoadLocationFromTZData != nil && TZData != nil { - return LoadLocationFromTZData("GMT", TZData) - } else { - return time.LoadLocation("GMT") - } -} - -func GetTimeInFormatISO8601() (timeStr string) { - gmt, err := GetGMTLocation() - - if err != nil { - panic(err) - } - return time.Now().In(gmt).Format("2006-01-02T15:04:05Z") -} - -func GetTimeInFormatRFC2616() (timeStr string) { - gmt, err := GetGMTLocation() - - if err != nil { - panic(err) - } - return time.Now().In(gmt).Format("Mon, 02 Jan 2006 15:04:05 GMT") -} - -func GetUrlFormedMap(source map[string]string) (urlEncoded string) { - urlEncoder := url.Values{} - for key, value := range source { - urlEncoder.Add(key, value) - } - urlEncoded = urlEncoder.Encode() - return -} - -func GetFromJsonString(jsonString, key string) (result string, err error) { - var responseMap map[string]*json.RawMessage - err = json.Unmarshal([]byte(jsonString), &responseMap) - if err != nil { - return - } - fmt.Println(string(*responseMap[key])) - err = json.Unmarshal(*responseMap[key], &result) - return -} - -func InitStructWithDefaultTag(bean interface{}) { - configType := reflect.TypeOf(bean) - for i := 0; i < configType.Elem().NumField(); i++ { - field := configType.Elem().Field(i) - defaultValue := field.Tag.Get("default") - if defaultValue == "" { - continue - } - setter := reflect.ValueOf(bean).Elem().Field(i) - switch field.Type.String() { - case "int": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "time.Duration": - intValue, _ := strconv.ParseInt(defaultValue, 10, 64) - setter.SetInt(intValue) - case "string": - setter.SetString(defaultValue) - case "bool": - boolValue, _ := strconv.ParseBool(defaultValue) - setter.SetBool(boolValue) - } - } -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go deleted file mode 100644 index 30e1dea47..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddBatchDomainRecords invokes the alidns.AddBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -func (client *Client) AddBatchDomainRecords(request *AddBatchDomainRecordsRequest) (response *AddBatchDomainRecordsResponse, err error) { - response = CreateAddBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// AddBatchDomainRecordsWithChan invokes the alidns.AddBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddBatchDomainRecordsWithChan(request *AddBatchDomainRecordsRequest) (<-chan *AddBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *AddBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddBatchDomainRecordsWithCallback invokes the alidns.AddBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/addbatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddBatchDomainRecordsWithCallback(request *AddBatchDomainRecordsRequest, callback func(response *AddBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.AddBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddBatchDomainRecordsRequest is the request struct for api AddBatchDomainRecords -type AddBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// AddBatchDomainRecordsResponse is the response struct for api AddBatchDomainRecords -type AddBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateAddBatchDomainRecordsRequest creates a request to invoke AddBatchDomainRecords API -func CreateAddBatchDomainRecordsRequest() (request *AddBatchDomainRecordsRequest) { - request = &AddBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddBatchDomainRecords", "", "") - return -} - -// CreateAddBatchDomainRecordsResponse creates a response to parse from AddBatchDomainRecords response -func CreateAddBatchDomainRecordsResponse() (response *AddBatchDomainRecordsResponse) { - response = &AddBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go deleted file mode 100644 index 1b2249e29..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomain invokes the alidns.AddDomain API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -func (client *Client) AddDomain(request *AddDomainRequest) (response *AddDomainResponse, err error) { - response = CreateAddDomainResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainWithChan invokes the alidns.AddDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainWithChan(request *AddDomainRequest) (<-chan *AddDomainResponse, <-chan error) { - responseChan := make(chan *AddDomainResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomain(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainWithCallback invokes the alidns.AddDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainWithCallback(request *AddDomainRequest, callback func(response *AddDomainResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainResponse - var err error - defer close(result) - response, err = client.AddDomain(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainRequest is the request struct for api AddDomain -type AddDomainRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// AddDomainResponse is the response struct for api AddDomain -type AddDomainResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - DnsServers DnsServersInAddDomain `json:"DnsServers" xml:"DnsServers"` -} - -// CreateAddDomainRequest creates a request to invoke AddDomain API -func CreateAddDomainRequest() (request *AddDomainRequest) { - request = &AddDomainRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomain", "", "") - return -} - -// CreateAddDomainResponse creates a response to parse from AddDomain response -func CreateAddDomainResponse() (response *AddDomainResponse) { - response = &AddDomainResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go deleted file mode 100644 index a1c7cd4c0..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_group.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomainGroup invokes the alidns.AddDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -func (client *Client) AddDomainGroup(request *AddDomainGroupRequest) (response *AddDomainGroupResponse, err error) { - response = CreateAddDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainGroupWithChan invokes the alidns.AddDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainGroupWithChan(request *AddDomainGroupRequest) (<-chan *AddDomainGroupResponse, <-chan error) { - responseChan := make(chan *AddDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainGroupWithCallback invokes the alidns.AddDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainGroupWithCallback(request *AddDomainGroupRequest, callback func(response *AddDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainGroupResponse - var err error - defer close(result) - response, err = client.AddDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainGroupRequest is the request struct for api AddDomainGroup -type AddDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupName string `position:"Query" name:"GroupName"` -} - -// AddDomainGroupResponse is the response struct for api AddDomainGroup -type AddDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateAddDomainGroupRequest creates a request to invoke AddDomainGroup API -func CreateAddDomainGroupRequest() (request *AddDomainGroupRequest) { - request = &AddDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomainGroup", "", "") - return -} - -// CreateAddDomainGroupResponse creates a response to parse from AddDomainGroup response -func CreateAddDomainGroupResponse() (response *AddDomainGroupResponse) { - response = &AddDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go deleted file mode 100644 index 1da602453..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/add_domain_record.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// AddDomainRecord invokes the alidns.AddDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -func (client *Client) AddDomainRecord(request *AddDomainRecordRequest) (response *AddDomainRecordResponse, err error) { - response = CreateAddDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// AddDomainRecordWithChan invokes the alidns.AddDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainRecordWithChan(request *AddDomainRecordRequest) (<-chan *AddDomainRecordResponse, <-chan error) { - responseChan := make(chan *AddDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.AddDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// AddDomainRecordWithCallback invokes the alidns.AddDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/adddomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) AddDomainRecordWithCallback(request *AddDomainRecordRequest, callback func(response *AddDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *AddDomainRecordResponse - var err error - defer close(result) - response, err = client.AddDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// AddDomainRecordRequest is the request struct for api AddDomainRecord -type AddDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` - TTL requests.Integer `position:"Query" name:"TTL"` - Priority requests.Integer `position:"Query" name:"Priority"` - Line string `position:"Query" name:"Line"` -} - -// AddDomainRecordResponse is the response struct for api AddDomainRecord -type AddDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateAddDomainRecordRequest creates a request to invoke AddDomainRecord API -func CreateAddDomainRecordRequest() (request *AddDomainRecordRequest) { - request = &AddDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "AddDomainRecord", "", "") - return -} - -// CreateAddDomainRecordResponse creates a response to parse from AddDomainRecord response -func CreateAddDomainRecordResponse() (response *AddDomainRecordResponse) { - response = &AddDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go deleted file mode 100644 index 86b68e7b9..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/apply_for_retrieval_domain_name.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ApplyForRetrievalDomainName invokes the alidns.ApplyForRetrievalDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -func (client *Client) ApplyForRetrievalDomainName(request *ApplyForRetrievalDomainNameRequest) (response *ApplyForRetrievalDomainNameResponse, err error) { - response = CreateApplyForRetrievalDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// ApplyForRetrievalDomainNameWithChan invokes the alidns.ApplyForRetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ApplyForRetrievalDomainNameWithChan(request *ApplyForRetrievalDomainNameRequest) (<-chan *ApplyForRetrievalDomainNameResponse, <-chan error) { - responseChan := make(chan *ApplyForRetrievalDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ApplyForRetrievalDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ApplyForRetrievalDomainNameWithCallback invokes the alidns.ApplyForRetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/applyforretrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ApplyForRetrievalDomainNameWithCallback(request *ApplyForRetrievalDomainNameRequest, callback func(response *ApplyForRetrievalDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ApplyForRetrievalDomainNameResponse - var err error - defer close(result) - response, err = client.ApplyForRetrievalDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ApplyForRetrievalDomainNameRequest is the request struct for api ApplyForRetrievalDomainName -type ApplyForRetrievalDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// ApplyForRetrievalDomainNameResponse is the response struct for api ApplyForRetrievalDomainName -type ApplyForRetrievalDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` -} - -// CreateApplyForRetrievalDomainNameRequest creates a request to invoke ApplyForRetrievalDomainName API -func CreateApplyForRetrievalDomainNameRequest() (request *ApplyForRetrievalDomainNameRequest) { - request = &ApplyForRetrievalDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ApplyForRetrievalDomainName", "", "") - return -} - -// CreateApplyForRetrievalDomainNameResponse creates a response to parse from ApplyForRetrievalDomainName response -func CreateApplyForRetrievalDomainNameResponse() (response *ApplyForRetrievalDomainNameResponse) { - response = &ApplyForRetrievalDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go deleted file mode 100644 index 61fed5be8..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_group.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ChangeDomainGroup invokes the alidns.ChangeDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -func (client *Client) ChangeDomainGroup(request *ChangeDomainGroupRequest) (response *ChangeDomainGroupResponse, err error) { - response = CreateChangeDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// ChangeDomainGroupWithChan invokes the alidns.ChangeDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainGroupWithChan(request *ChangeDomainGroupRequest) (<-chan *ChangeDomainGroupResponse, <-chan error) { - responseChan := make(chan *ChangeDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ChangeDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ChangeDomainGroupWithCallback invokes the alidns.ChangeDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainGroupWithCallback(request *ChangeDomainGroupRequest, callback func(response *ChangeDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ChangeDomainGroupResponse - var err error - defer close(result) - response, err = client.ChangeDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ChangeDomainGroupRequest is the request struct for api ChangeDomainGroup -type ChangeDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// ChangeDomainGroupResponse is the response struct for api ChangeDomainGroup -type ChangeDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateChangeDomainGroupRequest creates a request to invoke ChangeDomainGroup API -func CreateChangeDomainGroupRequest() (request *ChangeDomainGroupRequest) { - request = &ChangeDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ChangeDomainGroup", "", "") - return -} - -// CreateChangeDomainGroupResponse creates a response to parse from ChangeDomainGroup response -func CreateChangeDomainGroupResponse() (response *ChangeDomainGroupResponse) { - response = &ChangeDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go deleted file mode 100644 index 04f329e49..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/change_domain_of_dns_product.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ChangeDomainOfDnsProduct invokes the alidns.ChangeDomainOfDnsProduct API synchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -func (client *Client) ChangeDomainOfDnsProduct(request *ChangeDomainOfDnsProductRequest) (response *ChangeDomainOfDnsProductResponse, err error) { - response = CreateChangeDomainOfDnsProductResponse() - err = client.DoAction(request, response) - return -} - -// ChangeDomainOfDnsProductWithChan invokes the alidns.ChangeDomainOfDnsProduct API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainOfDnsProductWithChan(request *ChangeDomainOfDnsProductRequest) (<-chan *ChangeDomainOfDnsProductResponse, <-chan error) { - responseChan := make(chan *ChangeDomainOfDnsProductResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ChangeDomainOfDnsProduct(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ChangeDomainOfDnsProductWithCallback invokes the alidns.ChangeDomainOfDnsProduct API asynchronously -// api document: https://help.aliyun.com/api/alidns/changedomainofdnsproduct.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ChangeDomainOfDnsProductWithCallback(request *ChangeDomainOfDnsProductRequest, callback func(response *ChangeDomainOfDnsProductResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ChangeDomainOfDnsProductResponse - var err error - defer close(result) - response, err = client.ChangeDomainOfDnsProduct(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ChangeDomainOfDnsProductRequest is the request struct for api ChangeDomainOfDnsProduct -type ChangeDomainOfDnsProductRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InstanceId string `position:"Query" name:"InstanceId"` - NewDomain string `position:"Query" name:"NewDomain"` - Force requests.Boolean `position:"Query" name:"Force"` -} - -// ChangeDomainOfDnsProductResponse is the response struct for api ChangeDomainOfDnsProduct -type ChangeDomainOfDnsProductResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - OriginalDomain string `json:"OriginalDomain" xml:"OriginalDomain"` -} - -// CreateChangeDomainOfDnsProductRequest creates a request to invoke ChangeDomainOfDnsProduct API -func CreateChangeDomainOfDnsProductRequest() (request *ChangeDomainOfDnsProductRequest) { - request = &ChangeDomainOfDnsProductRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ChangeDomainOfDnsProduct", "", "") - return -} - -// CreateChangeDomainOfDnsProductResponse creates a response to parse from ChangeDomainOfDnsProduct response -func CreateChangeDomainOfDnsProductResponse() (response *ChangeDomainOfDnsProductResponse) { - response = &ChangeDomainOfDnsProductResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go deleted file mode 100644 index 876e4deb7..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/check_domain_record.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// CheckDomainRecord invokes the alidns.CheckDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -func (client *Client) CheckDomainRecord(request *CheckDomainRecordRequest) (response *CheckDomainRecordResponse, err error) { - response = CreateCheckDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// CheckDomainRecordWithChan invokes the alidns.CheckDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) CheckDomainRecordWithChan(request *CheckDomainRecordRequest) (<-chan *CheckDomainRecordResponse, <-chan error) { - responseChan := make(chan *CheckDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.CheckDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// CheckDomainRecordWithCallback invokes the alidns.CheckDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/checkdomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) CheckDomainRecordWithCallback(request *CheckDomainRecordRequest, callback func(response *CheckDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *CheckDomainRecordResponse - var err error - defer close(result) - response, err = client.CheckDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// CheckDomainRecordRequest is the request struct for api CheckDomainRecord -type CheckDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` -} - -// CheckDomainRecordResponse is the response struct for api CheckDomainRecord -type CheckDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - IsExist bool `json:"IsExist" xml:"IsExist"` -} - -// CreateCheckDomainRecordRequest creates a request to invoke CheckDomainRecord API -func CreateCheckDomainRecordRequest() (request *CheckDomainRecordRequest) { - request = &CheckDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "CheckDomainRecord", "", "") - return -} - -// CreateCheckDomainRecordResponse creates a response to parse from CheckDomainRecord response -func CreateCheckDomainRecordResponse() (response *CheckDomainRecordResponse) { - response = &CheckDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go deleted file mode 100644 index bd92fdd31..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/client.go +++ /dev/null @@ -1,81 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth" -) - -// Client is the sdk client struct, each func corresponds to an OpenAPI -type Client struct { - sdk.Client -} - -// NewClient creates a sdk client with environment variables -func NewClient() (client *Client, err error) { - client = &Client{} - err = client.Init() - return -} - -// NewClientWithOptions creates a sdk client with regionId/sdkConfig/credential -// this is the common api to create a sdk client -func NewClientWithOptions(regionId string, config *sdk.Config, credential auth.Credential) (client *Client, err error) { - client = &Client{} - err = client.InitWithOptions(regionId, config, credential) - return -} - -// NewClientWithAccessKey is a shortcut to create sdk client with accesskey -// usage: https://help.aliyun.com/document_detail/66217.html -func NewClientWithAccessKey(regionId, accessKeyId, accessKeySecret string) (client *Client, err error) { - client = &Client{} - err = client.InitWithAccessKey(regionId, accessKeyId, accessKeySecret) - return -} - -// NewClientWithStsToken is a shortcut to create sdk client with sts token -// usage: https://help.aliyun.com/document_detail/66222.html -func NewClientWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken string) (client *Client, err error) { - client = &Client{} - err = client.InitWithStsToken(regionId, stsAccessKeyId, stsAccessKeySecret, stsToken) - return -} - -// NewClientWithRamRoleArn is a shortcut to create sdk client with ram roleArn -// usage: https://help.aliyun.com/document_detail/66222.html -func NewClientWithRamRoleArn(regionId string, accessKeyId, accessKeySecret, roleArn, roleSessionName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithRamRoleArn(regionId, accessKeyId, accessKeySecret, roleArn, roleSessionName) - return -} - -// NewClientWithEcsRamRole is a shortcut to create sdk client with ecs ram role -// usage: https://help.aliyun.com/document_detail/66223.html -func NewClientWithEcsRamRole(regionId string, roleName string) (client *Client, err error) { - client = &Client{} - err = client.InitWithEcsRamRole(regionId, roleName) - return -} - -// NewClientWithRsaKeyPair is a shortcut to create sdk client with rsa key pair -// attention: rsa key pair auth is only Japan regions available -func NewClientWithRsaKeyPair(regionId string, publicKeyId, privateKey string, sessionExpiration int) (client *Client, err error) { - client = &Client{} - err = client.InitWithRsaKeyPair(regionId, publicKeyId, privateKey, sessionExpiration) - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go deleted file mode 100644 index 8c973f766..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteBatchDomainRecords invokes the alidns.DeleteBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -func (client *Client) DeleteBatchDomainRecords(request *DeleteBatchDomainRecordsRequest) (response *DeleteBatchDomainRecordsResponse, err error) { - response = CreateDeleteBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteBatchDomainRecordsWithChan invokes the alidns.DeleteBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainRecordsWithChan(request *DeleteBatchDomainRecordsRequest) (<-chan *DeleteBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DeleteBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteBatchDomainRecordsWithCallback invokes the alidns.DeleteBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainRecordsWithCallback(request *DeleteBatchDomainRecordsRequest, callback func(response *DeleteBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.DeleteBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteBatchDomainRecordsRequest is the request struct for api DeleteBatchDomainRecords -type DeleteBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// DeleteBatchDomainRecordsResponse is the response struct for api DeleteBatchDomainRecords -type DeleteBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateDeleteBatchDomainRecordsRequest creates a request to invoke DeleteBatchDomainRecords API -func CreateDeleteBatchDomainRecordsRequest() (request *DeleteBatchDomainRecordsRequest) { - request = &DeleteBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteBatchDomainRecords", "", "") - return -} - -// CreateDeleteBatchDomainRecordsResponse creates a response to parse from DeleteBatchDomainRecords response -func CreateDeleteBatchDomainRecordsResponse() (response *DeleteBatchDomainRecordsResponse) { - response = &DeleteBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go deleted file mode 100644 index fbbac4cec..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_batch_domains.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteBatchDomains invokes the alidns.DeleteBatchDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -func (client *Client) DeleteBatchDomains(request *DeleteBatchDomainsRequest) (response *DeleteBatchDomainsResponse, err error) { - response = CreateDeleteBatchDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteBatchDomainsWithChan invokes the alidns.DeleteBatchDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainsWithChan(request *DeleteBatchDomainsRequest) (<-chan *DeleteBatchDomainsResponse, <-chan error) { - responseChan := make(chan *DeleteBatchDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteBatchDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteBatchDomainsWithCallback invokes the alidns.DeleteBatchDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletebatchdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteBatchDomainsWithCallback(request *DeleteBatchDomainsRequest, callback func(response *DeleteBatchDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteBatchDomainsResponse - var err error - defer close(result) - response, err = client.DeleteBatchDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteBatchDomainsRequest is the request struct for api DeleteBatchDomains -type DeleteBatchDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Domains string `position:"Query" name:"Domains"` -} - -// DeleteBatchDomainsResponse is the response struct for api DeleteBatchDomains -type DeleteBatchDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateDeleteBatchDomainsRequest creates a request to invoke DeleteBatchDomains API -func CreateDeleteBatchDomainsRequest() (request *DeleteBatchDomainsRequest) { - request = &DeleteBatchDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteBatchDomains", "", "") - return -} - -// CreateDeleteBatchDomainsResponse creates a response to parse from DeleteBatchDomains response -func CreateDeleteBatchDomainsResponse() (response *DeleteBatchDomainsResponse) { - response = &DeleteBatchDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go deleted file mode 100644 index 097f37f9a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomain invokes the alidns.DeleteDomain API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -func (client *Client) DeleteDomain(request *DeleteDomainRequest) (response *DeleteDomainResponse, err error) { - response = CreateDeleteDomainResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainWithChan invokes the alidns.DeleteDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainWithChan(request *DeleteDomainRequest) (<-chan *DeleteDomainResponse, <-chan error) { - responseChan := make(chan *DeleteDomainResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomain(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainWithCallback invokes the alidns.DeleteDomain API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomain.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainWithCallback(request *DeleteDomainRequest, callback func(response *DeleteDomainResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainResponse - var err error - defer close(result) - response, err = client.DeleteDomain(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainRequest is the request struct for api DeleteDomain -type DeleteDomainRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// DeleteDomainResponse is the response struct for api DeleteDomain -type DeleteDomainResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` -} - -// CreateDeleteDomainRequest creates a request to invoke DeleteDomain API -func CreateDeleteDomainRequest() (request *DeleteDomainRequest) { - request = &DeleteDomainRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomain", "", "") - return -} - -// CreateDeleteDomainResponse creates a response to parse from DeleteDomain response -func CreateDeleteDomainResponse() (response *DeleteDomainResponse) { - response = &DeleteDomainResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go deleted file mode 100644 index 341b91227..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_group.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomainGroup invokes the alidns.DeleteDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -func (client *Client) DeleteDomainGroup(request *DeleteDomainGroupRequest) (response *DeleteDomainGroupResponse, err error) { - response = CreateDeleteDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainGroupWithChan invokes the alidns.DeleteDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainGroupWithChan(request *DeleteDomainGroupRequest) (<-chan *DeleteDomainGroupResponse, <-chan error) { - responseChan := make(chan *DeleteDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainGroupWithCallback invokes the alidns.DeleteDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainGroupWithCallback(request *DeleteDomainGroupRequest, callback func(response *DeleteDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainGroupResponse - var err error - defer close(result) - response, err = client.DeleteDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainGroupRequest is the request struct for api DeleteDomainGroup -type DeleteDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupId string `position:"Query" name:"GroupId"` -} - -// DeleteDomainGroupResponse is the response struct for api DeleteDomainGroup -type DeleteDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateDeleteDomainGroupRequest creates a request to invoke DeleteDomainGroup API -func CreateDeleteDomainGroupRequest() (request *DeleteDomainGroupRequest) { - request = &DeleteDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomainGroup", "", "") - return -} - -// CreateDeleteDomainGroupResponse creates a response to parse from DeleteDomainGroup response -func CreateDeleteDomainGroupResponse() (response *DeleteDomainGroupResponse) { - response = &DeleteDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go deleted file mode 100644 index 73f2b08fc..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_domain_record.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteDomainRecord invokes the alidns.DeleteDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -func (client *Client) DeleteDomainRecord(request *DeleteDomainRecordRequest) (response *DeleteDomainRecordResponse, err error) { - response = CreateDeleteDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// DeleteDomainRecordWithChan invokes the alidns.DeleteDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainRecordWithChan(request *DeleteDomainRecordRequest) (<-chan *DeleteDomainRecordResponse, <-chan error) { - responseChan := make(chan *DeleteDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteDomainRecordWithCallback invokes the alidns.DeleteDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteDomainRecordWithCallback(request *DeleteDomainRecordRequest, callback func(response *DeleteDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteDomainRecordResponse - var err error - defer close(result) - response, err = client.DeleteDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteDomainRecordRequest is the request struct for api DeleteDomainRecord -type DeleteDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` -} - -// DeleteDomainRecordResponse is the response struct for api DeleteDomainRecord -type DeleteDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateDeleteDomainRecordRequest creates a request to invoke DeleteDomainRecord API -func CreateDeleteDomainRecordRequest() (request *DeleteDomainRecordRequest) { - request = &DeleteDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteDomainRecord", "", "") - return -} - -// CreateDeleteDomainRecordResponse creates a response to parse from DeleteDomainRecord response -func CreateDeleteDomainRecordResponse() (response *DeleteDomainRecordResponse) { - response = &DeleteDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go deleted file mode 100644 index 06bb0fd72..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/delete_sub_domain_records.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DeleteSubDomainRecords invokes the alidns.DeleteSubDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -func (client *Client) DeleteSubDomainRecords(request *DeleteSubDomainRecordsRequest) (response *DeleteSubDomainRecordsResponse, err error) { - response = CreateDeleteSubDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DeleteSubDomainRecordsWithChan invokes the alidns.DeleteSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteSubDomainRecordsWithChan(request *DeleteSubDomainRecordsRequest) (<-chan *DeleteSubDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DeleteSubDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DeleteSubDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DeleteSubDomainRecordsWithCallback invokes the alidns.DeleteSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/deletesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DeleteSubDomainRecordsWithCallback(request *DeleteSubDomainRecordsRequest, callback func(response *DeleteSubDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DeleteSubDomainRecordsResponse - var err error - defer close(result) - response, err = client.DeleteSubDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DeleteSubDomainRecordsRequest is the request struct for api DeleteSubDomainRecords -type DeleteSubDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` -} - -// DeleteSubDomainRecordsResponse is the response struct for api DeleteSubDomainRecords -type DeleteSubDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RR string `json:"RR" xml:"RR"` - TotalCount string `json:"TotalCount" xml:"TotalCount"` -} - -// CreateDeleteSubDomainRecordsRequest creates a request to invoke DeleteSubDomainRecords API -func CreateDeleteSubDomainRecordsRequest() (request *DeleteSubDomainRecordsRequest) { - request = &DeleteSubDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DeleteSubDomainRecords", "", "") - return -} - -// CreateDeleteSubDomainRecordsResponse creates a response to parse from DeleteSubDomainRecords response -func CreateDeleteSubDomainRecordsResponse() (response *DeleteSubDomainRecordsResponse) { - response = &DeleteSubDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go deleted file mode 100644 index 67590cb8b..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_batch_result.go +++ /dev/null @@ -1,110 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeBatchResult invokes the alidns.DescribeBatchResult API synchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -func (client *Client) DescribeBatchResult(request *DescribeBatchResultRequest) (response *DescribeBatchResultResponse, err error) { - response = CreateDescribeBatchResultResponse() - err = client.DoAction(request, response) - return -} - -// DescribeBatchResultWithChan invokes the alidns.DescribeBatchResult API asynchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeBatchResultWithChan(request *DescribeBatchResultRequest) (<-chan *DescribeBatchResultResponse, <-chan error) { - responseChan := make(chan *DescribeBatchResultResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeBatchResult(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeBatchResultWithCallback invokes the alidns.DescribeBatchResult API asynchronously -// api document: https://help.aliyun.com/api/alidns/describebatchresult.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeBatchResultWithCallback(request *DescribeBatchResultRequest, callback func(response *DescribeBatchResultResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeBatchResultResponse - var err error - defer close(result) - response, err = client.DescribeBatchResult(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeBatchResultRequest is the request struct for api DescribeBatchResult -type DescribeBatchResultRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - TraceId string `position:"Query" name:"TraceId"` -} - -// DescribeBatchResultResponse is the response struct for api DescribeBatchResult -type DescribeBatchResultResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` - Status int `json:"Status" xml:"Status"` - BatchCount int `json:"BatchCount" xml:"BatchCount"` - SuccessNumber int `json:"SuccessNumber" xml:"SuccessNumber"` - FailResults FailResults `json:"FailResults" xml:"FailResults"` -} - -// CreateDescribeBatchResultRequest creates a request to invoke DescribeBatchResult API -func CreateDescribeBatchResultRequest() (request *DescribeBatchResultRequest) { - request = &DescribeBatchResultRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeBatchResult", "", "") - return -} - -// CreateDescribeBatchResultResponse creates a response to parse from DescribeBatchResult response -func CreateDescribeBatchResultResponse() (response *DescribeBatchResultResponse) { - response = &DescribeBatchResultResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go deleted file mode 100644 index b92bf7830..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instance.go +++ /dev/null @@ -1,134 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDnsProductInstance invokes the alidns.DescribeDnsProductInstance API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -func (client *Client) DescribeDnsProductInstance(request *DescribeDnsProductInstanceRequest) (response *DescribeDnsProductInstanceResponse, err error) { - response = CreateDescribeDnsProductInstanceResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDnsProductInstanceWithChan invokes the alidns.DescribeDnsProductInstance API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstanceWithChan(request *DescribeDnsProductInstanceRequest) (<-chan *DescribeDnsProductInstanceResponse, <-chan error) { - responseChan := make(chan *DescribeDnsProductInstanceResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDnsProductInstance(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDnsProductInstanceWithCallback invokes the alidns.DescribeDnsProductInstance API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstance.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstanceWithCallback(request *DescribeDnsProductInstanceRequest, callback func(response *DescribeDnsProductInstanceResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDnsProductInstanceResponse - var err error - defer close(result) - response, err = client.DescribeDnsProductInstance(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDnsProductInstanceRequest is the request struct for api DescribeDnsProductInstance -type DescribeDnsProductInstanceRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InstanceId string `position:"Query" name:"InstanceId"` -} - -// DescribeDnsProductInstanceResponse is the response struct for api DescribeDnsProductInstance -type DescribeDnsProductInstanceResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - StartTime string `json:"StartTime" xml:"StartTime"` - StartTimestamp int `json:"StartTimestamp" xml:"StartTimestamp"` - EndTime string `json:"EndTime" xml:"EndTime"` - EndTimestamp int `json:"EndTimestamp" xml:"EndTimestamp"` - Domain string `json:"Domain" xml:"Domain"` - BindCount int `json:"BindCount" xml:"BindCount"` - BindUsedCount int `json:"BindUsedCount" xml:"BindUsedCount"` - TTLMinValue int `json:"TTLMinValue" xml:"TTLMinValue"` - SubDomainLevel int `json:"SubDomainLevel" xml:"SubDomainLevel"` - DnsSLBCount int `json:"DnsSLBCount" xml:"DnsSLBCount"` - URLForwardCount int `json:"URLForwardCount" xml:"URLForwardCount"` - DDosDefendFlow int `json:"DDosDefendFlow" xml:"DDosDefendFlow"` - DDosDefendQuery int `json:"DDosDefendQuery" xml:"DDosDefendQuery"` - OverseaDDosDefendFlow int `json:"OverseaDDosDefendFlow" xml:"OverseaDDosDefendFlow"` - SearchEngineLines string `json:"SearchEngineLines" xml:"SearchEngineLines"` - ISPLines string `json:"ISPLines" xml:"ISPLines"` - ISPRegionLines string `json:"ISPRegionLines" xml:"ISPRegionLines"` - OverseaLine string `json:"OverseaLine" xml:"OverseaLine"` - MonitorNodeCount int `json:"MonitorNodeCount" xml:"MonitorNodeCount"` - MonitorFrequency int `json:"MonitorFrequency" xml:"MonitorFrequency"` - MonitorTaskCount int `json:"MonitorTaskCount" xml:"MonitorTaskCount"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - Gslb bool `json:"Gslb" xml:"Gslb"` - InClean bool `json:"InClean" xml:"InClean"` - InBlackHole bool `json:"InBlackHole" xml:"InBlackHole"` - DnsServers DnsServersInDescribeDnsProductInstance `json:"DnsServers" xml:"DnsServers"` -} - -// CreateDescribeDnsProductInstanceRequest creates a request to invoke DescribeDnsProductInstance API -func CreateDescribeDnsProductInstanceRequest() (request *DescribeDnsProductInstanceRequest) { - request = &DescribeDnsProductInstanceRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDnsProductInstance", "", "") - return -} - -// CreateDescribeDnsProductInstanceResponse creates a response to parse from DescribeDnsProductInstance response -func CreateDescribeDnsProductInstanceResponse() (response *DescribeDnsProductInstanceResponse) { - response = &DescribeDnsProductInstanceResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go deleted file mode 100644 index ae17278e8..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dns_product_instances.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDnsProductInstances invokes the alidns.DescribeDnsProductInstances API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -func (client *Client) DescribeDnsProductInstances(request *DescribeDnsProductInstancesRequest) (response *DescribeDnsProductInstancesResponse, err error) { - response = CreateDescribeDnsProductInstancesResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDnsProductInstancesWithChan invokes the alidns.DescribeDnsProductInstances API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstancesWithChan(request *DescribeDnsProductInstancesRequest) (<-chan *DescribeDnsProductInstancesResponse, <-chan error) { - responseChan := make(chan *DescribeDnsProductInstancesResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDnsProductInstances(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDnsProductInstancesWithCallback invokes the alidns.DescribeDnsProductInstances API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsproductinstances.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDnsProductInstancesWithCallback(request *DescribeDnsProductInstancesRequest, callback func(response *DescribeDnsProductInstancesResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDnsProductInstancesResponse - var err error - defer close(result) - response, err = client.DescribeDnsProductInstances(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDnsProductInstancesRequest is the request struct for api DescribeDnsProductInstances -type DescribeDnsProductInstancesRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - VersionCode string `position:"Query" name:"VersionCode"` -} - -// DescribeDnsProductInstancesResponse is the response struct for api DescribeDnsProductInstances -type DescribeDnsProductInstancesResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DnsProducts DnsProducts `json:"DnsProducts" xml:"DnsProducts"` -} - -// CreateDescribeDnsProductInstancesRequest creates a request to invoke DescribeDnsProductInstances API -func CreateDescribeDnsProductInstancesRequest() (request *DescribeDnsProductInstancesRequest) { - request = &DescribeDnsProductInstancesRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDnsProductInstances", "", "") - return -} - -// CreateDescribeDnsProductInstancesResponse creates a response to parse from DescribeDnsProductInstances response -func CreateDescribeDnsProductInstancesResponse() (response *DescribeDnsProductInstancesResponse) { - response = &DescribeDnsProductInstancesResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go deleted file mode 100644 index b545f411a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_dnsslb_sub_domains.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDNSSLBSubDomains invokes the alidns.DescribeDNSSLBSubDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -func (client *Client) DescribeDNSSLBSubDomains(request *DescribeDNSSLBSubDomainsRequest) (response *DescribeDNSSLBSubDomainsResponse, err error) { - response = CreateDescribeDNSSLBSubDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDNSSLBSubDomainsWithChan invokes the alidns.DescribeDNSSLBSubDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDNSSLBSubDomainsWithChan(request *DescribeDNSSLBSubDomainsRequest) (<-chan *DescribeDNSSLBSubDomainsResponse, <-chan error) { - responseChan := make(chan *DescribeDNSSLBSubDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDNSSLBSubDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDNSSLBSubDomainsWithCallback invokes the alidns.DescribeDNSSLBSubDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describednsslbsubdomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDNSSLBSubDomainsWithCallback(request *DescribeDNSSLBSubDomainsRequest, callback func(response *DescribeDNSSLBSubDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDNSSLBSubDomainsResponse - var err error - defer close(result) - response, err = client.DescribeDNSSLBSubDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDNSSLBSubDomainsRequest is the request struct for api DescribeDNSSLBSubDomains -type DescribeDNSSLBSubDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDNSSLBSubDomainsResponse is the response struct for api DescribeDNSSLBSubDomains -type DescribeDNSSLBSubDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - SlbSubDomains SlbSubDomains `json:"SlbSubDomains" xml:"SlbSubDomains"` -} - -// CreateDescribeDNSSLBSubDomainsRequest creates a request to invoke DescribeDNSSLBSubDomains API -func CreateDescribeDNSSLBSubDomainsRequest() (request *DescribeDNSSLBSubDomainsRequest) { - request = &DescribeDNSSLBSubDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDNSSLBSubDomains", "", "") - return -} - -// CreateDescribeDNSSLBSubDomainsResponse creates a response to parse from DescribeDNSSLBSubDomains response -func CreateDescribeDNSSLBSubDomainsResponse() (response *DescribeDNSSLBSubDomainsResponse) { - response = &DescribeDNSSLBSubDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go deleted file mode 100644 index ffe1f1f37..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_groups.go +++ /dev/null @@ -1,111 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainGroups invokes the alidns.DescribeDomainGroups API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -func (client *Client) DescribeDomainGroups(request *DescribeDomainGroupsRequest) (response *DescribeDomainGroupsResponse, err error) { - response = CreateDescribeDomainGroupsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainGroupsWithChan invokes the alidns.DescribeDomainGroups API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainGroupsWithChan(request *DescribeDomainGroupsRequest) (<-chan *DescribeDomainGroupsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainGroupsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainGroups(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainGroupsWithCallback invokes the alidns.DescribeDomainGroups API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaingroups.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainGroupsWithCallback(request *DescribeDomainGroupsRequest, callback func(response *DescribeDomainGroupsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainGroupsResponse - var err error - defer close(result) - response, err = client.DescribeDomainGroups(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainGroupsRequest is the request struct for api DescribeDomainGroups -type DescribeDomainGroupsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDomainGroupsResponse is the response struct for api DescribeDomainGroups -type DescribeDomainGroupsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainGroups DomainGroups `json:"DomainGroups" xml:"DomainGroups"` -} - -// CreateDescribeDomainGroupsRequest creates a request to invoke DescribeDomainGroups API -func CreateDescribeDomainGroupsRequest() (request *DescribeDomainGroupsRequest) { - request = &DescribeDomainGroupsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainGroups", "", "") - return -} - -// CreateDescribeDomainGroupsResponse creates a response to parse from DescribeDomainGroups response -func CreateDescribeDomainGroupsResponse() (response *DescribeDomainGroupsResponse) { - response = &DescribeDomainGroupsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go deleted file mode 100644 index 0f6f3e08b..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_info.go +++ /dev/null @@ -1,123 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainInfo invokes the alidns.DescribeDomainInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -func (client *Client) DescribeDomainInfo(request *DescribeDomainInfoRequest) (response *DescribeDomainInfoResponse, err error) { - response = CreateDescribeDomainInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainInfoWithChan invokes the alidns.DescribeDomainInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainInfoWithChan(request *DescribeDomainInfoRequest) (<-chan *DescribeDomainInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainInfoWithCallback invokes the alidns.DescribeDomainInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomaininfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainInfoWithCallback(request *DescribeDomainInfoRequest, callback func(response *DescribeDomainInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainInfoRequest is the request struct for api DescribeDomainInfo -type DescribeDomainInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - NeedDetailAttributes requests.Boolean `position:"Query" name:"NeedDetailAttributes"` -} - -// DescribeDomainInfoResponse is the response struct for api DescribeDomainInfo -type DescribeDomainInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - AliDomain bool `json:"AliDomain" xml:"AliDomain"` - Remark string `json:"Remark" xml:"Remark"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - MinTtl int `json:"MinTtl" xml:"MinTtl"` - RecordLineTreeJson string `json:"RecordLineTreeJson" xml:"RecordLineTreeJson"` - LineType string `json:"LineType" xml:"LineType"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - DnsServers DnsServersInDescribeDomainInfo `json:"DnsServers" xml:"DnsServers"` - AvailableTtls AvailableTtls `json:"AvailableTtls" xml:"AvailableTtls"` - RecordLines RecordLinesInDescribeDomainInfo `json:"RecordLines" xml:"RecordLines"` -} - -// CreateDescribeDomainInfoRequest creates a request to invoke DescribeDomainInfo API -func CreateDescribeDomainInfoRequest() (request *DescribeDomainInfoRequest) { - request = &DescribeDomainInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainInfo", "", "") - return -} - -// CreateDescribeDomainInfoResponse creates a response to parse from DescribeDomainInfo response -func CreateDescribeDomainInfoResponse() (response *DescribeDomainInfoResponse) { - response = &DescribeDomainInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go deleted file mode 100644 index 39e18ce87..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_logs.go +++ /dev/null @@ -1,114 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainLogs invokes the alidns.DescribeDomainLogs API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -func (client *Client) DescribeDomainLogs(request *DescribeDomainLogsRequest) (response *DescribeDomainLogsResponse, err error) { - response = CreateDescribeDomainLogsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainLogsWithChan invokes the alidns.DescribeDomainLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainLogsWithChan(request *DescribeDomainLogsRequest) (<-chan *DescribeDomainLogsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainLogsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainLogs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainLogsWithCallback invokes the alidns.DescribeDomainLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainLogsWithCallback(request *DescribeDomainLogsRequest, callback func(response *DescribeDomainLogsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainLogsResponse - var err error - defer close(result) - response, err = client.DescribeDomainLogs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainLogsRequest is the request struct for api DescribeDomainLogs -type DescribeDomainLogsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - GroupId string `position:"Query" name:"GroupId"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - StartDate string `position:"Query" name:"StartDate"` - EndDate string `position:"Query" name:"endDate"` -} - -// DescribeDomainLogsResponse is the response struct for api DescribeDomainLogs -type DescribeDomainLogsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainLogs DomainLogs `json:"DomainLogs" xml:"DomainLogs"` -} - -// CreateDescribeDomainLogsRequest creates a request to invoke DescribeDomainLogs API -func CreateDescribeDomainLogsRequest() (request *DescribeDomainLogsRequest) { - request = &DescribeDomainLogsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainLogs", "", "") - return -} - -// CreateDescribeDomainLogsResponse creates a response to parse from DescribeDomainLogs response -func CreateDescribeDomainLogsResponse() (response *DescribeDomainLogsResponse) { - response = &DescribeDomainLogsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go deleted file mode 100644 index 51c86a95c..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_ns.go +++ /dev/null @@ -1,109 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainNs invokes the alidns.DescribeDomainNs API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -func (client *Client) DescribeDomainNs(request *DescribeDomainNsRequest) (response *DescribeDomainNsResponse, err error) { - response = CreateDescribeDomainNsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainNsWithChan invokes the alidns.DescribeDomainNs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainNsWithChan(request *DescribeDomainNsRequest) (<-chan *DescribeDomainNsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainNsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainNs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainNsWithCallback invokes the alidns.DescribeDomainNs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainNsWithCallback(request *DescribeDomainNsRequest, callback func(response *DescribeDomainNsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainNsResponse - var err error - defer close(result) - response, err = client.DescribeDomainNs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainNsRequest is the request struct for api DescribeDomainNs -type DescribeDomainNsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// DescribeDomainNsResponse is the response struct for api DescribeDomainNs -type DescribeDomainNsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - AllAliDns bool `json:"AllAliDns" xml:"AllAliDns"` - IncludeAliDns bool `json:"IncludeAliDns" xml:"IncludeAliDns"` - DnsServers DnsServersInDescribeDomainNs `json:"DnsServers" xml:"DnsServers"` - ExpectDnsServers ExpectDnsServers `json:"ExpectDnsServers" xml:"ExpectDnsServers"` -} - -// CreateDescribeDomainNsRequest creates a request to invoke DescribeDomainNs API -func CreateDescribeDomainNsRequest() (request *DescribeDomainNsRequest) { - request = &DescribeDomainNsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainNs", "", "") - return -} - -// CreateDescribeDomainNsResponse creates a response to parse from DescribeDomainNs response -func CreateDescribeDomainNsResponse() (response *DescribeDomainNsResponse) { - response = &DescribeDomainNsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go deleted file mode 100644 index c59a7c528..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_record_info.go +++ /dev/null @@ -1,119 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainRecordInfo invokes the alidns.DescribeDomainRecordInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -func (client *Client) DescribeDomainRecordInfo(request *DescribeDomainRecordInfoRequest) (response *DescribeDomainRecordInfoResponse, err error) { - response = CreateDescribeDomainRecordInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainRecordInfoWithChan invokes the alidns.DescribeDomainRecordInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordInfoWithChan(request *DescribeDomainRecordInfoRequest) (<-chan *DescribeDomainRecordInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainRecordInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainRecordInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainRecordInfoWithCallback invokes the alidns.DescribeDomainRecordInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecordinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordInfoWithCallback(request *DescribeDomainRecordInfoRequest, callback func(response *DescribeDomainRecordInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainRecordInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainRecordInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainRecordInfoRequest is the request struct for api DescribeDomainRecordInfo -type DescribeDomainRecordInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` -} - -// DescribeDomainRecordInfoResponse is the response struct for api DescribeDomainRecordInfo -type DescribeDomainRecordInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - RecordId string `json:"RecordId" xml:"RecordId"` - RR string `json:"RR" xml:"RR"` - Type string `json:"Type" xml:"Type"` - Value string `json:"Value" xml:"Value"` - TTL int `json:"TTL" xml:"TTL"` - Priority int `json:"Priority" xml:"Priority"` - Line string `json:"Line" xml:"Line"` - Status string `json:"Status" xml:"Status"` - Locked bool `json:"Locked" xml:"Locked"` -} - -// CreateDescribeDomainRecordInfoRequest creates a request to invoke DescribeDomainRecordInfo API -func CreateDescribeDomainRecordInfoRequest() (request *DescribeDomainRecordInfoRequest) { - request = &DescribeDomainRecordInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainRecordInfo", "", "") - return -} - -// CreateDescribeDomainRecordInfoResponse creates a response to parse from DescribeDomainRecordInfo response -func CreateDescribeDomainRecordInfoResponse() (response *DescribeDomainRecordInfoResponse) { - response = &DescribeDomainRecordInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go deleted file mode 100644 index bc905384a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_records.go +++ /dev/null @@ -1,117 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainRecords invokes the alidns.DescribeDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -func (client *Client) DescribeDomainRecords(request *DescribeDomainRecordsRequest) (response *DescribeDomainRecordsResponse, err error) { - response = CreateDescribeDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainRecordsWithChan invokes the alidns.DescribeDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordsWithChan(request *DescribeDomainRecordsRequest) (<-chan *DescribeDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainRecordsWithCallback invokes the alidns.DescribeDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainRecordsWithCallback(request *DescribeDomainRecordsRequest, callback func(response *DescribeDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainRecordsResponse - var err error - defer close(result) - response, err = client.DescribeDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainRecordsRequest is the request struct for api DescribeDomainRecords -type DescribeDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - KeyWord string `position:"Query" name:"KeyWord"` - RRKeyWord string `position:"Query" name:"RRKeyWord"` - TypeKeyWord string `position:"Query" name:"TypeKeyWord"` - ValueKeyWord string `position:"Query" name:"ValueKeyWord"` - OrderBy string `position:"Query" name:"OrderBy"` - Direction string `position:"Query" name:"Direction"` -} - -// DescribeDomainRecordsResponse is the response struct for api DescribeDomainRecords -type DescribeDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainRecords DomainRecordsInDescribeDomainRecords `json:"DomainRecords" xml:"DomainRecords"` -} - -// CreateDescribeDomainRecordsRequest creates a request to invoke DescribeDomainRecords API -func CreateDescribeDomainRecordsRequest() (request *DescribeDomainRecordsRequest) { - request = &DescribeDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainRecords", "", "") - return -} - -// CreateDescribeDomainRecordsResponse creates a response to parse from DescribeDomainRecords response -func CreateDescribeDomainRecordsResponse() (response *DescribeDomainRecordsResponse) { - response = &DescribeDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go deleted file mode 100644 index 9984f6dfc..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domain_whois_info.go +++ /dev/null @@ -1,113 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomainWhoisInfo invokes the alidns.DescribeDomainWhoisInfo API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -func (client *Client) DescribeDomainWhoisInfo(request *DescribeDomainWhoisInfoRequest) (response *DescribeDomainWhoisInfoResponse, err error) { - response = CreateDescribeDomainWhoisInfoResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainWhoisInfoWithChan invokes the alidns.DescribeDomainWhoisInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainWhoisInfoWithChan(request *DescribeDomainWhoisInfoRequest) (<-chan *DescribeDomainWhoisInfoResponse, <-chan error) { - responseChan := make(chan *DescribeDomainWhoisInfoResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomainWhoisInfo(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainWhoisInfoWithCallback invokes the alidns.DescribeDomainWhoisInfo API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomainwhoisinfo.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainWhoisInfoWithCallback(request *DescribeDomainWhoisInfoRequest, callback func(response *DescribeDomainWhoisInfoResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainWhoisInfoResponse - var err error - defer close(result) - response, err = client.DescribeDomainWhoisInfo(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainWhoisInfoRequest is the request struct for api DescribeDomainWhoisInfo -type DescribeDomainWhoisInfoRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - GroupId string `position:"Query" name:"GroupId"` -} - -// DescribeDomainWhoisInfoResponse is the response struct for api DescribeDomainWhoisInfo -type DescribeDomainWhoisInfoResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RegistrantName string `json:"RegistrantName" xml:"RegistrantName"` - RegistrantEmail string `json:"RegistrantEmail" xml:"RegistrantEmail"` - Registrar string `json:"Registrar" xml:"Registrar"` - RegistrationDate string `json:"RegistrationDate" xml:"RegistrationDate"` - ExpirationDate string `json:"ExpirationDate" xml:"ExpirationDate"` - StatusList StatusList `json:"StatusList" xml:"StatusList"` - DnsServers DnsServersInDescribeDomainWhoisInfo `json:"DnsServers" xml:"DnsServers"` -} - -// CreateDescribeDomainWhoisInfoRequest creates a request to invoke DescribeDomainWhoisInfo API -func CreateDescribeDomainWhoisInfoRequest() (request *DescribeDomainWhoisInfoRequest) { - request = &DescribeDomainWhoisInfoRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomainWhoisInfo", "", "") - return -} - -// CreateDescribeDomainWhoisInfoResponse creates a response to parse from DescribeDomainWhoisInfo response -func CreateDescribeDomainWhoisInfoResponse() (response *DescribeDomainWhoisInfoResponse) { - response = &DescribeDomainWhoisInfoResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go deleted file mode 100644 index a49982b7b..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_domains.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeDomains invokes the alidns.DescribeDomains API synchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -func (client *Client) DescribeDomains(request *DescribeDomainsRequest) (response *DescribeDomainsResponse, err error) { - response = CreateDescribeDomainsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeDomainsWithChan invokes the alidns.DescribeDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainsWithChan(request *DescribeDomainsRequest) (<-chan *DescribeDomainsResponse, <-chan error) { - responseChan := make(chan *DescribeDomainsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeDomains(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeDomainsWithCallback invokes the alidns.DescribeDomains API asynchronously -// api document: https://help.aliyun.com/api/alidns/describedomains.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeDomainsWithCallback(request *DescribeDomainsRequest, callback func(response *DescribeDomainsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeDomainsResponse - var err error - defer close(result) - response, err = client.DescribeDomains(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeDomainsRequest is the request struct for api DescribeDomains -type DescribeDomainsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - KeyWord string `position:"Query" name:"KeyWord"` - GroupId string `position:"Query" name:"GroupId"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` -} - -// DescribeDomainsResponse is the response struct for api DescribeDomains -type DescribeDomainsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - Domains Domains `json:"Domains" xml:"Domains"` -} - -// CreateDescribeDomainsRequest creates a request to invoke DescribeDomains API -func CreateDescribeDomainsRequest() (request *DescribeDomainsRequest) { - request = &DescribeDomainsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeDomains", "", "") - return -} - -// CreateDescribeDomainsResponse creates a response to parse from DescribeDomains response -func CreateDescribeDomainsResponse() (response *DescribeDomainsResponse) { - response = &DescribeDomainsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go deleted file mode 100644 index d9cd3e626..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_record_logs.go +++ /dev/null @@ -1,114 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeRecordLogs invokes the alidns.DescribeRecordLogs API synchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -func (client *Client) DescribeRecordLogs(request *DescribeRecordLogsRequest) (response *DescribeRecordLogsResponse, err error) { - response = CreateDescribeRecordLogsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeRecordLogsWithChan invokes the alidns.DescribeRecordLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeRecordLogsWithChan(request *DescribeRecordLogsRequest) (<-chan *DescribeRecordLogsResponse, <-chan error) { - responseChan := make(chan *DescribeRecordLogsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeRecordLogs(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeRecordLogsWithCallback invokes the alidns.DescribeRecordLogs API asynchronously -// api document: https://help.aliyun.com/api/alidns/describerecordlogs.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeRecordLogsWithCallback(request *DescribeRecordLogsRequest, callback func(response *DescribeRecordLogsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeRecordLogsResponse - var err error - defer close(result) - response, err = client.DescribeRecordLogs(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeRecordLogsRequest is the request struct for api DescribeRecordLogs -type DescribeRecordLogsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - KeyWord string `position:"Query" name:"KeyWord"` - StartDate string `position:"Query" name:"StartDate"` - EndDate string `position:"Query" name:"endDate"` -} - -// DescribeRecordLogsResponse is the response struct for api DescribeRecordLogs -type DescribeRecordLogsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - RecordLogs RecordLogs `json:"RecordLogs" xml:"RecordLogs"` -} - -// CreateDescribeRecordLogsRequest creates a request to invoke DescribeRecordLogs API -func CreateDescribeRecordLogsRequest() (request *DescribeRecordLogsRequest) { - request = &DescribeRecordLogsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeRecordLogs", "", "") - return -} - -// CreateDescribeRecordLogsResponse creates a response to parse from DescribeRecordLogs response -func CreateDescribeRecordLogsResponse() (response *DescribeRecordLogsResponse) { - response = &DescribeRecordLogsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go deleted file mode 100644 index 2b4ae7d94..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_sub_domain_records.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeSubDomainRecords invokes the alidns.DescribeSubDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -func (client *Client) DescribeSubDomainRecords(request *DescribeSubDomainRecordsRequest) (response *DescribeSubDomainRecordsResponse, err error) { - response = CreateDescribeSubDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// DescribeSubDomainRecordsWithChan invokes the alidns.DescribeSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSubDomainRecordsWithChan(request *DescribeSubDomainRecordsRequest) (<-chan *DescribeSubDomainRecordsResponse, <-chan error) { - responseChan := make(chan *DescribeSubDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeSubDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeSubDomainRecordsWithCallback invokes the alidns.DescribeSubDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesubdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSubDomainRecordsWithCallback(request *DescribeSubDomainRecordsRequest, callback func(response *DescribeSubDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeSubDomainRecordsResponse - var err error - defer close(result) - response, err = client.DescribeSubDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeSubDomainRecordsRequest is the request struct for api DescribeSubDomainRecords -type DescribeSubDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - SubDomain string `position:"Query" name:"SubDomain"` - PageNumber requests.Integer `position:"Query" name:"PageNumber"` - PageSize requests.Integer `position:"Query" name:"PageSize"` - Type string `position:"Query" name:"Type"` -} - -// DescribeSubDomainRecordsResponse is the response struct for api DescribeSubDomainRecords -type DescribeSubDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TotalCount int `json:"TotalCount" xml:"TotalCount"` - PageNumber int `json:"PageNumber" xml:"PageNumber"` - PageSize int `json:"PageSize" xml:"PageSize"` - DomainRecords DomainRecordsInDescribeSubDomainRecords `json:"DomainRecords" xml:"DomainRecords"` -} - -// CreateDescribeSubDomainRecordsRequest creates a request to invoke DescribeSubDomainRecords API -func CreateDescribeSubDomainRecordsRequest() (request *DescribeSubDomainRecordsRequest) { - request = &DescribeSubDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeSubDomainRecords", "", "") - return -} - -// CreateDescribeSubDomainRecordsResponse creates a response to parse from DescribeSubDomainRecords response -func CreateDescribeSubDomainRecordsResponse() (response *DescribeSubDomainRecordsResponse) { - response = &DescribeSubDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go deleted file mode 100644 index 3738c3cb2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/describe_support_lines.go +++ /dev/null @@ -1,105 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// DescribeSupportLines invokes the alidns.DescribeSupportLines API synchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -func (client *Client) DescribeSupportLines(request *DescribeSupportLinesRequest) (response *DescribeSupportLinesResponse, err error) { - response = CreateDescribeSupportLinesResponse() - err = client.DoAction(request, response) - return -} - -// DescribeSupportLinesWithChan invokes the alidns.DescribeSupportLines API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSupportLinesWithChan(request *DescribeSupportLinesRequest) (<-chan *DescribeSupportLinesResponse, <-chan error) { - responseChan := make(chan *DescribeSupportLinesResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.DescribeSupportLines(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// DescribeSupportLinesWithCallback invokes the alidns.DescribeSupportLines API asynchronously -// api document: https://help.aliyun.com/api/alidns/describesupportlines.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) DescribeSupportLinesWithCallback(request *DescribeSupportLinesRequest, callback func(response *DescribeSupportLinesResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *DescribeSupportLinesResponse - var err error - defer close(result) - response, err = client.DescribeSupportLines(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// DescribeSupportLinesRequest is the request struct for api DescribeSupportLines -type DescribeSupportLinesRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` -} - -// DescribeSupportLinesResponse is the response struct for api DescribeSupportLines -type DescribeSupportLinesResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordLines RecordLinesInDescribeSupportLines `json:"RecordLines" xml:"RecordLines"` -} - -// CreateDescribeSupportLinesRequest creates a request to invoke DescribeSupportLines API -func CreateDescribeSupportLinesRequest() (request *DescribeSupportLinesRequest) { - request = &DescribeSupportLinesRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "DescribeSupportLines", "", "") - return -} - -// CreateDescribeSupportLinesResponse creates a response to parse from DescribeSupportLines response -func CreateDescribeSupportLinesResponse() (response *DescribeSupportLinesResponse) { - response = &DescribeSupportLinesResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go deleted file mode 100644 index e5199878c..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/get_main_domain_name.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// GetMainDomainName invokes the alidns.GetMainDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -func (client *Client) GetMainDomainName(request *GetMainDomainNameRequest) (response *GetMainDomainNameResponse, err error) { - response = CreateGetMainDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// GetMainDomainNameWithChan invokes the alidns.GetMainDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) GetMainDomainNameWithChan(request *GetMainDomainNameRequest) (<-chan *GetMainDomainNameResponse, <-chan error) { - responseChan := make(chan *GetMainDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.GetMainDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// GetMainDomainNameWithCallback invokes the alidns.GetMainDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/getmaindomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) GetMainDomainNameWithCallback(request *GetMainDomainNameRequest, callback func(response *GetMainDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *GetMainDomainNameResponse - var err error - defer close(result) - response, err = client.GetMainDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// GetMainDomainNameRequest is the request struct for api GetMainDomainName -type GetMainDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - InputString string `position:"Query" name:"InputString"` -} - -// GetMainDomainNameResponse is the response struct for api GetMainDomainName -type GetMainDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` - RR string `json:"RR" xml:"RR"` - DomainLevel int `json:"DomainLevel" xml:"DomainLevel"` -} - -// CreateGetMainDomainNameRequest creates a request to invoke GetMainDomainName API -func CreateGetMainDomainNameRequest() (request *GetMainDomainNameRequest) { - request = &GetMainDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "GetMainDomainName", "", "") - return -} - -// CreateGetMainDomainNameResponse creates a response to parse from GetMainDomainName response -func CreateGetMainDomainNameResponse() (response *GetMainDomainNameResponse) { - response = &GetMainDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go deleted file mode 100644 index 3b452cdf7..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/modify_hichina_domain_dns.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// ModifyHichinaDomainDNS invokes the alidns.ModifyHichinaDomainDNS API synchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -func (client *Client) ModifyHichinaDomainDNS(request *ModifyHichinaDomainDNSRequest) (response *ModifyHichinaDomainDNSResponse, err error) { - response = CreateModifyHichinaDomainDNSResponse() - err = client.DoAction(request, response) - return -} - -// ModifyHichinaDomainDNSWithChan invokes the alidns.ModifyHichinaDomainDNS API asynchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ModifyHichinaDomainDNSWithChan(request *ModifyHichinaDomainDNSRequest) (<-chan *ModifyHichinaDomainDNSResponse, <-chan error) { - responseChan := make(chan *ModifyHichinaDomainDNSResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.ModifyHichinaDomainDNS(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// ModifyHichinaDomainDNSWithCallback invokes the alidns.ModifyHichinaDomainDNS API asynchronously -// api document: https://help.aliyun.com/api/alidns/modifyhichinadomaindns.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) ModifyHichinaDomainDNSWithCallback(request *ModifyHichinaDomainDNSRequest, callback func(response *ModifyHichinaDomainDNSResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *ModifyHichinaDomainDNSResponse - var err error - defer close(result) - response, err = client.ModifyHichinaDomainDNS(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// ModifyHichinaDomainDNSRequest is the request struct for api ModifyHichinaDomainDNS -type ModifyHichinaDomainDNSRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// ModifyHichinaDomainDNSResponse is the response struct for api ModifyHichinaDomainDNS -type ModifyHichinaDomainDNSResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - OriginalDnsServers OriginalDnsServers `json:"OriginalDnsServers" xml:"OriginalDnsServers"` - NewDnsServers NewDnsServers `json:"NewDnsServers" xml:"NewDnsServers"` -} - -// CreateModifyHichinaDomainDNSRequest creates a request to invoke ModifyHichinaDomainDNS API -func CreateModifyHichinaDomainDNSRequest() (request *ModifyHichinaDomainDNSRequest) { - request = &ModifyHichinaDomainDNSRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "ModifyHichinaDomainDNS", "", "") - return -} - -// CreateModifyHichinaDomainDNSResponse creates a response to parse from ModifyHichinaDomainDNS response -func CreateModifyHichinaDomainDNSResponse() (response *ModifyHichinaDomainDNSResponse) { - response = &ModifyHichinaDomainDNSResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go deleted file mode 100644 index 753b85df5..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/retrieval_domain_name.go +++ /dev/null @@ -1,107 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// RetrievalDomainName invokes the alidns.RetrievalDomainName API synchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -func (client *Client) RetrievalDomainName(request *RetrievalDomainNameRequest) (response *RetrievalDomainNameResponse, err error) { - response = CreateRetrievalDomainNameResponse() - err = client.DoAction(request, response) - return -} - -// RetrievalDomainNameWithChan invokes the alidns.RetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) RetrievalDomainNameWithChan(request *RetrievalDomainNameRequest) (<-chan *RetrievalDomainNameResponse, <-chan error) { - responseChan := make(chan *RetrievalDomainNameResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.RetrievalDomainName(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// RetrievalDomainNameWithCallback invokes the alidns.RetrievalDomainName API asynchronously -// api document: https://help.aliyun.com/api/alidns/retrievaldomainname.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) RetrievalDomainNameWithCallback(request *RetrievalDomainNameRequest, callback func(response *RetrievalDomainNameResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *RetrievalDomainNameResponse - var err error - defer close(result) - response, err = client.RetrievalDomainName(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// RetrievalDomainNameRequest is the request struct for api RetrievalDomainName -type RetrievalDomainNameRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - DomainName string `position:"Query" name:"DomainName"` -} - -// RetrievalDomainNameResponse is the response struct for api RetrievalDomainName -type RetrievalDomainNameResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - DomainName string `json:"DomainName" xml:"DomainName"` - WhoisEmail string `json:"WhoisEmail" xml:"WhoisEmail"` -} - -// CreateRetrievalDomainNameRequest creates a request to invoke RetrievalDomainName API -func CreateRetrievalDomainNameRequest() (request *RetrievalDomainNameRequest) { - request = &RetrievalDomainNameRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "RetrievalDomainName", "", "") - return -} - -// CreateRetrievalDomainNameResponse creates a response to parse from RetrievalDomainName response -func CreateRetrievalDomainNameResponse() (response *RetrievalDomainNameResponse) { - response = &RetrievalDomainNameResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go deleted file mode 100644 index 858d6fe67..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_dnsslb_status.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SetDNSSLBStatus invokes the alidns.SetDNSSLBStatus API synchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -func (client *Client) SetDNSSLBStatus(request *SetDNSSLBStatusRequest) (response *SetDNSSLBStatusResponse, err error) { - response = CreateSetDNSSLBStatusResponse() - err = client.DoAction(request, response) - return -} - -// SetDNSSLBStatusWithChan invokes the alidns.SetDNSSLBStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDNSSLBStatusWithChan(request *SetDNSSLBStatusRequest) (<-chan *SetDNSSLBStatusResponse, <-chan error) { - responseChan := make(chan *SetDNSSLBStatusResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SetDNSSLBStatus(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SetDNSSLBStatusWithCallback invokes the alidns.SetDNSSLBStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdnsslbstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDNSSLBStatusWithCallback(request *SetDNSSLBStatusRequest, callback func(response *SetDNSSLBStatusResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SetDNSSLBStatusResponse - var err error - defer close(result) - response, err = client.SetDNSSLBStatus(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SetDNSSLBStatusRequest is the request struct for api SetDNSSLBStatus -type SetDNSSLBStatusRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - SubDomain string `position:"Query" name:"SubDomain"` - Open requests.Boolean `position:"Query" name:"Open"` -} - -// SetDNSSLBStatusResponse is the response struct for api SetDNSSLBStatus -type SetDNSSLBStatusResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - Open bool `json:"Open" xml:"Open"` -} - -// CreateSetDNSSLBStatusRequest creates a request to invoke SetDNSSLBStatus API -func CreateSetDNSSLBStatusRequest() (request *SetDNSSLBStatusRequest) { - request = &SetDNSSLBStatusRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "SetDNSSLBStatus", "", "") - return -} - -// CreateSetDNSSLBStatusResponse creates a response to parse from SetDNSSLBStatus response -func CreateSetDNSSLBStatusResponse() (response *SetDNSSLBStatusResponse) { - response = &SetDNSSLBStatusResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go deleted file mode 100644 index 29ba5f727..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/set_domain_record_status.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// SetDomainRecordStatus invokes the alidns.SetDomainRecordStatus API synchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -func (client *Client) SetDomainRecordStatus(request *SetDomainRecordStatusRequest) (response *SetDomainRecordStatusResponse, err error) { - response = CreateSetDomainRecordStatusResponse() - err = client.DoAction(request, response) - return -} - -// SetDomainRecordStatusWithChan invokes the alidns.SetDomainRecordStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDomainRecordStatusWithChan(request *SetDomainRecordStatusRequest) (<-chan *SetDomainRecordStatusResponse, <-chan error) { - responseChan := make(chan *SetDomainRecordStatusResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.SetDomainRecordStatus(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// SetDomainRecordStatusWithCallback invokes the alidns.SetDomainRecordStatus API asynchronously -// api document: https://help.aliyun.com/api/alidns/setdomainrecordstatus.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) SetDomainRecordStatusWithCallback(request *SetDomainRecordStatusRequest, callback func(response *SetDomainRecordStatusResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *SetDomainRecordStatusResponse - var err error - defer close(result) - response, err = client.SetDomainRecordStatus(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// SetDomainRecordStatusRequest is the request struct for api SetDomainRecordStatus -type SetDomainRecordStatusRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - Status string `position:"Query" name:"Status"` -} - -// SetDomainRecordStatusResponse is the response struct for api SetDomainRecordStatus -type SetDomainRecordStatusResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` - Status string `json:"Status" xml:"Status"` -} - -// CreateSetDomainRecordStatusRequest creates a request to invoke SetDomainRecordStatus API -func CreateSetDomainRecordStatusRequest() (request *SetDomainRecordStatusRequest) { - request = &SetDomainRecordStatusRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "SetDomainRecordStatus", "", "") - return -} - -// CreateSetDomainRecordStatusResponse creates a response to parse from SetDomainRecordStatus response -func CreateSetDomainRecordStatusResponse() (response *SetDomainRecordStatusResponse) { - response = &SetDomainRecordStatusResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go deleted file mode 100644 index e1d0ac7d5..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_available_ttls.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// AvailableTtls is a nested struct in alidns response -type AvailableTtls struct { - AvailableTtl []string `json:"AvailableTtl" xml:"AvailableTtl"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go deleted file mode 100644 index 50a2e8678..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_product.go +++ /dev/null @@ -1,48 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsProduct is a nested struct in alidns response -type DnsProduct struct { - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - StartTime string `json:"StartTime" xml:"StartTime"` - EndTime string `json:"EndTime" xml:"EndTime"` - StartTimestamp int `json:"StartTimestamp" xml:"StartTimestamp"` - EndTimestamp int `json:"EndTimestamp" xml:"EndTimestamp"` - Domain string `json:"Domain" xml:"Domain"` - BindCount int `json:"BindCount" xml:"BindCount"` - BindUsedCount int `json:"BindUsedCount" xml:"BindUsedCount"` - TTLMinValue int `json:"TTLMinValue" xml:"TTLMinValue"` - SubDomainLevel int `json:"SubDomainLevel" xml:"SubDomainLevel"` - DnsSLBCount int `json:"DnsSLBCount" xml:"DnsSLBCount"` - URLForwardCount int `json:"URLForwardCount" xml:"URLForwardCount"` - DDosDefendFlow int `json:"DDosDefendFlow" xml:"DDosDefendFlow"` - DDosDefendQuery int `json:"DDosDefendQuery" xml:"DDosDefendQuery"` - OverseaDDosDefendFlow int `json:"OverseaDDosDefendFlow" xml:"OverseaDDosDefendFlow"` - SearchEngineLines string `json:"SearchEngineLines" xml:"SearchEngineLines"` - ISPLines string `json:"ISPLines" xml:"ISPLines"` - ISPRegionLines string `json:"ISPRegionLines" xml:"ISPRegionLines"` - OverseaLine string `json:"OverseaLine" xml:"OverseaLine"` - MonitorNodeCount int `json:"MonitorNodeCount" xml:"MonitorNodeCount"` - MonitorFrequency int `json:"MonitorFrequency" xml:"MonitorFrequency"` - MonitorTaskCount int `json:"MonitorTaskCount" xml:"MonitorTaskCount"` - RegionLines bool `json:"RegionLines" xml:"RegionLines"` - Gslb bool `json:"Gslb" xml:"Gslb"` - InClean bool `json:"InClean" xml:"InClean"` - InBlackHole bool `json:"InBlackHole" xml:"InBlackHole"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go deleted file mode 100644 index 636a96ff0..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_products.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsProducts is a nested struct in alidns response -type DnsProducts struct { - DnsProduct []DnsProduct `json:"DnsProduct" xml:"DnsProduct"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go deleted file mode 100644 index d6f5bfb2b..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_add_domain.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInAddDomain is a nested struct in alidns response -type DnsServersInAddDomain struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go deleted file mode 100644 index 64d0db2ff..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_dns_product_instance.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDnsProductInstance is a nested struct in alidns response -type DnsServersInDescribeDnsProductInstance struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go deleted file mode 100644 index debe6483b..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainInfo is a nested struct in alidns response -type DnsServersInDescribeDomainInfo struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go deleted file mode 100644 index 67d752ec9..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_ns.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainNs is a nested struct in alidns response -type DnsServersInDescribeDomainNs struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go deleted file mode 100644 index fc03ed41a..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domain_whois_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomainWhoisInfo is a nested struct in alidns response -type DnsServersInDescribeDomainWhoisInfo struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go deleted file mode 100644 index dada40af2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_dns_servers_in_describe_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DnsServersInDescribeDomains is a nested struct in alidns response -type DnsServersInDescribeDomains struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go deleted file mode 100644 index 0dd46e6f3..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain.go +++ /dev/null @@ -1,35 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Domain is a nested struct in alidns response -type Domain struct { - DomainId string `json:"DomainId" xml:"DomainId"` - DomainName string `json:"DomainName" xml:"DomainName"` - PunyCode string `json:"PunyCode" xml:"PunyCode"` - AliDomain bool `json:"AliDomain" xml:"AliDomain"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - RegistrantEmail string `json:"RegistrantEmail" xml:"RegistrantEmail"` - Remark string `json:"Remark" xml:"Remark"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - InstanceId string `json:"InstanceId" xml:"InstanceId"` - VersionCode string `json:"VersionCode" xml:"VersionCode"` - VersionName string `json:"VersionName" xml:"VersionName"` - InstanceEndTime string `json:"InstanceEndTime" xml:"InstanceEndTime"` - InstanceExpired bool `json:"InstanceExpired" xml:"InstanceExpired"` - DnsServers DnsServersInDescribeDomains `json:"DnsServers" xml:"DnsServers"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go deleted file mode 100644 index 89646e8a2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_group.go +++ /dev/null @@ -1,23 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainGroup is a nested struct in alidns response -type DomainGroup struct { - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` - DomainCount int `json:"DomainCount" xml:"DomainCount"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go deleted file mode 100644 index ce193d883..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_groups.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainGroups is a nested struct in alidns response -type DomainGroups struct { - DomainGroup []DomainGroup `json:"DomainGroup" xml:"DomainGroup"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go deleted file mode 100644 index 40128f6b9..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_log.go +++ /dev/null @@ -1,26 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainLog is a nested struct in alidns response -type DomainLog struct { - ActionTime string `json:"ActionTime" xml:"ActionTime"` - ActionTimestamp int `json:"ActionTimestamp" xml:"ActionTimestamp"` - DomainName string `json:"DomainName" xml:"DomainName"` - Action string `json:"Action" xml:"Action"` - Message string `json:"Message" xml:"Message"` - ClientIp string `json:"ClientIp" xml:"ClientIp"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go deleted file mode 100644 index 3964d02b5..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_logs.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainLogs is a nested struct in alidns response -type DomainLogs struct { - DomainLog []DomainLog `json:"DomainLog" xml:"DomainLog"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go deleted file mode 100644 index 5ef972598..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_domain_records.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainRecordsInDescribeDomainRecords is a nested struct in alidns response -type DomainRecordsInDescribeDomainRecords struct { - Record []Record `json:"Record" xml:"Record"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go deleted file mode 100644 index 9b64ba0c8..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domain_records_in_describe_sub_domain_records.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// DomainRecordsInDescribeSubDomainRecords is a nested struct in alidns response -type DomainRecordsInDescribeSubDomainRecords struct { - Record []Record `json:"Record" xml:"Record"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go deleted file mode 100644 index aff37f854..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Domains is a nested struct in alidns response -type Domains struct { - Domain []Domain `json:"Domain" xml:"Domain"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go deleted file mode 100644 index 9befd95b8..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_expect_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// ExpectDnsServers is a nested struct in alidns response -type ExpectDnsServers struct { - ExpectDnsServer []string `json:"ExpectDnsServer" xml:"ExpectDnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go deleted file mode 100644 index 0fc2d3051..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_result.go +++ /dev/null @@ -1,22 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// FailResult is a nested struct in alidns response -type FailResult struct { - BatchIndex string `json:"BatchIndex" xml:"BatchIndex"` - ErrorCode string `json:"ErrorCode" xml:"ErrorCode"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go deleted file mode 100644 index 54ee4d18d..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_fail_results.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// FailResults is a nested struct in alidns response -type FailResults struct { - FailResult []FailResult `json:"FailResult" xml:"FailResult"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go deleted file mode 100644 index 5fd8b180f..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_new_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// NewDnsServers is a nested struct in alidns response -type NewDnsServers struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go deleted file mode 100644 index b6f90bb3d..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_original_dns_servers.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// OriginalDnsServers is a nested struct in alidns response -type OriginalDnsServers struct { - DnsServer []string `json:"DnsServer" xml:"DnsServer"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go deleted file mode 100644 index b4f0f1913..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record.go +++ /dev/null @@ -1,32 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// Record is a nested struct in alidns response -type Record struct { - Locked bool `json:"Locked" xml:"Locked"` - Type string `json:"Type" xml:"Type"` - Line string `json:"Line" xml:"Line"` - RR string `json:"RR" xml:"RR"` - Remark string `json:"Remark" xml:"Remark"` - Priority int `json:"Priority" xml:"Priority"` - RecordId string `json:"RecordId" xml:"RecordId"` - Value string `json:"Value" xml:"Value"` - DomainName string `json:"DomainName" xml:"DomainName"` - Weight int `json:"Weight" xml:"Weight"` - Status string `json:"Status" xml:"Status"` - TTL int `json:"TTL" xml:"TTL"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go deleted file mode 100644 index 2219c2d16..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_line.go +++ /dev/null @@ -1,24 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLine is a nested struct in alidns response -type RecordLine struct { - LineName string `json:"LineName" xml:"LineName"` - FatherCode string `json:"FatherCode" xml:"FatherCode"` - LineDisplayName string `json:"LineDisplayName" xml:"LineDisplayName"` - LineCode string `json:"LineCode" xml:"LineCode"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go deleted file mode 100644 index 203f525b2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_domain_info.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLinesInDescribeDomainInfo is a nested struct in alidns response -type RecordLinesInDescribeDomainInfo struct { - RecordLine []RecordLine `json:"RecordLine" xml:"RecordLine"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go deleted file mode 100644 index 5c2e05f20..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_lines_in_describe_support_lines.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLinesInDescribeSupportLines is a nested struct in alidns response -type RecordLinesInDescribeSupportLines struct { - RecordLine []RecordLine `json:"RecordLine" xml:"RecordLine"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go deleted file mode 100644 index ee4583520..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_log.go +++ /dev/null @@ -1,25 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLog is a nested struct in alidns response -type RecordLog struct { - ActionTime string `json:"ActionTime" xml:"ActionTime"` - ActionTimestamp int `json:"ActionTimestamp" xml:"ActionTimestamp"` - Action string `json:"Action" xml:"Action"` - Message string `json:"Message" xml:"Message"` - ClientIp string `json:"ClientIp" xml:"ClientIp"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go deleted file mode 100644 index b5a42b5eb..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_record_logs.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// RecordLogs is a nested struct in alidns response -type RecordLogs struct { - RecordLog []RecordLog `json:"RecordLog" xml:"RecordLog"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go deleted file mode 100644 index 043a44718..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domain.go +++ /dev/null @@ -1,24 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SlbSubDomain is a nested struct in alidns response -type SlbSubDomain struct { - SubDomain string `json:"SubDomain" xml:"SubDomain"` - RecordCount int `json:"RecordCount" xml:"RecordCount"` - Open bool `json:"Open" xml:"Open"` - Type string `json:"Type" xml:"Type"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go deleted file mode 100644 index 4618d59c3..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_slb_sub_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// SlbSubDomains is a nested struct in alidns response -type SlbSubDomains struct { - SlbSubDomain []SlbSubDomain `json:"SlbSubDomain" xml:"SlbSubDomain"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go deleted file mode 100644 index 341e43d03..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/struct_status_list.go +++ /dev/null @@ -1,21 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -// StatusList is a nested struct in alidns response -type StatusList struct { - Status []string `json:"Status" xml:"Status"` -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go deleted file mode 100644 index c90e20455..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_batch_domain_records.go +++ /dev/null @@ -1,106 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateBatchDomainRecords invokes the alidns.UpdateBatchDomainRecords API synchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -func (client *Client) UpdateBatchDomainRecords(request *UpdateBatchDomainRecordsRequest) (response *UpdateBatchDomainRecordsResponse, err error) { - response = CreateUpdateBatchDomainRecordsResponse() - err = client.DoAction(request, response) - return -} - -// UpdateBatchDomainRecordsWithChan invokes the alidns.UpdateBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateBatchDomainRecordsWithChan(request *UpdateBatchDomainRecordsRequest) (<-chan *UpdateBatchDomainRecordsResponse, <-chan error) { - responseChan := make(chan *UpdateBatchDomainRecordsResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateBatchDomainRecords(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateBatchDomainRecordsWithCallback invokes the alidns.UpdateBatchDomainRecords API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatebatchdomainrecords.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateBatchDomainRecordsWithCallback(request *UpdateBatchDomainRecordsRequest, callback func(response *UpdateBatchDomainRecordsResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateBatchDomainRecordsResponse - var err error - defer close(result) - response, err = client.UpdateBatchDomainRecords(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateBatchDomainRecordsRequest is the request struct for api UpdateBatchDomainRecords -type UpdateBatchDomainRecordsRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - Records string `position:"Query" name:"Records"` -} - -// UpdateBatchDomainRecordsResponse is the response struct for api UpdateBatchDomainRecords -type UpdateBatchDomainRecordsResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - TraceId string `json:"TraceId" xml:"TraceId"` -} - -// CreateUpdateBatchDomainRecordsRequest creates a request to invoke UpdateBatchDomainRecords API -func CreateUpdateBatchDomainRecordsRequest() (request *UpdateBatchDomainRecordsRequest) { - request = &UpdateBatchDomainRecordsRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateBatchDomainRecords", "", "") - return -} - -// CreateUpdateBatchDomainRecordsResponse creates a response to parse from UpdateBatchDomainRecords response -func CreateUpdateBatchDomainRecordsResponse() (response *UpdateBatchDomainRecordsResponse) { - response = &UpdateBatchDomainRecordsResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go deleted file mode 100644 index ec372a215..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_dnsslb_weight.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDNSSLBWeight invokes the alidns.UpdateDNSSLBWeight API synchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -func (client *Client) UpdateDNSSLBWeight(request *UpdateDNSSLBWeightRequest) (response *UpdateDNSSLBWeightResponse, err error) { - response = CreateUpdateDNSSLBWeightResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDNSSLBWeightWithChan invokes the alidns.UpdateDNSSLBWeight API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDNSSLBWeightWithChan(request *UpdateDNSSLBWeightRequest) (<-chan *UpdateDNSSLBWeightResponse, <-chan error) { - responseChan := make(chan *UpdateDNSSLBWeightResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDNSSLBWeight(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDNSSLBWeightWithCallback invokes the alidns.UpdateDNSSLBWeight API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatednsslbweight.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDNSSLBWeightWithCallback(request *UpdateDNSSLBWeightRequest, callback func(response *UpdateDNSSLBWeightResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDNSSLBWeightResponse - var err error - defer close(result) - response, err = client.UpdateDNSSLBWeight(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDNSSLBWeightRequest is the request struct for api UpdateDNSSLBWeight -type UpdateDNSSLBWeightRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - Weight requests.Integer `position:"Query" name:"Weight"` -} - -// UpdateDNSSLBWeightResponse is the response struct for api UpdateDNSSLBWeight -type UpdateDNSSLBWeightResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` - Weight int `json:"Weight" xml:"Weight"` -} - -// CreateUpdateDNSSLBWeightRequest creates a request to invoke UpdateDNSSLBWeight API -func CreateUpdateDNSSLBWeightRequest() (request *UpdateDNSSLBWeightRequest) { - request = &UpdateDNSSLBWeightRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDNSSLBWeight", "", "") - return -} - -// CreateUpdateDNSSLBWeightResponse creates a response to parse from UpdateDNSSLBWeight response -func CreateUpdateDNSSLBWeightResponse() (response *UpdateDNSSLBWeightResponse) { - response = &UpdateDNSSLBWeightResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go deleted file mode 100644 index 61f1fb1d2..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_group.go +++ /dev/null @@ -1,108 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDomainGroup invokes the alidns.UpdateDomainGroup API synchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -func (client *Client) UpdateDomainGroup(request *UpdateDomainGroupRequest) (response *UpdateDomainGroupResponse, err error) { - response = CreateUpdateDomainGroupResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDomainGroupWithChan invokes the alidns.UpdateDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainGroupWithChan(request *UpdateDomainGroupRequest) (<-chan *UpdateDomainGroupResponse, <-chan error) { - responseChan := make(chan *UpdateDomainGroupResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDomainGroup(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDomainGroupWithCallback invokes the alidns.UpdateDomainGroup API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomaingroup.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainGroupWithCallback(request *UpdateDomainGroupRequest, callback func(response *UpdateDomainGroupResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDomainGroupResponse - var err error - defer close(result) - response, err = client.UpdateDomainGroup(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDomainGroupRequest is the request struct for api UpdateDomainGroup -type UpdateDomainGroupRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - GroupId string `position:"Query" name:"GroupId"` - GroupName string `position:"Query" name:"GroupName"` -} - -// UpdateDomainGroupResponse is the response struct for api UpdateDomainGroup -type UpdateDomainGroupResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - GroupId string `json:"GroupId" xml:"GroupId"` - GroupName string `json:"GroupName" xml:"GroupName"` -} - -// CreateUpdateDomainGroupRequest creates a request to invoke UpdateDomainGroup API -func CreateUpdateDomainGroupRequest() (request *UpdateDomainGroupRequest) { - request = &UpdateDomainGroupRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDomainGroup", "", "") - return -} - -// CreateUpdateDomainGroupResponse creates a response to parse from UpdateDomainGroup response -func CreateUpdateDomainGroupResponse() (response *UpdateDomainGroupResponse) { - response = &UpdateDomainGroupResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go b/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go deleted file mode 100644 index 1e9c0daf1..000000000 --- a/vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/alidns/update_domain_record.go +++ /dev/null @@ -1,112 +0,0 @@ -package alidns - -//Licensed under the Apache License, Version 2.0 (the "License"); -//you may not use this file except in compliance with the License. -//You may obtain a copy of the License at -// -//http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, -//WITHOUT 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 Alibaba Cloud SDK Code Generator. -// Changes may cause incorrect behavior and will be lost if the code is regenerated. - -import ( - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/responses" -) - -// UpdateDomainRecord invokes the alidns.UpdateDomainRecord API synchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -func (client *Client) UpdateDomainRecord(request *UpdateDomainRecordRequest) (response *UpdateDomainRecordResponse, err error) { - response = CreateUpdateDomainRecordResponse() - err = client.DoAction(request, response) - return -} - -// UpdateDomainRecordWithChan invokes the alidns.UpdateDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainRecordWithChan(request *UpdateDomainRecordRequest) (<-chan *UpdateDomainRecordResponse, <-chan error) { - responseChan := make(chan *UpdateDomainRecordResponse, 1) - errChan := make(chan error, 1) - err := client.AddAsyncTask(func() { - defer close(responseChan) - defer close(errChan) - response, err := client.UpdateDomainRecord(request) - if err != nil { - errChan <- err - } else { - responseChan <- response - } - }) - if err != nil { - errChan <- err - close(responseChan) - close(errChan) - } - return responseChan, errChan -} - -// UpdateDomainRecordWithCallback invokes the alidns.UpdateDomainRecord API asynchronously -// api document: https://help.aliyun.com/api/alidns/updatedomainrecord.html -// asynchronous document: https://help.aliyun.com/document_detail/66220.html -func (client *Client) UpdateDomainRecordWithCallback(request *UpdateDomainRecordRequest, callback func(response *UpdateDomainRecordResponse, err error)) <-chan int { - result := make(chan int, 1) - err := client.AddAsyncTask(func() { - var response *UpdateDomainRecordResponse - var err error - defer close(result) - response, err = client.UpdateDomainRecord(request) - callback(response, err) - result <- 1 - }) - if err != nil { - defer close(result) - callback(nil, err) - result <- 0 - } - return result -} - -// UpdateDomainRecordRequest is the request struct for api UpdateDomainRecord -type UpdateDomainRecordRequest struct { - *requests.RpcRequest - Lang string `position:"Query" name:"Lang"` - UserClientIp string `position:"Query" name:"UserClientIp"` - RecordId string `position:"Query" name:"RecordId"` - RR string `position:"Query" name:"RR"` - Type string `position:"Query" name:"Type"` - Value string `position:"Query" name:"Value"` - TTL requests.Integer `position:"Query" name:"TTL"` - Priority requests.Integer `position:"Query" name:"Priority"` - Line string `position:"Query" name:"Line"` -} - -// UpdateDomainRecordResponse is the response struct for api UpdateDomainRecord -type UpdateDomainRecordResponse struct { - *responses.BaseResponse - RequestId string `json:"RequestId" xml:"RequestId"` - RecordId string `json:"RecordId" xml:"RecordId"` -} - -// CreateUpdateDomainRecordRequest creates a request to invoke UpdateDomainRecord API -func CreateUpdateDomainRecordRequest() (request *UpdateDomainRecordRequest) { - request = &UpdateDomainRecordRequest{ - RpcRequest: &requests.RpcRequest{}, - } - request.InitWithApiInfo("Alidns", "2015-01-09", "UpdateDomainRecord", "", "") - return -} - -// CreateUpdateDomainRecordResponse creates a response to parse from UpdateDomainRecord response -func CreateUpdateDomainRecordResponse() (response *UpdateDomainRecordResponse) { - response = &UpdateDomainRecordResponse{ - BaseResponse: &responses.BaseResponse{}, - } - return -} diff --git a/vendor/github.com/apache/thrift/LICENSE b/vendor/github.com/apache/thrift/LICENSE deleted file mode 100644 index 3b6d7d74c..000000000 --- a/vendor/github.com/apache/thrift/LICENSE +++ /dev/null @@ -1,239 +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. - --------------------------------------------------- -SOFTWARE DISTRIBUTED WITH THRIFT: - -The Apache Thrift software includes a number of subcomponents with -separate copyright notices and license terms. Your use of the source -code for the these subcomponents is subject to the terms and -conditions of the following licenses. - --------------------------------------------------- -Portions of the following files are licensed under the MIT License: - - lib/erl/src/Makefile.am - -Please see doc/otp-base-license.txt for the full terms of this license. - --------------------------------------------------- -For the aclocal/ax_boost_base.m4 and contrib/fb303/aclocal/ax_boost_base.m4 components: - -# Copyright (c) 2007 Thomas Porschberg -# -# Copying and distribution of this file, with or without -# modification, are permitted in any medium without royalty provided -# the copyright notice and this notice are preserved. - --------------------------------------------------- -For the lib/nodejs/lib/thrift/json_parse.js: - -/* - json_parse.js - 2015-05-02 - Public Domain. - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - -*/ -(By Douglas Crockford ) --------------------------------------------------- diff --git a/vendor/github.com/apache/thrift/NOTICE b/vendor/github.com/apache/thrift/NOTICE deleted file mode 100644 index 902dc8d31..000000000 --- a/vendor/github.com/apache/thrift/NOTICE +++ /dev/null @@ -1,5 +0,0 @@ -Apache Thrift -Copyright 2006-2017 The Apache Software Foundation. - -This product includes software developed at -The Apache Software Foundation (http://www.apache.org/). diff --git a/vendor/github.com/apache/thrift/contrib/fb303/LICENSE b/vendor/github.com/apache/thrift/contrib/fb303/LICENSE deleted file mode 100644 index 4eacb6431..000000000 --- a/vendor/github.com/apache/thrift/contrib/fb303/LICENSE +++ /dev/null @@ -1,16 +0,0 @@ -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you under the Apache License, Version 2.0 (the -"License"); you may not use this file except in compliance -with the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, -software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT 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/apache/thrift/debian/copyright b/vendor/github.com/apache/thrift/debian/copyright deleted file mode 100644 index 850643c9a..000000000 --- a/vendor/github.com/apache/thrift/debian/copyright +++ /dev/null @@ -1,129 +0,0 @@ -This package was debianized by Thrift Developer's . - - -This package and the Debian packaging is licensed under the Apache License, -see `/usr/share/common-licenses/Apache-2.0'. - -The following information was copied from Apache Thrift LICENSE file. - --------------------------------------------------- -SOFTWARE DISTRIBUTED WITH THRIFT: - -The Apache Thrift software includes a number of subcomponents with -separate copyright notices and license terms. Your use of the source -code for the these subcomponents is subject to the terms and -conditions of the following licenses. - --------------------------------------------------- -Portions of the following files are licensed under the MIT License: - - lib/erl/src/Makefile.am - -Please see doc/otp-base-license.txt for the full terms of this license. - - --------------------------------------------------- -The following files contain some portions of code contributed under -the Thrift Software License (see doc/old-thrift-license.txt), and relicensed -under the Apache 2.0 License: - - compiler/cpp/Makefile.am - compiler/cpp/src/generate/t_cocoa_generator.cc - compiler/cpp/src/generate/t_cpp_generator.cc - compiler/cpp/src/generate/t_csharp_generator.cc - compiler/cpp/src/generate/t_erl_generator.cc - compiler/cpp/src/generate/t_hs_generator.cc - compiler/cpp/src/generate/t_java_generator.cc - compiler/cpp/src/generate/t_ocaml_generator.cc - compiler/cpp/src/generate/t_perl_generator.cc - compiler/cpp/src/generate/t_php_generator.cc - compiler/cpp/src/generate/t_py_generator.cc - compiler/cpp/src/generate/t_rb_generator.cc - compiler/cpp/src/generate/t_st_generator.cc - compiler/cpp/src/generate/t_xsd_generator.cc - compiler/cpp/src/main.cc - compiler/cpp/src/parse/t_field.h - compiler/cpp/src/parse/t_program.h - compiler/cpp/src/platform.h - compiler/cpp/src/thriftl.ll - compiler/cpp/src/thrifty.yy - lib/csharp/src/Protocol/TBinaryProtocol.cs - lib/csharp/src/Protocol/TField.cs - lib/csharp/src/Protocol/TList.cs - lib/csharp/src/Protocol/TMap.cs - lib/csharp/src/Protocol/TMessage.cs - lib/csharp/src/Protocol/TMessageType.cs - lib/csharp/src/Protocol/TProtocol.cs - lib/csharp/src/Protocol/TProtocolException.cs - lib/csharp/src/Protocol/TProtocolFactory.cs - lib/csharp/src/Protocol/TProtocolUtil.cs - lib/csharp/src/Protocol/TSet.cs - lib/csharp/src/Protocol/TStruct.cs - lib/csharp/src/Protocol/TType.cs - lib/csharp/src/Server/TServer.cs - lib/csharp/src/Server/TSimpleServer.cs - lib/csharp/src/Server/TThreadPoolServer.cs - lib/csharp/src/TApplicationException.cs - lib/csharp/src/Thrift.csproj - lib/csharp/src/Thrift.sln - lib/csharp/src/TProcessor.cs - lib/csharp/src/Transport/TServerSocket.cs - lib/csharp/src/Transport/TServerTransport.cs - lib/csharp/src/Transport/TSocket.cs - lib/csharp/src/Transport/TStreamTransport.cs - lib/csharp/src/Transport/TTransport.cs - lib/csharp/src/Transport/TTransportException.cs - lib/csharp/src/Transport/TTransportFactory.cs - lib/csharp/ThriftMSBuildTask/Properties/AssemblyInfo.cs - lib/csharp/ThriftMSBuildTask/ThriftBuild.cs - lib/csharp/ThriftMSBuildTask/ThriftMSBuildTask.csproj - lib/rb/lib/thrift.rb - lib/st/README - lib/st/thrift.st - test/OptionalRequiredTest.cpp - test/OptionalRequiredTest.thrift - test/ThriftTest.thrift - --------------------------------------------------- -For the aclocal/ax_boost_base.m4 and contrib/fb303/aclocal/ax_boost_base.m4 components: - -# Copyright (c) 2007 Thomas Porschberg -# -# Copying and distribution of this file, with or without -# modification, are permitted in any medium without royalty provided -# the copyright notice and this notice are preserved. - --------------------------------------------------- -For the compiler/cpp/src/md5.[ch] components: - -/* - Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved. - - This software is provided 'as-is', without any express or implied - warranty. In no event will the authors be held liable for any damages - arising from the use of this software. - - Permission is granted to anyone to use this software for any purpose, - including commercial applications, and to alter it and redistribute it - freely, subject to the following restrictions: - - 1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would be - appreciated but is not required. - 2. Altered source versions must be plainly marked as such, and must not be - misrepresented as being the original software. - 3. This notice may not be removed or altered from any source distribution. - - L. Peter Deutsch - ghost@aladdin.com - - */ - ---------------------------------------------------- -For the lib/rb/setup.rb: Copyright (c) 2000-2005 Minero Aoki, -lib/ocaml/OCamlMakefile and lib/ocaml/README-OCamlMakefile components: - Copyright (C) 1999 - 2007 Markus Mottl - -Licensed under the terms of the GNU Lesser General Public License 2.1 -(see doc/lgpl-2.1.txt for the full terms of this license) diff --git a/vendor/github.com/apache/thrift/lib/dart/LICENSE_HEADER b/vendor/github.com/apache/thrift/lib/dart/LICENSE_HEADER deleted file mode 100644 index 4eacb6431..000000000 --- a/vendor/github.com/apache/thrift/lib/dart/LICENSE_HEADER +++ /dev/null @@ -1,16 +0,0 @@ -Licensed to the Apache Software Foundation (ASF) under one -or more contributor license agreements. See the NOTICE file -distributed with this work for additional information -regarding copyright ownership. The ASF licenses this file -to you under the Apache License, Version 2.0 (the -"License"); you may not use this file except in compliance -with the License. You may obtain a copy of the License at - -http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, -software distributed under the License is distributed on an -"AS IS" BASIS, WITHOUT 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/apache/thrift/lib/go/thrift/application_exception.go b/vendor/github.com/apache/thrift/lib/go/thrift/application_exception.go deleted file mode 100644 index b9d7eedcd..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/application_exception.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -const ( - UNKNOWN_APPLICATION_EXCEPTION = 0 - UNKNOWN_METHOD = 1 - INVALID_MESSAGE_TYPE_EXCEPTION = 2 - WRONG_METHOD_NAME = 3 - BAD_SEQUENCE_ID = 4 - MISSING_RESULT = 5 - INTERNAL_ERROR = 6 - PROTOCOL_ERROR = 7 -) - -var defaultApplicationExceptionMessage = map[int32]string{ - UNKNOWN_APPLICATION_EXCEPTION: "unknown application exception", - UNKNOWN_METHOD: "unknown method", - INVALID_MESSAGE_TYPE_EXCEPTION: "invalid message type", - WRONG_METHOD_NAME: "wrong method name", - BAD_SEQUENCE_ID: "bad sequence ID", - MISSING_RESULT: "missing result", - INTERNAL_ERROR: "unknown internal error", - PROTOCOL_ERROR: "unknown protocol error", -} - -// Application level Thrift exception -type TApplicationException interface { - TException - TypeId() int32 - Read(iprot TProtocol) error - Write(oprot TProtocol) error -} - -type tApplicationException struct { - message string - type_ int32 -} - -func (e tApplicationException) Error() string { - if e.message != "" { - return e.message - } - return defaultApplicationExceptionMessage[e.type_] -} - -func NewTApplicationException(type_ int32, message string) TApplicationException { - return &tApplicationException{message, type_} -} - -func (p *tApplicationException) TypeId() int32 { - return p.type_ -} - -func (p *tApplicationException) Read(iprot TProtocol) error { - // TODO: this should really be generated by the compiler - _, err := iprot.ReadStructBegin() - if err != nil { - return err - } - - message := "" - type_ := int32(UNKNOWN_APPLICATION_EXCEPTION) - - for { - _, ttype, id, err := iprot.ReadFieldBegin() - if err != nil { - return err - } - if ttype == STOP { - break - } - switch id { - case 1: - if ttype == STRING { - if message, err = iprot.ReadString(); err != nil { - return err - } - } else { - if err = SkipDefaultDepth(iprot, ttype); err != nil { - return err - } - } - case 2: - if ttype == I32 { - if type_, err = iprot.ReadI32(); err != nil { - return err - } - } else { - if err = SkipDefaultDepth(iprot, ttype); err != nil { - return err - } - } - default: - if err = SkipDefaultDepth(iprot, ttype); err != nil { - return err - } - } - if err = iprot.ReadFieldEnd(); err != nil { - return err - } - } - if err := iprot.ReadStructEnd(); err != nil { - return err - } - - p.message = message - p.type_ = type_ - - return nil -} - -func (p *tApplicationException) Write(oprot TProtocol) (err error) { - err = oprot.WriteStructBegin("TApplicationException") - if len(p.Error()) > 0 { - err = oprot.WriteFieldBegin("message", STRING, 1) - if err != nil { - return - } - err = oprot.WriteString(p.Error()) - if err != nil { - return - } - err = oprot.WriteFieldEnd() - if err != nil { - return - } - } - err = oprot.WriteFieldBegin("type", I32, 2) - if err != nil { - return - } - err = oprot.WriteI32(p.type_) - if err != nil { - return - } - err = oprot.WriteFieldEnd() - if err != nil { - return - } - err = oprot.WriteFieldStop() - if err != nil { - return - } - err = oprot.WriteStructEnd() - return -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/binary_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/binary_protocol.go deleted file mode 100644 index 1f90bf435..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/binary_protocol.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bytes" - "context" - "encoding/binary" - "errors" - "fmt" - "io" - "math" -) - -type TBinaryProtocol struct { - trans TRichTransport - origTransport TTransport - reader io.Reader - writer io.Writer - strictRead bool - strictWrite bool - buffer [64]byte -} - -type TBinaryProtocolFactory struct { - strictRead bool - strictWrite bool -} - -func NewTBinaryProtocolTransport(t TTransport) *TBinaryProtocol { - return NewTBinaryProtocol(t, false, true) -} - -func NewTBinaryProtocol(t TTransport, strictRead, strictWrite bool) *TBinaryProtocol { - p := &TBinaryProtocol{origTransport: t, strictRead: strictRead, strictWrite: strictWrite} - if et, ok := t.(TRichTransport); ok { - p.trans = et - } else { - p.trans = NewTRichTransport(t) - } - p.reader = p.trans - p.writer = p.trans - return p -} - -func NewTBinaryProtocolFactoryDefault() *TBinaryProtocolFactory { - return NewTBinaryProtocolFactory(false, true) -} - -func NewTBinaryProtocolFactory(strictRead, strictWrite bool) *TBinaryProtocolFactory { - return &TBinaryProtocolFactory{strictRead: strictRead, strictWrite: strictWrite} -} - -func (p *TBinaryProtocolFactory) GetProtocol(t TTransport) TProtocol { - return NewTBinaryProtocol(t, p.strictRead, p.strictWrite) -} - -/** - * Writing Methods - */ - -func (p *TBinaryProtocol) WriteMessageBegin(name string, typeId TMessageType, seqId int32) error { - if p.strictWrite { - version := uint32(VERSION_1) | uint32(typeId) - e := p.WriteI32(int32(version)) - if e != nil { - return e - } - e = p.WriteString(name) - if e != nil { - return e - } - e = p.WriteI32(seqId) - return e - } else { - e := p.WriteString(name) - if e != nil { - return e - } - e = p.WriteByte(int8(typeId)) - if e != nil { - return e - } - e = p.WriteI32(seqId) - return e - } - return nil -} - -func (p *TBinaryProtocol) WriteMessageEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteStructBegin(name string) error { - return nil -} - -func (p *TBinaryProtocol) WriteStructEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteFieldBegin(name string, typeId TType, id int16) error { - e := p.WriteByte(int8(typeId)) - if e != nil { - return e - } - e = p.WriteI16(id) - return e -} - -func (p *TBinaryProtocol) WriteFieldEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteFieldStop() error { - e := p.WriteByte(STOP) - return e -} - -func (p *TBinaryProtocol) WriteMapBegin(keyType TType, valueType TType, size int) error { - e := p.WriteByte(int8(keyType)) - if e != nil { - return e - } - e = p.WriteByte(int8(valueType)) - if e != nil { - return e - } - e = p.WriteI32(int32(size)) - return e -} - -func (p *TBinaryProtocol) WriteMapEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteListBegin(elemType TType, size int) error { - e := p.WriteByte(int8(elemType)) - if e != nil { - return e - } - e = p.WriteI32(int32(size)) - return e -} - -func (p *TBinaryProtocol) WriteListEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteSetBegin(elemType TType, size int) error { - e := p.WriteByte(int8(elemType)) - if e != nil { - return e - } - e = p.WriteI32(int32(size)) - return e -} - -func (p *TBinaryProtocol) WriteSetEnd() error { - return nil -} - -func (p *TBinaryProtocol) WriteBool(value bool) error { - if value { - return p.WriteByte(1) - } - return p.WriteByte(0) -} - -func (p *TBinaryProtocol) WriteByte(value int8) error { - e := p.trans.WriteByte(byte(value)) - return NewTProtocolException(e) -} - -func (p *TBinaryProtocol) WriteI16(value int16) error { - v := p.buffer[0:2] - binary.BigEndian.PutUint16(v, uint16(value)) - _, e := p.writer.Write(v) - return NewTProtocolException(e) -} - -func (p *TBinaryProtocol) WriteI32(value int32) error { - v := p.buffer[0:4] - binary.BigEndian.PutUint32(v, uint32(value)) - _, e := p.writer.Write(v) - return NewTProtocolException(e) -} - -func (p *TBinaryProtocol) WriteI64(value int64) error { - v := p.buffer[0:8] - binary.BigEndian.PutUint64(v, uint64(value)) - _, err := p.writer.Write(v) - return NewTProtocolException(err) -} - -func (p *TBinaryProtocol) WriteDouble(value float64) error { - return p.WriteI64(int64(math.Float64bits(value))) -} - -func (p *TBinaryProtocol) WriteString(value string) error { - e := p.WriteI32(int32(len(value))) - if e != nil { - return e - } - _, err := p.trans.WriteString(value) - return NewTProtocolException(err) -} - -func (p *TBinaryProtocol) WriteBinary(value []byte) error { - e := p.WriteI32(int32(len(value))) - if e != nil { - return e - } - _, err := p.writer.Write(value) - return NewTProtocolException(err) -} - -/** - * Reading methods - */ - -func (p *TBinaryProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqId int32, err error) { - size, e := p.ReadI32() - if e != nil { - return "", typeId, 0, NewTProtocolException(e) - } - if size < 0 { - typeId = TMessageType(size & 0x0ff) - version := int64(int64(size) & VERSION_MASK) - if version != VERSION_1 { - return name, typeId, seqId, NewTProtocolExceptionWithType(BAD_VERSION, fmt.Errorf("Bad version in ReadMessageBegin")) - } - name, e = p.ReadString() - if e != nil { - return name, typeId, seqId, NewTProtocolException(e) - } - seqId, e = p.ReadI32() - if e != nil { - return name, typeId, seqId, NewTProtocolException(e) - } - return name, typeId, seqId, nil - } - if p.strictRead { - return name, typeId, seqId, NewTProtocolExceptionWithType(BAD_VERSION, fmt.Errorf("Missing version in ReadMessageBegin")) - } - name, e2 := p.readStringBody(size) - if e2 != nil { - return name, typeId, seqId, e2 - } - b, e3 := p.ReadByte() - if e3 != nil { - return name, typeId, seqId, e3 - } - typeId = TMessageType(b) - seqId, e4 := p.ReadI32() - if e4 != nil { - return name, typeId, seqId, e4 - } - return name, typeId, seqId, nil -} - -func (p *TBinaryProtocol) ReadMessageEnd() error { - return nil -} - -func (p *TBinaryProtocol) ReadStructBegin() (name string, err error) { - return -} - -func (p *TBinaryProtocol) ReadStructEnd() error { - return nil -} - -func (p *TBinaryProtocol) ReadFieldBegin() (name string, typeId TType, seqId int16, err error) { - t, err := p.ReadByte() - typeId = TType(t) - if err != nil { - return name, typeId, seqId, err - } - if t != STOP { - seqId, err = p.ReadI16() - } - return name, typeId, seqId, err -} - -func (p *TBinaryProtocol) ReadFieldEnd() error { - return nil -} - -var invalidDataLength = NewTProtocolExceptionWithType(INVALID_DATA, errors.New("Invalid data length")) - -func (p *TBinaryProtocol) ReadMapBegin() (kType, vType TType, size int, err error) { - k, e := p.ReadByte() - if e != nil { - err = NewTProtocolException(e) - return - } - kType = TType(k) - v, e := p.ReadByte() - if e != nil { - err = NewTProtocolException(e) - return - } - vType = TType(v) - size32, e := p.ReadI32() - if e != nil { - err = NewTProtocolException(e) - return - } - if size32 < 0 { - err = invalidDataLength - return - } - size = int(size32) - return kType, vType, size, nil -} - -func (p *TBinaryProtocol) ReadMapEnd() error { - return nil -} - -func (p *TBinaryProtocol) ReadListBegin() (elemType TType, size int, err error) { - b, e := p.ReadByte() - if e != nil { - err = NewTProtocolException(e) - return - } - elemType = TType(b) - size32, e := p.ReadI32() - if e != nil { - err = NewTProtocolException(e) - return - } - if size32 < 0 { - err = invalidDataLength - return - } - size = int(size32) - - return -} - -func (p *TBinaryProtocol) ReadListEnd() error { - return nil -} - -func (p *TBinaryProtocol) ReadSetBegin() (elemType TType, size int, err error) { - b, e := p.ReadByte() - if e != nil { - err = NewTProtocolException(e) - return - } - elemType = TType(b) - size32, e := p.ReadI32() - if e != nil { - err = NewTProtocolException(e) - return - } - if size32 < 0 { - err = invalidDataLength - return - } - size = int(size32) - return elemType, size, nil -} - -func (p *TBinaryProtocol) ReadSetEnd() error { - return nil -} - -func (p *TBinaryProtocol) ReadBool() (bool, error) { - b, e := p.ReadByte() - v := true - if b != 1 { - v = false - } - return v, e -} - -func (p *TBinaryProtocol) ReadByte() (int8, error) { - v, err := p.trans.ReadByte() - return int8(v), err -} - -func (p *TBinaryProtocol) ReadI16() (value int16, err error) { - buf := p.buffer[0:2] - err = p.readAll(buf) - value = int16(binary.BigEndian.Uint16(buf)) - return value, err -} - -func (p *TBinaryProtocol) ReadI32() (value int32, err error) { - buf := p.buffer[0:4] - err = p.readAll(buf) - value = int32(binary.BigEndian.Uint32(buf)) - return value, err -} - -func (p *TBinaryProtocol) ReadI64() (value int64, err error) { - buf := p.buffer[0:8] - err = p.readAll(buf) - value = int64(binary.BigEndian.Uint64(buf)) - return value, err -} - -func (p *TBinaryProtocol) ReadDouble() (value float64, err error) { - buf := p.buffer[0:8] - err = p.readAll(buf) - value = math.Float64frombits(binary.BigEndian.Uint64(buf)) - return value, err -} - -func (p *TBinaryProtocol) ReadString() (value string, err error) { - size, e := p.ReadI32() - if e != nil { - return "", e - } - if size < 0 { - err = invalidDataLength - return - } - - return p.readStringBody(size) -} - -func (p *TBinaryProtocol) ReadBinary() ([]byte, error) { - size, e := p.ReadI32() - if e != nil { - return nil, e - } - if size < 0 { - return nil, invalidDataLength - } - - isize := int(size) - buf := make([]byte, isize) - _, err := io.ReadFull(p.trans, buf) - return buf, NewTProtocolException(err) -} - -func (p *TBinaryProtocol) Flush(ctx context.Context) (err error) { - return NewTProtocolException(p.trans.Flush(ctx)) -} - -func (p *TBinaryProtocol) Skip(fieldType TType) (err error) { - return SkipDefaultDepth(p, fieldType) -} - -func (p *TBinaryProtocol) Transport() TTransport { - return p.origTransport -} - -func (p *TBinaryProtocol) readAll(buf []byte) error { - _, err := io.ReadFull(p.reader, buf) - return NewTProtocolException(err) -} - -const readLimit = 32768 - -func (p *TBinaryProtocol) readStringBody(size int32) (value string, err error) { - if size < 0 { - return "", nil - } - - var ( - buf bytes.Buffer - e error - b []byte - ) - - switch { - case int(size) <= len(p.buffer): - b = p.buffer[:size] // avoids allocation for small reads - case int(size) < readLimit: - b = make([]byte, size) - default: - b = make([]byte, readLimit) - } - - for size > 0 { - _, e = io.ReadFull(p.trans, b) - buf.Write(b) - if e != nil { - break - } - size -= readLimit - if size < readLimit && size > 0 { - b = b[:size] - } - } - return buf.String(), NewTProtocolException(e) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/buffered_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/buffered_transport.go deleted file mode 100644 index 96702061b..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/buffered_transport.go +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bufio" - "context" -) - -type TBufferedTransportFactory struct { - size int -} - -type TBufferedTransport struct { - bufio.ReadWriter - tp TTransport -} - -func (p *TBufferedTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - return NewTBufferedTransport(trans, p.size), nil -} - -func NewTBufferedTransportFactory(bufferSize int) *TBufferedTransportFactory { - return &TBufferedTransportFactory{size: bufferSize} -} - -func NewTBufferedTransport(trans TTransport, bufferSize int) *TBufferedTransport { - return &TBufferedTransport{ - ReadWriter: bufio.ReadWriter{ - Reader: bufio.NewReaderSize(trans, bufferSize), - Writer: bufio.NewWriterSize(trans, bufferSize), - }, - tp: trans, - } -} - -func (p *TBufferedTransport) IsOpen() bool { - return p.tp.IsOpen() -} - -func (p *TBufferedTransport) Open() (err error) { - return p.tp.Open() -} - -func (p *TBufferedTransport) Close() (err error) { - return p.tp.Close() -} - -func (p *TBufferedTransport) Read(b []byte) (int, error) { - n, err := p.ReadWriter.Read(b) - if err != nil { - p.ReadWriter.Reader.Reset(p.tp) - } - return n, err -} - -func (p *TBufferedTransport) Write(b []byte) (int, error) { - n, err := p.ReadWriter.Write(b) - if err != nil { - p.ReadWriter.Writer.Reset(p.tp) - } - return n, err -} - -func (p *TBufferedTransport) Flush(ctx context.Context) error { - if err := p.ReadWriter.Flush(); err != nil { - p.ReadWriter.Writer.Reset(p.tp) - return err - } - return p.tp.Flush(ctx) -} - -func (p *TBufferedTransport) RemainingBytes() (num_bytes uint64) { - return p.tp.RemainingBytes() -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/client.go b/vendor/github.com/apache/thrift/lib/go/thrift/client.go deleted file mode 100644 index 28791ccd0..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/client.go +++ /dev/null @@ -1,85 +0,0 @@ -package thrift - -import ( - "context" - "fmt" -) - -type TClient interface { - Call(ctx context.Context, method string, args, result TStruct) error -} - -type TStandardClient struct { - seqId int32 - iprot, oprot TProtocol -} - -// TStandardClient implements TClient, and uses the standard message format for Thrift. -// It is not safe for concurrent use. -func NewTStandardClient(inputProtocol, outputProtocol TProtocol) *TStandardClient { - return &TStandardClient{ - iprot: inputProtocol, - oprot: outputProtocol, - } -} - -func (p *TStandardClient) Send(ctx context.Context, oprot TProtocol, seqId int32, method string, args TStruct) error { - if err := oprot.WriteMessageBegin(method, CALL, seqId); err != nil { - return err - } - if err := args.Write(oprot); err != nil { - return err - } - if err := oprot.WriteMessageEnd(); err != nil { - return err - } - return oprot.Flush(ctx) -} - -func (p *TStandardClient) Recv(iprot TProtocol, seqId int32, method string, result TStruct) error { - rMethod, rTypeId, rSeqId, err := iprot.ReadMessageBegin() - if err != nil { - return err - } - - if method != rMethod { - return NewTApplicationException(WRONG_METHOD_NAME, fmt.Sprintf("%s: wrong method name", method)) - } else if seqId != rSeqId { - return NewTApplicationException(BAD_SEQUENCE_ID, fmt.Sprintf("%s: out of order sequence response", method)) - } else if rTypeId == EXCEPTION { - var exception tApplicationException - if err := exception.Read(iprot); err != nil { - return err - } - - if err := iprot.ReadMessageEnd(); err != nil { - return err - } - - return &exception - } else if rTypeId != REPLY { - return NewTApplicationException(INVALID_MESSAGE_TYPE_EXCEPTION, fmt.Sprintf("%s: invalid message type", method)) - } - - if err := result.Read(iprot); err != nil { - return err - } - - return iprot.ReadMessageEnd() -} - -func (p *TStandardClient) Call(ctx context.Context, method string, args, result TStruct) error { - p.seqId++ - seqId := p.seqId - - if err := p.Send(ctx, p.oprot, seqId, method, args); err != nil { - return err - } - - // method is oneway - if result == nil { - return nil - } - - return p.Recv(p.iprot, seqId, method, result) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/compact_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/compact_protocol.go deleted file mode 100644 index 1900d50c3..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/compact_protocol.go +++ /dev/null @@ -1,810 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "encoding/binary" - "fmt" - "io" - "math" -) - -const ( - COMPACT_PROTOCOL_ID = 0x082 - COMPACT_VERSION = 1 - COMPACT_VERSION_MASK = 0x1f - COMPACT_TYPE_MASK = 0x0E0 - COMPACT_TYPE_BITS = 0x07 - COMPACT_TYPE_SHIFT_AMOUNT = 5 -) - -type tCompactType byte - -const ( - COMPACT_BOOLEAN_TRUE = 0x01 - COMPACT_BOOLEAN_FALSE = 0x02 - COMPACT_BYTE = 0x03 - COMPACT_I16 = 0x04 - COMPACT_I32 = 0x05 - COMPACT_I64 = 0x06 - COMPACT_DOUBLE = 0x07 - COMPACT_BINARY = 0x08 - COMPACT_LIST = 0x09 - COMPACT_SET = 0x0A - COMPACT_MAP = 0x0B - COMPACT_STRUCT = 0x0C -) - -var ( - ttypeToCompactType map[TType]tCompactType -) - -func init() { - ttypeToCompactType = map[TType]tCompactType{ - STOP: STOP, - BOOL: COMPACT_BOOLEAN_TRUE, - BYTE: COMPACT_BYTE, - I16: COMPACT_I16, - I32: COMPACT_I32, - I64: COMPACT_I64, - DOUBLE: COMPACT_DOUBLE, - STRING: COMPACT_BINARY, - LIST: COMPACT_LIST, - SET: COMPACT_SET, - MAP: COMPACT_MAP, - STRUCT: COMPACT_STRUCT, - } -} - -type TCompactProtocolFactory struct{} - -func NewTCompactProtocolFactory() *TCompactProtocolFactory { - return &TCompactProtocolFactory{} -} - -func (p *TCompactProtocolFactory) GetProtocol(trans TTransport) TProtocol { - return NewTCompactProtocol(trans) -} - -type TCompactProtocol struct { - trans TRichTransport - origTransport TTransport - - // Used to keep track of the last field for the current and previous structs, - // so we can do the delta stuff. - lastField []int - lastFieldId int - - // If we encounter a boolean field begin, save the TField here so it can - // have the value incorporated. - booleanFieldName string - booleanFieldId int16 - booleanFieldPending bool - - // If we read a field header, and it's a boolean field, save the boolean - // value here so that readBool can use it. - boolValue bool - boolValueIsNotNull bool - buffer [64]byte -} - -// Create a TCompactProtocol given a TTransport -func NewTCompactProtocol(trans TTransport) *TCompactProtocol { - p := &TCompactProtocol{origTransport: trans, lastField: []int{}} - if et, ok := trans.(TRichTransport); ok { - p.trans = et - } else { - p.trans = NewTRichTransport(trans) - } - - return p - -} - -// -// Public Writing methods. -// - -// Write a message header to the wire. Compact Protocol messages contain the -// protocol version so we can migrate forwards in the future if need be. -func (p *TCompactProtocol) WriteMessageBegin(name string, typeId TMessageType, seqid int32) error { - err := p.writeByteDirect(COMPACT_PROTOCOL_ID) - if err != nil { - return NewTProtocolException(err) - } - err = p.writeByteDirect((COMPACT_VERSION & COMPACT_VERSION_MASK) | ((byte(typeId) << COMPACT_TYPE_SHIFT_AMOUNT) & COMPACT_TYPE_MASK)) - if err != nil { - return NewTProtocolException(err) - } - _, err = p.writeVarint32(seqid) - if err != nil { - return NewTProtocolException(err) - } - e := p.WriteString(name) - return e - -} - -func (p *TCompactProtocol) WriteMessageEnd() error { return nil } - -// Write a struct begin. This doesn't actually put anything on the wire. We -// use it as an opportunity to put special placeholder markers on the field -// stack so we can get the field id deltas correct. -func (p *TCompactProtocol) WriteStructBegin(name string) error { - p.lastField = append(p.lastField, p.lastFieldId) - p.lastFieldId = 0 - return nil -} - -// Write a struct end. This doesn't actually put anything on the wire. We use -// this as an opportunity to pop the last field from the current struct off -// of the field stack. -func (p *TCompactProtocol) WriteStructEnd() error { - p.lastFieldId = p.lastField[len(p.lastField)-1] - p.lastField = p.lastField[:len(p.lastField)-1] - return nil -} - -func (p *TCompactProtocol) WriteFieldBegin(name string, typeId TType, id int16) error { - if typeId == BOOL { - // we want to possibly include the value, so we'll wait. - p.booleanFieldName, p.booleanFieldId, p.booleanFieldPending = name, id, true - return nil - } - _, err := p.writeFieldBeginInternal(name, typeId, id, 0xFF) - return NewTProtocolException(err) -} - -// The workhorse of writeFieldBegin. It has the option of doing a -// 'type override' of the type header. This is used specifically in the -// boolean field case. -func (p *TCompactProtocol) writeFieldBeginInternal(name string, typeId TType, id int16, typeOverride byte) (int, error) { - // short lastField = lastField_.pop(); - - // if there's a type override, use that. - var typeToWrite byte - if typeOverride == 0xFF { - typeToWrite = byte(p.getCompactType(typeId)) - } else { - typeToWrite = typeOverride - } - // check if we can use delta encoding for the field id - fieldId := int(id) - written := 0 - if fieldId > p.lastFieldId && fieldId-p.lastFieldId <= 15 { - // write them together - err := p.writeByteDirect(byte((fieldId-p.lastFieldId)<<4) | typeToWrite) - if err != nil { - return 0, err - } - } else { - // write them separate - err := p.writeByteDirect(typeToWrite) - if err != nil { - return 0, err - } - err = p.WriteI16(id) - written = 1 + 2 - if err != nil { - return 0, err - } - } - - p.lastFieldId = fieldId - // p.lastField.Push(field.id); - return written, nil -} - -func (p *TCompactProtocol) WriteFieldEnd() error { return nil } - -func (p *TCompactProtocol) WriteFieldStop() error { - err := p.writeByteDirect(STOP) - return NewTProtocolException(err) -} - -func (p *TCompactProtocol) WriteMapBegin(keyType TType, valueType TType, size int) error { - if size == 0 { - err := p.writeByteDirect(0) - return NewTProtocolException(err) - } - _, err := p.writeVarint32(int32(size)) - if err != nil { - return NewTProtocolException(err) - } - err = p.writeByteDirect(byte(p.getCompactType(keyType))<<4 | byte(p.getCompactType(valueType))) - return NewTProtocolException(err) -} - -func (p *TCompactProtocol) WriteMapEnd() error { return nil } - -// Write a list header. -func (p *TCompactProtocol) WriteListBegin(elemType TType, size int) error { - _, err := p.writeCollectionBegin(elemType, size) - return NewTProtocolException(err) -} - -func (p *TCompactProtocol) WriteListEnd() error { return nil } - -// Write a set header. -func (p *TCompactProtocol) WriteSetBegin(elemType TType, size int) error { - _, err := p.writeCollectionBegin(elemType, size) - return NewTProtocolException(err) -} - -func (p *TCompactProtocol) WriteSetEnd() error { return nil } - -func (p *TCompactProtocol) WriteBool(value bool) error { - v := byte(COMPACT_BOOLEAN_FALSE) - if value { - v = byte(COMPACT_BOOLEAN_TRUE) - } - if p.booleanFieldPending { - // we haven't written the field header yet - _, err := p.writeFieldBeginInternal(p.booleanFieldName, BOOL, p.booleanFieldId, v) - p.booleanFieldPending = false - return NewTProtocolException(err) - } - // we're not part of a field, so just write the value. - err := p.writeByteDirect(v) - return NewTProtocolException(err) -} - -// Write a byte. Nothing to see here! -func (p *TCompactProtocol) WriteByte(value int8) error { - err := p.writeByteDirect(byte(value)) - return NewTProtocolException(err) -} - -// Write an I16 as a zigzag varint. -func (p *TCompactProtocol) WriteI16(value int16) error { - _, err := p.writeVarint32(p.int32ToZigzag(int32(value))) - return NewTProtocolException(err) -} - -// Write an i32 as a zigzag varint. -func (p *TCompactProtocol) WriteI32(value int32) error { - _, err := p.writeVarint32(p.int32ToZigzag(value)) - return NewTProtocolException(err) -} - -// Write an i64 as a zigzag varint. -func (p *TCompactProtocol) WriteI64(value int64) error { - _, err := p.writeVarint64(p.int64ToZigzag(value)) - return NewTProtocolException(err) -} - -// Write a double to the wire as 8 bytes. -func (p *TCompactProtocol) WriteDouble(value float64) error { - buf := p.buffer[0:8] - binary.LittleEndian.PutUint64(buf, math.Float64bits(value)) - _, err := p.trans.Write(buf) - return NewTProtocolException(err) -} - -// Write a string to the wire with a varint size preceding. -func (p *TCompactProtocol) WriteString(value string) error { - _, e := p.writeVarint32(int32(len(value))) - if e != nil { - return NewTProtocolException(e) - } - if len(value) > 0 { - } - _, e = p.trans.WriteString(value) - return e -} - -// Write a byte array, using a varint for the size. -func (p *TCompactProtocol) WriteBinary(bin []byte) error { - _, e := p.writeVarint32(int32(len(bin))) - if e != nil { - return NewTProtocolException(e) - } - if len(bin) > 0 { - _, e = p.trans.Write(bin) - return NewTProtocolException(e) - } - return nil -} - -// -// Reading methods. -// - -// Read a message header. -func (p *TCompactProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqId int32, err error) { - - protocolId, err := p.readByteDirect() - if err != nil { - return - } - - if protocolId != COMPACT_PROTOCOL_ID { - e := fmt.Errorf("Expected protocol id %02x but got %02x", COMPACT_PROTOCOL_ID, protocolId) - return "", typeId, seqId, NewTProtocolExceptionWithType(BAD_VERSION, e) - } - - versionAndType, err := p.readByteDirect() - if err != nil { - return - } - - version := versionAndType & COMPACT_VERSION_MASK - typeId = TMessageType((versionAndType >> COMPACT_TYPE_SHIFT_AMOUNT) & COMPACT_TYPE_BITS) - if version != COMPACT_VERSION { - e := fmt.Errorf("Expected version %02x but got %02x", COMPACT_VERSION, version) - err = NewTProtocolExceptionWithType(BAD_VERSION, e) - return - } - seqId, e := p.readVarint32() - if e != nil { - err = NewTProtocolException(e) - return - } - name, err = p.ReadString() - return -} - -func (p *TCompactProtocol) ReadMessageEnd() error { return nil } - -// Read a struct begin. There's nothing on the wire for this, but it is our -// opportunity to push a new struct begin marker onto the field stack. -func (p *TCompactProtocol) ReadStructBegin() (name string, err error) { - p.lastField = append(p.lastField, p.lastFieldId) - p.lastFieldId = 0 - return -} - -// Doesn't actually consume any wire data, just removes the last field for -// this struct from the field stack. -func (p *TCompactProtocol) ReadStructEnd() error { - // consume the last field we read off the wire. - p.lastFieldId = p.lastField[len(p.lastField)-1] - p.lastField = p.lastField[:len(p.lastField)-1] - return nil -} - -// Read a field header off the wire. -func (p *TCompactProtocol) ReadFieldBegin() (name string, typeId TType, id int16, err error) { - t, err := p.readByteDirect() - if err != nil { - return - } - - // if it's a stop, then we can return immediately, as the struct is over. - if (t & 0x0f) == STOP { - return "", STOP, 0, nil - } - - // mask off the 4 MSB of the type header. it could contain a field id delta. - modifier := int16((t & 0xf0) >> 4) - if modifier == 0 { - // not a delta. look ahead for the zigzag varint field id. - id, err = p.ReadI16() - if err != nil { - return - } - } else { - // has a delta. add the delta to the last read field id. - id = int16(p.lastFieldId) + modifier - } - typeId, e := p.getTType(tCompactType(t & 0x0f)) - if e != nil { - err = NewTProtocolException(e) - return - } - - // if this happens to be a boolean field, the value is encoded in the type - if p.isBoolType(t) { - // save the boolean value in a special instance variable. - p.boolValue = (byte(t)&0x0f == COMPACT_BOOLEAN_TRUE) - p.boolValueIsNotNull = true - } - - // push the new field onto the field stack so we can keep the deltas going. - p.lastFieldId = int(id) - return -} - -func (p *TCompactProtocol) ReadFieldEnd() error { return nil } - -// Read a map header off the wire. If the size is zero, skip reading the key -// and value type. This means that 0-length maps will yield TMaps without the -// "correct" types. -func (p *TCompactProtocol) ReadMapBegin() (keyType TType, valueType TType, size int, err error) { - size32, e := p.readVarint32() - if e != nil { - err = NewTProtocolException(e) - return - } - if size32 < 0 { - err = invalidDataLength - return - } - size = int(size32) - - keyAndValueType := byte(STOP) - if size != 0 { - keyAndValueType, err = p.readByteDirect() - if err != nil { - return - } - } - keyType, _ = p.getTType(tCompactType(keyAndValueType >> 4)) - valueType, _ = p.getTType(tCompactType(keyAndValueType & 0xf)) - return -} - -func (p *TCompactProtocol) ReadMapEnd() error { return nil } - -// Read a list header off the wire. If the list size is 0-14, the size will -// be packed into the element type header. If it's a longer list, the 4 MSB -// of the element type header will be 0xF, and a varint will follow with the -// true size. -func (p *TCompactProtocol) ReadListBegin() (elemType TType, size int, err error) { - size_and_type, err := p.readByteDirect() - if err != nil { - return - } - size = int((size_and_type >> 4) & 0x0f) - if size == 15 { - size2, e := p.readVarint32() - if e != nil { - err = NewTProtocolException(e) - return - } - if size2 < 0 { - err = invalidDataLength - return - } - size = int(size2) - } - elemType, e := p.getTType(tCompactType(size_and_type)) - if e != nil { - err = NewTProtocolException(e) - return - } - return -} - -func (p *TCompactProtocol) ReadListEnd() error { return nil } - -// Read a set header off the wire. If the set size is 0-14, the size will -// be packed into the element type header. If it's a longer set, the 4 MSB -// of the element type header will be 0xF, and a varint will follow with the -// true size. -func (p *TCompactProtocol) ReadSetBegin() (elemType TType, size int, err error) { - return p.ReadListBegin() -} - -func (p *TCompactProtocol) ReadSetEnd() error { return nil } - -// Read a boolean off the wire. If this is a boolean field, the value should -// already have been read during readFieldBegin, so we'll just consume the -// pre-stored value. Otherwise, read a byte. -func (p *TCompactProtocol) ReadBool() (value bool, err error) { - if p.boolValueIsNotNull { - p.boolValueIsNotNull = false - return p.boolValue, nil - } - v, err := p.readByteDirect() - return v == COMPACT_BOOLEAN_TRUE, err -} - -// Read a single byte off the wire. Nothing interesting here. -func (p *TCompactProtocol) ReadByte() (int8, error) { - v, err := p.readByteDirect() - if err != nil { - return 0, NewTProtocolException(err) - } - return int8(v), err -} - -// Read an i16 from the wire as a zigzag varint. -func (p *TCompactProtocol) ReadI16() (value int16, err error) { - v, err := p.ReadI32() - return int16(v), err -} - -// Read an i32 from the wire as a zigzag varint. -func (p *TCompactProtocol) ReadI32() (value int32, err error) { - v, e := p.readVarint32() - if e != nil { - return 0, NewTProtocolException(e) - } - value = p.zigzagToInt32(v) - return value, nil -} - -// Read an i64 from the wire as a zigzag varint. -func (p *TCompactProtocol) ReadI64() (value int64, err error) { - v, e := p.readVarint64() - if e != nil { - return 0, NewTProtocolException(e) - } - value = p.zigzagToInt64(v) - return value, nil -} - -// No magic here - just read a double off the wire. -func (p *TCompactProtocol) ReadDouble() (value float64, err error) { - longBits := p.buffer[0:8] - _, e := io.ReadFull(p.trans, longBits) - if e != nil { - return 0.0, NewTProtocolException(e) - } - return math.Float64frombits(p.bytesToUint64(longBits)), nil -} - -// Reads a []byte (via readBinary), and then UTF-8 decodes it. -func (p *TCompactProtocol) ReadString() (value string, err error) { - length, e := p.readVarint32() - if e != nil { - return "", NewTProtocolException(e) - } - if length < 0 { - return "", invalidDataLength - } - - if length == 0 { - return "", nil - } - var buf []byte - if length <= int32(len(p.buffer)) { - buf = p.buffer[0:length] - } else { - buf = make([]byte, length) - } - _, e = io.ReadFull(p.trans, buf) - return string(buf), NewTProtocolException(e) -} - -// Read a []byte from the wire. -func (p *TCompactProtocol) ReadBinary() (value []byte, err error) { - length, e := p.readVarint32() - if e != nil { - return nil, NewTProtocolException(e) - } - if length == 0 { - return []byte{}, nil - } - if length < 0 { - return nil, invalidDataLength - } - - buf := make([]byte, length) - _, e = io.ReadFull(p.trans, buf) - return buf, NewTProtocolException(e) -} - -func (p *TCompactProtocol) Flush(ctx context.Context) (err error) { - return NewTProtocolException(p.trans.Flush(ctx)) -} - -func (p *TCompactProtocol) Skip(fieldType TType) (err error) { - return SkipDefaultDepth(p, fieldType) -} - -func (p *TCompactProtocol) Transport() TTransport { - return p.origTransport -} - -// -// Internal writing methods -// - -// Abstract method for writing the start of lists and sets. List and sets on -// the wire differ only by the type indicator. -func (p *TCompactProtocol) writeCollectionBegin(elemType TType, size int) (int, error) { - if size <= 14 { - return 1, p.writeByteDirect(byte(int32(size<<4) | int32(p.getCompactType(elemType)))) - } - err := p.writeByteDirect(0xf0 | byte(p.getCompactType(elemType))) - if err != nil { - return 0, err - } - m, err := p.writeVarint32(int32(size)) - return 1 + m, err -} - -// Write an i32 as a varint. Results in 1-5 bytes on the wire. -// TODO(pomack): make a permanent buffer like writeVarint64? -func (p *TCompactProtocol) writeVarint32(n int32) (int, error) { - i32buf := p.buffer[0:5] - idx := 0 - for { - if (n & ^0x7F) == 0 { - i32buf[idx] = byte(n) - idx++ - // p.writeByteDirect(byte(n)); - break - // return; - } else { - i32buf[idx] = byte((n & 0x7F) | 0x80) - idx++ - // p.writeByteDirect(byte(((n & 0x7F) | 0x80))); - u := uint32(n) - n = int32(u >> 7) - } - } - return p.trans.Write(i32buf[0:idx]) -} - -// Write an i64 as a varint. Results in 1-10 bytes on the wire. -func (p *TCompactProtocol) writeVarint64(n int64) (int, error) { - varint64out := p.buffer[0:10] - idx := 0 - for { - if (n & ^0x7F) == 0 { - varint64out[idx] = byte(n) - idx++ - break - } else { - varint64out[idx] = byte((n & 0x7F) | 0x80) - idx++ - u := uint64(n) - n = int64(u >> 7) - } - } - return p.trans.Write(varint64out[0:idx]) -} - -// Convert l into a zigzag long. This allows negative numbers to be -// represented compactly as a varint. -func (p *TCompactProtocol) int64ToZigzag(l int64) int64 { - return (l << 1) ^ (l >> 63) -} - -// Convert l into a zigzag long. This allows negative numbers to be -// represented compactly as a varint. -func (p *TCompactProtocol) int32ToZigzag(n int32) int32 { - return (n << 1) ^ (n >> 31) -} - -func (p *TCompactProtocol) fixedUint64ToBytes(n uint64, buf []byte) { - binary.LittleEndian.PutUint64(buf, n) -} - -func (p *TCompactProtocol) fixedInt64ToBytes(n int64, buf []byte) { - binary.LittleEndian.PutUint64(buf, uint64(n)) -} - -// Writes a byte without any possibility of all that field header nonsense. -// Used internally by other writing methods that know they need to write a byte. -func (p *TCompactProtocol) writeByteDirect(b byte) error { - return p.trans.WriteByte(b) -} - -// Writes a byte without any possibility of all that field header nonsense. -func (p *TCompactProtocol) writeIntAsByteDirect(n int) (int, error) { - return 1, p.writeByteDirect(byte(n)) -} - -// -// Internal reading methods -// - -// Read an i32 from the wire as a varint. The MSB of each byte is set -// if there is another byte to follow. This can read up to 5 bytes. -func (p *TCompactProtocol) readVarint32() (int32, error) { - // if the wire contains the right stuff, this will just truncate the i64 we - // read and get us the right sign. - v, err := p.readVarint64() - return int32(v), err -} - -// Read an i64 from the wire as a proper varint. The MSB of each byte is set -// if there is another byte to follow. This can read up to 10 bytes. -func (p *TCompactProtocol) readVarint64() (int64, error) { - shift := uint(0) - result := int64(0) - for { - b, err := p.readByteDirect() - if err != nil { - return 0, err - } - result |= int64(b&0x7f) << shift - if (b & 0x80) != 0x80 { - break - } - shift += 7 - } - return result, nil -} - -// Read a byte, unlike ReadByte that reads Thrift-byte that is i8. -func (p *TCompactProtocol) readByteDirect() (byte, error) { - return p.trans.ReadByte() -} - -// -// encoding helpers -// - -// Convert from zigzag int to int. -func (p *TCompactProtocol) zigzagToInt32(n int32) int32 { - u := uint32(n) - return int32(u>>1) ^ -(n & 1) -} - -// Convert from zigzag long to long. -func (p *TCompactProtocol) zigzagToInt64(n int64) int64 { - u := uint64(n) - return int64(u>>1) ^ -(n & 1) -} - -// Note that it's important that the mask bytes are long literals, -// otherwise they'll default to ints, and when you shift an int left 56 bits, -// you just get a messed up int. -func (p *TCompactProtocol) bytesToInt64(b []byte) int64 { - return int64(binary.LittleEndian.Uint64(b)) -} - -// Note that it's important that the mask bytes are long literals, -// otherwise they'll default to ints, and when you shift an int left 56 bits, -// you just get a messed up int. -func (p *TCompactProtocol) bytesToUint64(b []byte) uint64 { - return binary.LittleEndian.Uint64(b) -} - -// -// type testing and converting -// - -func (p *TCompactProtocol) isBoolType(b byte) bool { - return (b&0x0f) == COMPACT_BOOLEAN_TRUE || (b&0x0f) == COMPACT_BOOLEAN_FALSE -} - -// Given a tCompactType constant, convert it to its corresponding -// TType value. -func (p *TCompactProtocol) getTType(t tCompactType) (TType, error) { - switch byte(t) & 0x0f { - case STOP: - return STOP, nil - case COMPACT_BOOLEAN_FALSE, COMPACT_BOOLEAN_TRUE: - return BOOL, nil - case COMPACT_BYTE: - return BYTE, nil - case COMPACT_I16: - return I16, nil - case COMPACT_I32: - return I32, nil - case COMPACT_I64: - return I64, nil - case COMPACT_DOUBLE: - return DOUBLE, nil - case COMPACT_BINARY: - return STRING, nil - case COMPACT_LIST: - return LIST, nil - case COMPACT_SET: - return SET, nil - case COMPACT_MAP: - return MAP, nil - case COMPACT_STRUCT: - return STRUCT, nil - } - return STOP, TException(fmt.Errorf("don't know what type: %v", t&0x0f)) -} - -// Given a TType value, find the appropriate TCompactProtocol.Types constant. -func (p *TCompactProtocol) getCompactType(t TType) tCompactType { - return ttypeToCompactType[t] -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/context.go b/vendor/github.com/apache/thrift/lib/go/thrift/context.go deleted file mode 100644 index d15c1bcf8..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/context.go +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import "context" - -var defaultCtx = context.Background() diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/debug_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/debug_protocol.go deleted file mode 100644 index 57943e0f3..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/debug_protocol.go +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "log" -) - -type TDebugProtocol struct { - Delegate TProtocol - LogPrefix string -} - -type TDebugProtocolFactory struct { - Underlying TProtocolFactory - LogPrefix string -} - -func NewTDebugProtocolFactory(underlying TProtocolFactory, logPrefix string) *TDebugProtocolFactory { - return &TDebugProtocolFactory{ - Underlying: underlying, - LogPrefix: logPrefix, - } -} - -func (t *TDebugProtocolFactory) GetProtocol(trans TTransport) TProtocol { - return &TDebugProtocol{ - Delegate: t.Underlying.GetProtocol(trans), - LogPrefix: t.LogPrefix, - } -} - -func (tdp *TDebugProtocol) WriteMessageBegin(name string, typeId TMessageType, seqid int32) error { - err := tdp.Delegate.WriteMessageBegin(name, typeId, seqid) - log.Printf("%sWriteMessageBegin(name=%#v, typeId=%#v, seqid=%#v) => %#v", tdp.LogPrefix, name, typeId, seqid, err) - return err -} -func (tdp *TDebugProtocol) WriteMessageEnd() error { - err := tdp.Delegate.WriteMessageEnd() - log.Printf("%sWriteMessageEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteStructBegin(name string) error { - err := tdp.Delegate.WriteStructBegin(name) - log.Printf("%sWriteStructBegin(name=%#v) => %#v", tdp.LogPrefix, name, err) - return err -} -func (tdp *TDebugProtocol) WriteStructEnd() error { - err := tdp.Delegate.WriteStructEnd() - log.Printf("%sWriteStructEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteFieldBegin(name string, typeId TType, id int16) error { - err := tdp.Delegate.WriteFieldBegin(name, typeId, id) - log.Printf("%sWriteFieldBegin(name=%#v, typeId=%#v, id%#v) => %#v", tdp.LogPrefix, name, typeId, id, err) - return err -} -func (tdp *TDebugProtocol) WriteFieldEnd() error { - err := tdp.Delegate.WriteFieldEnd() - log.Printf("%sWriteFieldEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteFieldStop() error { - err := tdp.Delegate.WriteFieldStop() - log.Printf("%sWriteFieldStop() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteMapBegin(keyType TType, valueType TType, size int) error { - err := tdp.Delegate.WriteMapBegin(keyType, valueType, size) - log.Printf("%sWriteMapBegin(keyType=%#v, valueType=%#v, size=%#v) => %#v", tdp.LogPrefix, keyType, valueType, size, err) - return err -} -func (tdp *TDebugProtocol) WriteMapEnd() error { - err := tdp.Delegate.WriteMapEnd() - log.Printf("%sWriteMapEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteListBegin(elemType TType, size int) error { - err := tdp.Delegate.WriteListBegin(elemType, size) - log.Printf("%sWriteListBegin(elemType=%#v, size=%#v) => %#v", tdp.LogPrefix, elemType, size, err) - return err -} -func (tdp *TDebugProtocol) WriteListEnd() error { - err := tdp.Delegate.WriteListEnd() - log.Printf("%sWriteListEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteSetBegin(elemType TType, size int) error { - err := tdp.Delegate.WriteSetBegin(elemType, size) - log.Printf("%sWriteSetBegin(elemType=%#v, size=%#v) => %#v", tdp.LogPrefix, elemType, size, err) - return err -} -func (tdp *TDebugProtocol) WriteSetEnd() error { - err := tdp.Delegate.WriteSetEnd() - log.Printf("%sWriteSetEnd() => %#v", tdp.LogPrefix, err) - return err -} -func (tdp *TDebugProtocol) WriteBool(value bool) error { - err := tdp.Delegate.WriteBool(value) - log.Printf("%sWriteBool(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteByte(value int8) error { - err := tdp.Delegate.WriteByte(value) - log.Printf("%sWriteByte(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteI16(value int16) error { - err := tdp.Delegate.WriteI16(value) - log.Printf("%sWriteI16(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteI32(value int32) error { - err := tdp.Delegate.WriteI32(value) - log.Printf("%sWriteI32(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteI64(value int64) error { - err := tdp.Delegate.WriteI64(value) - log.Printf("%sWriteI64(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteDouble(value float64) error { - err := tdp.Delegate.WriteDouble(value) - log.Printf("%sWriteDouble(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteString(value string) error { - err := tdp.Delegate.WriteString(value) - log.Printf("%sWriteString(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} -func (tdp *TDebugProtocol) WriteBinary(value []byte) error { - err := tdp.Delegate.WriteBinary(value) - log.Printf("%sWriteBinary(value=%#v) => %#v", tdp.LogPrefix, value, err) - return err -} - -func (tdp *TDebugProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqid int32, err error) { - name, typeId, seqid, err = tdp.Delegate.ReadMessageBegin() - log.Printf("%sReadMessageBegin() (name=%#v, typeId=%#v, seqid=%#v, err=%#v)", tdp.LogPrefix, name, typeId, seqid, err) - return -} -func (tdp *TDebugProtocol) ReadMessageEnd() (err error) { - err = tdp.Delegate.ReadMessageEnd() - log.Printf("%sReadMessageEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadStructBegin() (name string, err error) { - name, err = tdp.Delegate.ReadStructBegin() - log.Printf("%sReadStructBegin() (name%#v, err=%#v)", tdp.LogPrefix, name, err) - return -} -func (tdp *TDebugProtocol) ReadStructEnd() (err error) { - err = tdp.Delegate.ReadStructEnd() - log.Printf("%sReadStructEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadFieldBegin() (name string, typeId TType, id int16, err error) { - name, typeId, id, err = tdp.Delegate.ReadFieldBegin() - log.Printf("%sReadFieldBegin() (name=%#v, typeId=%#v, id=%#v, err=%#v)", tdp.LogPrefix, name, typeId, id, err) - return -} -func (tdp *TDebugProtocol) ReadFieldEnd() (err error) { - err = tdp.Delegate.ReadFieldEnd() - log.Printf("%sReadFieldEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadMapBegin() (keyType TType, valueType TType, size int, err error) { - keyType, valueType, size, err = tdp.Delegate.ReadMapBegin() - log.Printf("%sReadMapBegin() (keyType=%#v, valueType=%#v, size=%#v, err=%#v)", tdp.LogPrefix, keyType, valueType, size, err) - return -} -func (tdp *TDebugProtocol) ReadMapEnd() (err error) { - err = tdp.Delegate.ReadMapEnd() - log.Printf("%sReadMapEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadListBegin() (elemType TType, size int, err error) { - elemType, size, err = tdp.Delegate.ReadListBegin() - log.Printf("%sReadListBegin() (elemType=%#v, size=%#v, err=%#v)", tdp.LogPrefix, elemType, size, err) - return -} -func (tdp *TDebugProtocol) ReadListEnd() (err error) { - err = tdp.Delegate.ReadListEnd() - log.Printf("%sReadListEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadSetBegin() (elemType TType, size int, err error) { - elemType, size, err = tdp.Delegate.ReadSetBegin() - log.Printf("%sReadSetBegin() (elemType=%#v, size=%#v, err=%#v)", tdp.LogPrefix, elemType, size, err) - return -} -func (tdp *TDebugProtocol) ReadSetEnd() (err error) { - err = tdp.Delegate.ReadSetEnd() - log.Printf("%sReadSetEnd() err=%#v", tdp.LogPrefix, err) - return -} -func (tdp *TDebugProtocol) ReadBool() (value bool, err error) { - value, err = tdp.Delegate.ReadBool() - log.Printf("%sReadBool() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadByte() (value int8, err error) { - value, err = tdp.Delegate.ReadByte() - log.Printf("%sReadByte() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadI16() (value int16, err error) { - value, err = tdp.Delegate.ReadI16() - log.Printf("%sReadI16() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadI32() (value int32, err error) { - value, err = tdp.Delegate.ReadI32() - log.Printf("%sReadI32() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadI64() (value int64, err error) { - value, err = tdp.Delegate.ReadI64() - log.Printf("%sReadI64() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadDouble() (value float64, err error) { - value, err = tdp.Delegate.ReadDouble() - log.Printf("%sReadDouble() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadString() (value string, err error) { - value, err = tdp.Delegate.ReadString() - log.Printf("%sReadString() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) ReadBinary() (value []byte, err error) { - value, err = tdp.Delegate.ReadBinary() - log.Printf("%sReadBinary() (value=%#v, err=%#v)", tdp.LogPrefix, value, err) - return -} -func (tdp *TDebugProtocol) Skip(fieldType TType) (err error) { - err = tdp.Delegate.Skip(fieldType) - log.Printf("%sSkip(fieldType=%#v) (err=%#v)", tdp.LogPrefix, fieldType, err) - return -} -func (tdp *TDebugProtocol) Flush(ctx context.Context) (err error) { - err = tdp.Delegate.Flush(ctx) - log.Printf("%sFlush() (err=%#v)", tdp.LogPrefix, err) - return -} - -func (tdp *TDebugProtocol) Transport() TTransport { - return tdp.Delegate.Transport() -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/deserializer.go b/vendor/github.com/apache/thrift/lib/go/thrift/deserializer.go deleted file mode 100644 index 91a0983a4..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/deserializer.go +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -type TDeserializer struct { - Transport TTransport - Protocol TProtocol -} - -func NewTDeserializer() *TDeserializer { - var transport TTransport - transport = NewTMemoryBufferLen(1024) - - protocol := NewTBinaryProtocolFactoryDefault().GetProtocol(transport) - - return &TDeserializer{ - transport, - protocol} -} - -func (t *TDeserializer) ReadString(msg TStruct, s string) (err error) { - err = nil - if _, err = t.Transport.Write([]byte(s)); err != nil { - return - } - if err = msg.Read(t.Protocol); err != nil { - return - } - return -} - -func (t *TDeserializer) Read(msg TStruct, b []byte) (err error) { - err = nil - if _, err = t.Transport.Write(b); err != nil { - return - } - if err = msg.Read(t.Protocol); err != nil { - return - } - return -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/exception.go b/vendor/github.com/apache/thrift/lib/go/thrift/exception.go deleted file mode 100644 index ea8d6f661..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/exception.go +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "errors" -) - -// Generic Thrift exception -type TException interface { - error -} - -// Prepends additional information to an error without losing the Thrift exception interface -func PrependError(prepend string, err error) error { - if t, ok := err.(TTransportException); ok { - return NewTTransportException(t.TypeId(), prepend+t.Error()) - } - if t, ok := err.(TProtocolException); ok { - return NewTProtocolExceptionWithType(t.TypeId(), errors.New(prepend+err.Error())) - } - if t, ok := err.(TApplicationException); ok { - return NewTApplicationException(t.TypeId(), prepend+t.Error()) - } - - return errors.New(prepend + err.Error()) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/field.go b/vendor/github.com/apache/thrift/lib/go/thrift/field.go deleted file mode 100644 index 9d6652550..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/field.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Helper class that encapsulates field metadata. -type field struct { - name string - typeId TType - id int -} - -func newField(n string, t TType, i int) *field { - return &field{name: n, typeId: t, id: i} -} - -func (p *field) Name() string { - if p == nil { - return "" - } - return p.name -} - -func (p *field) TypeId() TType { - if p == nil { - return TType(VOID) - } - return p.typeId -} - -func (p *field) Id() int { - if p == nil { - return -1 - } - return p.id -} - -func (p *field) String() string { - if p == nil { - return "" - } - return "" -} - -var ANONYMOUS_FIELD *field - -type fieldSlice []field - -func (p fieldSlice) Len() int { - return len(p) -} - -func (p fieldSlice) Less(i, j int) bool { - return p[i].Id() < p[j].Id() -} - -func (p fieldSlice) Swap(i, j int) { - p[i], p[j] = p[j], p[i] -} - -func init() { - ANONYMOUS_FIELD = newField("", STOP, 0) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/framed_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/framed_transport.go deleted file mode 100644 index 81fa65aaa..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/framed_transport.go +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bufio" - "bytes" - "context" - "encoding/binary" - "fmt" - "io" -) - -const DEFAULT_MAX_LENGTH = 16384000 - -type TFramedTransport struct { - transport TTransport - buf bytes.Buffer - reader *bufio.Reader - frameSize uint32 //Current remaining size of the frame. if ==0 read next frame header - buffer [4]byte - maxLength uint32 -} - -type tFramedTransportFactory struct { - factory TTransportFactory - maxLength uint32 -} - -func NewTFramedTransportFactory(factory TTransportFactory) TTransportFactory { - return &tFramedTransportFactory{factory: factory, maxLength: DEFAULT_MAX_LENGTH} -} - -func NewTFramedTransportFactoryMaxLength(factory TTransportFactory, maxLength uint32) TTransportFactory { - return &tFramedTransportFactory{factory: factory, maxLength: maxLength} -} - -func (p *tFramedTransportFactory) GetTransport(base TTransport) (TTransport, error) { - tt, err := p.factory.GetTransport(base) - if err != nil { - return nil, err - } - return NewTFramedTransportMaxLength(tt, p.maxLength), nil -} - -func NewTFramedTransport(transport TTransport) *TFramedTransport { - return &TFramedTransport{transport: transport, reader: bufio.NewReader(transport), maxLength: DEFAULT_MAX_LENGTH} -} - -func NewTFramedTransportMaxLength(transport TTransport, maxLength uint32) *TFramedTransport { - return &TFramedTransport{transport: transport, reader: bufio.NewReader(transport), maxLength: maxLength} -} - -func (p *TFramedTransport) Open() error { - return p.transport.Open() -} - -func (p *TFramedTransport) IsOpen() bool { - return p.transport.IsOpen() -} - -func (p *TFramedTransport) Close() error { - return p.transport.Close() -} - -func (p *TFramedTransport) Read(buf []byte) (l int, err error) { - if p.frameSize == 0 { - p.frameSize, err = p.readFrameHeader() - if err != nil { - return - } - } - if p.frameSize < uint32(len(buf)) { - frameSize := p.frameSize - tmp := make([]byte, p.frameSize) - l, err = p.Read(tmp) - copy(buf, tmp) - if err == nil { - err = NewTTransportExceptionFromError(fmt.Errorf("Not enough frame size %d to read %d bytes", frameSize, len(buf))) - return - } - } - got, err := p.reader.Read(buf) - p.frameSize = p.frameSize - uint32(got) - //sanity check - if p.frameSize < 0 { - return 0, NewTTransportException(UNKNOWN_TRANSPORT_EXCEPTION, "Negative frame size") - } - return got, NewTTransportExceptionFromError(err) -} - -func (p *TFramedTransport) ReadByte() (c byte, err error) { - if p.frameSize == 0 { - p.frameSize, err = p.readFrameHeader() - if err != nil { - return - } - } - if p.frameSize < 1 { - return 0, NewTTransportExceptionFromError(fmt.Errorf("Not enough frame size %d to read %d bytes", p.frameSize, 1)) - } - c, err = p.reader.ReadByte() - if err == nil { - p.frameSize-- - } - return -} - -func (p *TFramedTransport) Write(buf []byte) (int, error) { - n, err := p.buf.Write(buf) - return n, NewTTransportExceptionFromError(err) -} - -func (p *TFramedTransport) WriteByte(c byte) error { - return p.buf.WriteByte(c) -} - -func (p *TFramedTransport) WriteString(s string) (n int, err error) { - return p.buf.WriteString(s) -} - -func (p *TFramedTransport) Flush(ctx context.Context) error { - size := p.buf.Len() - buf := p.buffer[:4] - binary.BigEndian.PutUint32(buf, uint32(size)) - _, err := p.transport.Write(buf) - if err != nil { - p.buf.Truncate(0) - return NewTTransportExceptionFromError(err) - } - if size > 0 { - if n, err := p.buf.WriteTo(p.transport); err != nil { - print("Error while flushing write buffer of size ", size, " to transport, only wrote ", n, " bytes: ", err.Error(), "\n") - p.buf.Truncate(0) - return NewTTransportExceptionFromError(err) - } - } - err = p.transport.Flush(ctx) - return NewTTransportExceptionFromError(err) -} - -func (p *TFramedTransport) readFrameHeader() (uint32, error) { - buf := p.buffer[:4] - if _, err := io.ReadFull(p.reader, buf); err != nil { - return 0, err - } - size := binary.BigEndian.Uint32(buf) - if size < 0 || size > p.maxLength { - return 0, NewTTransportException(UNKNOWN_TRANSPORT_EXCEPTION, fmt.Sprintf("Incorrect frame size (%d)", size)) - } - return size, nil -} - -func (p *TFramedTransport) RemainingBytes() (num_bytes uint64) { - return uint64(p.frameSize) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/http_client.go b/vendor/github.com/apache/thrift/lib/go/thrift/http_client.go deleted file mode 100644 index 5c82bf538..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/http_client.go +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bytes" - "context" - "io" - "io/ioutil" - "net/http" - "net/url" - "strconv" -) - -// Default to using the shared http client. Library users are -// free to change this global client or specify one through -// THttpClientOptions. -var DefaultHttpClient *http.Client = http.DefaultClient - -type THttpClient struct { - client *http.Client - response *http.Response - url *url.URL - requestBuffer *bytes.Buffer - header http.Header - nsecConnectTimeout int64 - nsecReadTimeout int64 -} - -type THttpClientTransportFactory struct { - options THttpClientOptions - url string -} - -func (p *THttpClientTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - if trans != nil { - t, ok := trans.(*THttpClient) - if ok && t.url != nil { - return NewTHttpClientWithOptions(t.url.String(), p.options) - } - } - return NewTHttpClientWithOptions(p.url, p.options) -} - -type THttpClientOptions struct { - // If nil, DefaultHttpClient is used - Client *http.Client -} - -func NewTHttpClientTransportFactory(url string) *THttpClientTransportFactory { - return NewTHttpClientTransportFactoryWithOptions(url, THttpClientOptions{}) -} - -func NewTHttpClientTransportFactoryWithOptions(url string, options THttpClientOptions) *THttpClientTransportFactory { - return &THttpClientTransportFactory{url: url, options: options} -} - -func NewTHttpClientWithOptions(urlstr string, options THttpClientOptions) (TTransport, error) { - parsedURL, err := url.Parse(urlstr) - if err != nil { - return nil, err - } - buf := make([]byte, 0, 1024) - client := options.Client - if client == nil { - client = DefaultHttpClient - } - httpHeader := map[string][]string{"Content-Type": {"application/x-thrift"}} - return &THttpClient{client: client, url: parsedURL, requestBuffer: bytes.NewBuffer(buf), header: httpHeader}, nil -} - -func NewTHttpClient(urlstr string) (TTransport, error) { - return NewTHttpClientWithOptions(urlstr, THttpClientOptions{}) -} - -// Set the HTTP Header for this specific Thrift Transport -// It is important that you first assert the TTransport as a THttpClient type -// like so: -// -// httpTrans := trans.(THttpClient) -// httpTrans.SetHeader("User-Agent","Thrift Client 1.0") -func (p *THttpClient) SetHeader(key string, value string) { - p.header.Add(key, value) -} - -// Get the HTTP Header represented by the supplied Header Key for this specific Thrift Transport -// It is important that you first assert the TTransport as a THttpClient type -// like so: -// -// httpTrans := trans.(THttpClient) -// hdrValue := httpTrans.GetHeader("User-Agent") -func (p *THttpClient) GetHeader(key string) string { - return p.header.Get(key) -} - -// Deletes the HTTP Header given a Header Key for this specific Thrift Transport -// It is important that you first assert the TTransport as a THttpClient type -// like so: -// -// httpTrans := trans.(THttpClient) -// httpTrans.DelHeader("User-Agent") -func (p *THttpClient) DelHeader(key string) { - p.header.Del(key) -} - -func (p *THttpClient) Open() error { - // do nothing - return nil -} - -func (p *THttpClient) IsOpen() bool { - return p.response != nil || p.requestBuffer != nil -} - -func (p *THttpClient) closeResponse() error { - var err error - if p.response != nil && p.response.Body != nil { - // The docs specify that if keepalive is enabled and the response body is not - // read to completion the connection will never be returned to the pool and - // reused. Errors are being ignored here because if the connection is invalid - // and this fails for some reason, the Close() method will do any remaining - // cleanup. - io.Copy(ioutil.Discard, p.response.Body) - - err = p.response.Body.Close() - } - - p.response = nil - return err -} - -func (p *THttpClient) Close() error { - if p.requestBuffer != nil { - p.requestBuffer.Reset() - p.requestBuffer = nil - } - return p.closeResponse() -} - -func (p *THttpClient) Read(buf []byte) (int, error) { - if p.response == nil { - return 0, NewTTransportException(NOT_OPEN, "Response buffer is empty, no request.") - } - n, err := p.response.Body.Read(buf) - if n > 0 && (err == nil || err == io.EOF) { - return n, nil - } - return n, NewTTransportExceptionFromError(err) -} - -func (p *THttpClient) ReadByte() (c byte, err error) { - return readByte(p.response.Body) -} - -func (p *THttpClient) Write(buf []byte) (int, error) { - n, err := p.requestBuffer.Write(buf) - return n, err -} - -func (p *THttpClient) WriteByte(c byte) error { - return p.requestBuffer.WriteByte(c) -} - -func (p *THttpClient) WriteString(s string) (n int, err error) { - return p.requestBuffer.WriteString(s) -} - -func (p *THttpClient) Flush(ctx context.Context) error { - // Close any previous response body to avoid leaking connections. - p.closeResponse() - - req, err := http.NewRequest("POST", p.url.String(), p.requestBuffer) - if err != nil { - return NewTTransportExceptionFromError(err) - } - req.Header = p.header - if ctx != nil { - req = req.WithContext(ctx) - } - response, err := p.client.Do(req) - if err != nil { - return NewTTransportExceptionFromError(err) - } - if response.StatusCode != http.StatusOK { - // Close the response to avoid leaking file descriptors. closeResponse does - // more than just call Close(), so temporarily assign it and reuse the logic. - p.response = response - p.closeResponse() - - // TODO(pomack) log bad response - return NewTTransportException(UNKNOWN_TRANSPORT_EXCEPTION, "HTTP Response code: "+strconv.Itoa(response.StatusCode)) - } - p.response = response - return nil -} - -func (p *THttpClient) RemainingBytes() (num_bytes uint64) { - len := p.response.ContentLength - if len >= 0 { - return uint64(len) - } - - const maxSize = ^uint64(0) - return maxSize // the thruth is, we just don't know unless framed is used -} - -// Deprecated: Use NewTHttpClientTransportFactory instead. -func NewTHttpPostClientTransportFactory(url string) *THttpClientTransportFactory { - return NewTHttpClientTransportFactoryWithOptions(url, THttpClientOptions{}) -} - -// Deprecated: Use NewTHttpClientTransportFactoryWithOptions instead. -func NewTHttpPostClientTransportFactoryWithOptions(url string, options THttpClientOptions) *THttpClientTransportFactory { - return NewTHttpClientTransportFactoryWithOptions(url, options) -} - -// Deprecated: Use NewTHttpClientWithOptions instead. -func NewTHttpPostClientWithOptions(urlstr string, options THttpClientOptions) (TTransport, error) { - return NewTHttpClientWithOptions(urlstr, options) -} - -// Deprecated: Use NewTHttpClient instead. -func NewTHttpPostClient(urlstr string) (TTransport, error) { - return NewTHttpClientWithOptions(urlstr, THttpClientOptions{}) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/http_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/http_transport.go deleted file mode 100644 index 66f0f388a..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/http_transport.go +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "compress/gzip" - "io" - "net/http" - "strings" -) - -// NewThriftHandlerFunc is a function that create a ready to use Apache Thrift Handler function -func NewThriftHandlerFunc(processor TProcessor, - inPfactory, outPfactory TProtocolFactory) func(w http.ResponseWriter, r *http.Request) { - - return gz(func(w http.ResponseWriter, r *http.Request) { - w.Header().Add("Content-Type", "application/x-thrift") - - transport := NewStreamTransport(r.Body, w) - processor.Process(r.Context(), inPfactory.GetProtocol(transport), outPfactory.GetProtocol(transport)) - }) -} - -// gz transparently compresses the HTTP response if the client supports it. -func gz(handler http.HandlerFunc) http.HandlerFunc { - return func(w http.ResponseWriter, r *http.Request) { - if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") { - handler(w, r) - return - } - w.Header().Set("Content-Encoding", "gzip") - gz := gzip.NewWriter(w) - defer gz.Close() - gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w} - handler(gzw, r) - } -} - -type gzipResponseWriter struct { - io.Writer - http.ResponseWriter -} - -func (w gzipResponseWriter) Write(b []byte) (int, error) { - return w.Writer.Write(b) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/iostream_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/iostream_transport.go deleted file mode 100644 index fea93bcef..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/iostream_transport.go +++ /dev/null @@ -1,214 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bufio" - "context" - "io" -) - -// StreamTransport is a Transport made of an io.Reader and/or an io.Writer -type StreamTransport struct { - io.Reader - io.Writer - isReadWriter bool - closed bool -} - -type StreamTransportFactory struct { - Reader io.Reader - Writer io.Writer - isReadWriter bool -} - -func (p *StreamTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - if trans != nil { - t, ok := trans.(*StreamTransport) - if ok { - if t.isReadWriter { - return NewStreamTransportRW(t.Reader.(io.ReadWriter)), nil - } - if t.Reader != nil && t.Writer != nil { - return NewStreamTransport(t.Reader, t.Writer), nil - } - if t.Reader != nil && t.Writer == nil { - return NewStreamTransportR(t.Reader), nil - } - if t.Reader == nil && t.Writer != nil { - return NewStreamTransportW(t.Writer), nil - } - return &StreamTransport{}, nil - } - } - if p.isReadWriter { - return NewStreamTransportRW(p.Reader.(io.ReadWriter)), nil - } - if p.Reader != nil && p.Writer != nil { - return NewStreamTransport(p.Reader, p.Writer), nil - } - if p.Reader != nil && p.Writer == nil { - return NewStreamTransportR(p.Reader), nil - } - if p.Reader == nil && p.Writer != nil { - return NewStreamTransportW(p.Writer), nil - } - return &StreamTransport{}, nil -} - -func NewStreamTransportFactory(reader io.Reader, writer io.Writer, isReadWriter bool) *StreamTransportFactory { - return &StreamTransportFactory{Reader: reader, Writer: writer, isReadWriter: isReadWriter} -} - -func NewStreamTransport(r io.Reader, w io.Writer) *StreamTransport { - return &StreamTransport{Reader: bufio.NewReader(r), Writer: bufio.NewWriter(w)} -} - -func NewStreamTransportR(r io.Reader) *StreamTransport { - return &StreamTransport{Reader: bufio.NewReader(r)} -} - -func NewStreamTransportW(w io.Writer) *StreamTransport { - return &StreamTransport{Writer: bufio.NewWriter(w)} -} - -func NewStreamTransportRW(rw io.ReadWriter) *StreamTransport { - bufrw := bufio.NewReadWriter(bufio.NewReader(rw), bufio.NewWriter(rw)) - return &StreamTransport{Reader: bufrw, Writer: bufrw, isReadWriter: true} -} - -func (p *StreamTransport) IsOpen() bool { - return !p.closed -} - -// implicitly opened on creation, can't be reopened once closed -func (p *StreamTransport) Open() error { - if !p.closed { - return NewTTransportException(ALREADY_OPEN, "StreamTransport already open.") - } else { - return NewTTransportException(NOT_OPEN, "cannot reopen StreamTransport.") - } -} - -// Closes both the input and output streams. -func (p *StreamTransport) Close() error { - if p.closed { - return NewTTransportException(NOT_OPEN, "StreamTransport already closed.") - } - p.closed = true - closedReader := false - if p.Reader != nil { - c, ok := p.Reader.(io.Closer) - if ok { - e := c.Close() - closedReader = true - if e != nil { - return e - } - } - p.Reader = nil - } - if p.Writer != nil && (!closedReader || !p.isReadWriter) { - c, ok := p.Writer.(io.Closer) - if ok { - e := c.Close() - if e != nil { - return e - } - } - p.Writer = nil - } - return nil -} - -// Flushes the underlying output stream if not null. -func (p *StreamTransport) Flush(ctx context.Context) error { - if p.Writer == nil { - return NewTTransportException(NOT_OPEN, "Cannot flush null outputStream") - } - f, ok := p.Writer.(Flusher) - if ok { - err := f.Flush() - if err != nil { - return NewTTransportExceptionFromError(err) - } - } - return nil -} - -func (p *StreamTransport) Read(c []byte) (n int, err error) { - n, err = p.Reader.Read(c) - if err != nil { - err = NewTTransportExceptionFromError(err) - } - return -} - -func (p *StreamTransport) ReadByte() (c byte, err error) { - f, ok := p.Reader.(io.ByteReader) - if ok { - c, err = f.ReadByte() - } else { - c, err = readByte(p.Reader) - } - if err != nil { - err = NewTTransportExceptionFromError(err) - } - return -} - -func (p *StreamTransport) Write(c []byte) (n int, err error) { - n, err = p.Writer.Write(c) - if err != nil { - err = NewTTransportExceptionFromError(err) - } - return -} - -func (p *StreamTransport) WriteByte(c byte) (err error) { - f, ok := p.Writer.(io.ByteWriter) - if ok { - err = f.WriteByte(c) - } else { - err = writeByte(p.Writer, c) - } - if err != nil { - err = NewTTransportExceptionFromError(err) - } - return -} - -func (p *StreamTransport) WriteString(s string) (n int, err error) { - f, ok := p.Writer.(stringWriter) - if ok { - n, err = f.WriteString(s) - } else { - n, err = p.Writer.Write([]byte(s)) - } - if err != nil { - err = NewTTransportExceptionFromError(err) - } - return -} - -func (p *StreamTransport) RemainingBytes() (num_bytes uint64) { - const maxSize = ^uint64(0) - return maxSize // the thruth is, we just don't know unless framed is used -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/json_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/json_protocol.go deleted file mode 100644 index 7be685d43..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/json_protocol.go +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "encoding/base64" - "fmt" -) - -const ( - THRIFT_JSON_PROTOCOL_VERSION = 1 -) - -// for references to _ParseContext see tsimplejson_protocol.go - -// JSON protocol implementation for thrift. -// -// This protocol produces/consumes a simple output format -// suitable for parsing by scripting languages. It should not be -// confused with the full-featured TJSONProtocol. -// -type TJSONProtocol struct { - *TSimpleJSONProtocol -} - -// Constructor -func NewTJSONProtocol(t TTransport) *TJSONProtocol { - v := &TJSONProtocol{TSimpleJSONProtocol: NewTSimpleJSONProtocol(t)} - v.parseContextStack = append(v.parseContextStack, int(_CONTEXT_IN_TOPLEVEL)) - v.dumpContext = append(v.dumpContext, int(_CONTEXT_IN_TOPLEVEL)) - return v -} - -// Factory -type TJSONProtocolFactory struct{} - -func (p *TJSONProtocolFactory) GetProtocol(trans TTransport) TProtocol { - return NewTJSONProtocol(trans) -} - -func NewTJSONProtocolFactory() *TJSONProtocolFactory { - return &TJSONProtocolFactory{} -} - -func (p *TJSONProtocol) WriteMessageBegin(name string, typeId TMessageType, seqId int32) error { - p.resetContextStack() // THRIFT-3735 - if e := p.OutputListBegin(); e != nil { - return e - } - if e := p.WriteI32(THRIFT_JSON_PROTOCOL_VERSION); e != nil { - return e - } - if e := p.WriteString(name); e != nil { - return e - } - if e := p.WriteByte(int8(typeId)); e != nil { - return e - } - if e := p.WriteI32(seqId); e != nil { - return e - } - return nil -} - -func (p *TJSONProtocol) WriteMessageEnd() error { - return p.OutputListEnd() -} - -func (p *TJSONProtocol) WriteStructBegin(name string) error { - if e := p.OutputObjectBegin(); e != nil { - return e - } - return nil -} - -func (p *TJSONProtocol) WriteStructEnd() error { - return p.OutputObjectEnd() -} - -func (p *TJSONProtocol) WriteFieldBegin(name string, typeId TType, id int16) error { - if e := p.WriteI16(id); e != nil { - return e - } - if e := p.OutputObjectBegin(); e != nil { - return e - } - s, e1 := p.TypeIdToString(typeId) - if e1 != nil { - return e1 - } - if e := p.WriteString(s); e != nil { - return e - } - return nil -} - -func (p *TJSONProtocol) WriteFieldEnd() error { - return p.OutputObjectEnd() -} - -func (p *TJSONProtocol) WriteFieldStop() error { return nil } - -func (p *TJSONProtocol) WriteMapBegin(keyType TType, valueType TType, size int) error { - if e := p.OutputListBegin(); e != nil { - return e - } - s, e1 := p.TypeIdToString(keyType) - if e1 != nil { - return e1 - } - if e := p.WriteString(s); e != nil { - return e - } - s, e1 = p.TypeIdToString(valueType) - if e1 != nil { - return e1 - } - if e := p.WriteString(s); e != nil { - return e - } - if e := p.WriteI64(int64(size)); e != nil { - return e - } - return p.OutputObjectBegin() -} - -func (p *TJSONProtocol) WriteMapEnd() error { - if e := p.OutputObjectEnd(); e != nil { - return e - } - return p.OutputListEnd() -} - -func (p *TJSONProtocol) WriteListBegin(elemType TType, size int) error { - return p.OutputElemListBegin(elemType, size) -} - -func (p *TJSONProtocol) WriteListEnd() error { - return p.OutputListEnd() -} - -func (p *TJSONProtocol) WriteSetBegin(elemType TType, size int) error { - return p.OutputElemListBegin(elemType, size) -} - -func (p *TJSONProtocol) WriteSetEnd() error { - return p.OutputListEnd() -} - -func (p *TJSONProtocol) WriteBool(b bool) error { - if b { - return p.WriteI32(1) - } - return p.WriteI32(0) -} - -func (p *TJSONProtocol) WriteByte(b int8) error { - return p.WriteI32(int32(b)) -} - -func (p *TJSONProtocol) WriteI16(v int16) error { - return p.WriteI32(int32(v)) -} - -func (p *TJSONProtocol) WriteI32(v int32) error { - return p.OutputI64(int64(v)) -} - -func (p *TJSONProtocol) WriteI64(v int64) error { - return p.OutputI64(int64(v)) -} - -func (p *TJSONProtocol) WriteDouble(v float64) error { - return p.OutputF64(v) -} - -func (p *TJSONProtocol) WriteString(v string) error { - return p.OutputString(v) -} - -func (p *TJSONProtocol) WriteBinary(v []byte) error { - // JSON library only takes in a string, - // not an arbitrary byte array, to ensure bytes are transmitted - // efficiently we must convert this into a valid JSON string - // therefore we use base64 encoding to avoid excessive escaping/quoting - if e := p.OutputPreValue(); e != nil { - return e - } - if _, e := p.write(JSON_QUOTE_BYTES); e != nil { - return NewTProtocolException(e) - } - writer := base64.NewEncoder(base64.StdEncoding, p.writer) - if _, e := writer.Write(v); e != nil { - p.writer.Reset(p.trans) // THRIFT-3735 - return NewTProtocolException(e) - } - if e := writer.Close(); e != nil { - return NewTProtocolException(e) - } - if _, e := p.write(JSON_QUOTE_BYTES); e != nil { - return NewTProtocolException(e) - } - return p.OutputPostValue() -} - -// Reading methods. -func (p *TJSONProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqId int32, err error) { - p.resetContextStack() // THRIFT-3735 - if isNull, err := p.ParseListBegin(); isNull || err != nil { - return name, typeId, seqId, err - } - version, err := p.ReadI32() - if err != nil { - return name, typeId, seqId, err - } - if version != THRIFT_JSON_PROTOCOL_VERSION { - e := fmt.Errorf("Unknown Protocol version %d, expected version %d", version, THRIFT_JSON_PROTOCOL_VERSION) - return name, typeId, seqId, NewTProtocolExceptionWithType(INVALID_DATA, e) - - } - if name, err = p.ReadString(); err != nil { - return name, typeId, seqId, err - } - bTypeId, err := p.ReadByte() - typeId = TMessageType(bTypeId) - if err != nil { - return name, typeId, seqId, err - } - if seqId, err = p.ReadI32(); err != nil { - return name, typeId, seqId, err - } - return name, typeId, seqId, nil -} - -func (p *TJSONProtocol) ReadMessageEnd() error { - err := p.ParseListEnd() - return err -} - -func (p *TJSONProtocol) ReadStructBegin() (name string, err error) { - _, err = p.ParseObjectStart() - return "", err -} - -func (p *TJSONProtocol) ReadStructEnd() error { - return p.ParseObjectEnd() -} - -func (p *TJSONProtocol) ReadFieldBegin() (string, TType, int16, error) { - b, _ := p.reader.Peek(1) - if len(b) < 1 || b[0] == JSON_RBRACE[0] || b[0] == JSON_RBRACKET[0] { - return "", STOP, -1, nil - } - fieldId, err := p.ReadI16() - if err != nil { - return "", STOP, fieldId, err - } - if _, err = p.ParseObjectStart(); err != nil { - return "", STOP, fieldId, err - } - sType, err := p.ReadString() - if err != nil { - return "", STOP, fieldId, err - } - fType, err := p.StringToTypeId(sType) - return "", fType, fieldId, err -} - -func (p *TJSONProtocol) ReadFieldEnd() error { - return p.ParseObjectEnd() -} - -func (p *TJSONProtocol) ReadMapBegin() (keyType TType, valueType TType, size int, e error) { - if isNull, e := p.ParseListBegin(); isNull || e != nil { - return VOID, VOID, 0, e - } - - // read keyType - sKeyType, e := p.ReadString() - if e != nil { - return keyType, valueType, size, e - } - keyType, e = p.StringToTypeId(sKeyType) - if e != nil { - return keyType, valueType, size, e - } - - // read valueType - sValueType, e := p.ReadString() - if e != nil { - return keyType, valueType, size, e - } - valueType, e = p.StringToTypeId(sValueType) - if e != nil { - return keyType, valueType, size, e - } - - // read size - iSize, e := p.ReadI64() - if e != nil { - return keyType, valueType, size, e - } - size = int(iSize) - - _, e = p.ParseObjectStart() - return keyType, valueType, size, e -} - -func (p *TJSONProtocol) ReadMapEnd() error { - e := p.ParseObjectEnd() - if e != nil { - return e - } - return p.ParseListEnd() -} - -func (p *TJSONProtocol) ReadListBegin() (elemType TType, size int, e error) { - return p.ParseElemListBegin() -} - -func (p *TJSONProtocol) ReadListEnd() error { - return p.ParseListEnd() -} - -func (p *TJSONProtocol) ReadSetBegin() (elemType TType, size int, e error) { - return p.ParseElemListBegin() -} - -func (p *TJSONProtocol) ReadSetEnd() error { - return p.ParseListEnd() -} - -func (p *TJSONProtocol) ReadBool() (bool, error) { - value, err := p.ReadI32() - return (value != 0), err -} - -func (p *TJSONProtocol) ReadByte() (int8, error) { - v, err := p.ReadI64() - return int8(v), err -} - -func (p *TJSONProtocol) ReadI16() (int16, error) { - v, err := p.ReadI64() - return int16(v), err -} - -func (p *TJSONProtocol) ReadI32() (int32, error) { - v, err := p.ReadI64() - return int32(v), err -} - -func (p *TJSONProtocol) ReadI64() (int64, error) { - v, _, err := p.ParseI64() - return v, err -} - -func (p *TJSONProtocol) ReadDouble() (float64, error) { - v, _, err := p.ParseF64() - return v, err -} - -func (p *TJSONProtocol) ReadString() (string, error) { - var v string - if err := p.ParsePreValue(); err != nil { - return v, err - } - f, _ := p.reader.Peek(1) - if len(f) > 0 && f[0] == JSON_QUOTE { - p.reader.ReadByte() - value, err := p.ParseStringBody() - v = value - if err != nil { - return v, err - } - } else if len(f) > 0 && f[0] == JSON_NULL[0] { - b := make([]byte, len(JSON_NULL)) - _, err := p.reader.Read(b) - if err != nil { - return v, NewTProtocolException(err) - } - if string(b) != string(JSON_NULL) { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(b)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } else { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(f)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return v, p.ParsePostValue() -} - -func (p *TJSONProtocol) ReadBinary() ([]byte, error) { - var v []byte - if err := p.ParsePreValue(); err != nil { - return nil, err - } - f, _ := p.reader.Peek(1) - if len(f) > 0 && f[0] == JSON_QUOTE { - p.reader.ReadByte() - value, err := p.ParseBase64EncodedBody() - v = value - if err != nil { - return v, err - } - } else if len(f) > 0 && f[0] == JSON_NULL[0] { - b := make([]byte, len(JSON_NULL)) - _, err := p.reader.Read(b) - if err != nil { - return v, NewTProtocolException(err) - } - if string(b) != string(JSON_NULL) { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(b)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } else { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(f)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - - return v, p.ParsePostValue() -} - -func (p *TJSONProtocol) Flush(ctx context.Context) (err error) { - err = p.writer.Flush() - if err == nil { - err = p.trans.Flush(ctx) - } - return NewTProtocolException(err) -} - -func (p *TJSONProtocol) Skip(fieldType TType) (err error) { - return SkipDefaultDepth(p, fieldType) -} - -func (p *TJSONProtocol) Transport() TTransport { - return p.trans -} - -func (p *TJSONProtocol) OutputElemListBegin(elemType TType, size int) error { - if e := p.OutputListBegin(); e != nil { - return e - } - s, e1 := p.TypeIdToString(elemType) - if e1 != nil { - return e1 - } - if e := p.WriteString(s); e != nil { - return e - } - if e := p.WriteI64(int64(size)); e != nil { - return e - } - return nil -} - -func (p *TJSONProtocol) ParseElemListBegin() (elemType TType, size int, e error) { - if isNull, e := p.ParseListBegin(); isNull || e != nil { - return VOID, 0, e - } - sElemType, err := p.ReadString() - if err != nil { - return VOID, size, err - } - elemType, err = p.StringToTypeId(sElemType) - if err != nil { - return elemType, size, err - } - nSize, err2 := p.ReadI64() - size = int(nSize) - return elemType, size, err2 -} - -func (p *TJSONProtocol) readElemListBegin() (elemType TType, size int, e error) { - if isNull, e := p.ParseListBegin(); isNull || e != nil { - return VOID, 0, e - } - sElemType, err := p.ReadString() - if err != nil { - return VOID, size, err - } - elemType, err = p.StringToTypeId(sElemType) - if err != nil { - return elemType, size, err - } - nSize, err2 := p.ReadI64() - size = int(nSize) - return elemType, size, err2 -} - -func (p *TJSONProtocol) writeElemListBegin(elemType TType, size int) error { - if e := p.OutputListBegin(); e != nil { - return e - } - s, e1 := p.TypeIdToString(elemType) - if e1 != nil { - return e1 - } - if e := p.OutputString(s); e != nil { - return e - } - if e := p.OutputI64(int64(size)); e != nil { - return e - } - return nil -} - -func (p *TJSONProtocol) TypeIdToString(fieldType TType) (string, error) { - switch byte(fieldType) { - case BOOL: - return "tf", nil - case BYTE: - return "i8", nil - case I16: - return "i16", nil - case I32: - return "i32", nil - case I64: - return "i64", nil - case DOUBLE: - return "dbl", nil - case STRING: - return "str", nil - case STRUCT: - return "rec", nil - case MAP: - return "map", nil - case SET: - return "set", nil - case LIST: - return "lst", nil - } - - e := fmt.Errorf("Unknown fieldType: %d", int(fieldType)) - return "", NewTProtocolExceptionWithType(INVALID_DATA, e) -} - -func (p *TJSONProtocol) StringToTypeId(fieldType string) (TType, error) { - switch fieldType { - case "tf": - return TType(BOOL), nil - case "i8": - return TType(BYTE), nil - case "i16": - return TType(I16), nil - case "i32": - return TType(I32), nil - case "i64": - return TType(I64), nil - case "dbl": - return TType(DOUBLE), nil - case "str": - return TType(STRING), nil - case "rec": - return TType(STRUCT), nil - case "map": - return TType(MAP), nil - case "set": - return TType(SET), nil - case "lst": - return TType(LIST), nil - } - - e := fmt.Errorf("Unknown type identifier: %s", fieldType) - return TType(STOP), NewTProtocolExceptionWithType(INVALID_DATA, e) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/memory_buffer.go b/vendor/github.com/apache/thrift/lib/go/thrift/memory_buffer.go deleted file mode 100644 index 5936d2730..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/memory_buffer.go +++ /dev/null @@ -1,80 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bytes" - "context" -) - -// Memory buffer-based implementation of the TTransport interface. -type TMemoryBuffer struct { - *bytes.Buffer - size int -} - -type TMemoryBufferTransportFactory struct { - size int -} - -func (p *TMemoryBufferTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - if trans != nil { - t, ok := trans.(*TMemoryBuffer) - if ok && t.size > 0 { - return NewTMemoryBufferLen(t.size), nil - } - } - return NewTMemoryBufferLen(p.size), nil -} - -func NewTMemoryBufferTransportFactory(size int) *TMemoryBufferTransportFactory { - return &TMemoryBufferTransportFactory{size: size} -} - -func NewTMemoryBuffer() *TMemoryBuffer { - return &TMemoryBuffer{Buffer: &bytes.Buffer{}, size: 0} -} - -func NewTMemoryBufferLen(size int) *TMemoryBuffer { - buf := make([]byte, 0, size) - return &TMemoryBuffer{Buffer: bytes.NewBuffer(buf), size: size} -} - -func (p *TMemoryBuffer) IsOpen() bool { - return true -} - -func (p *TMemoryBuffer) Open() error { - return nil -} - -func (p *TMemoryBuffer) Close() error { - p.Buffer.Reset() - return nil -} - -// Flushing a memory buffer is a no-op -func (p *TMemoryBuffer) Flush(ctx context.Context) error { - return nil -} - -func (p *TMemoryBuffer) RemainingBytes() (num_bytes uint64) { - return uint64(p.Buffer.Len()) -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/messagetype.go b/vendor/github.com/apache/thrift/lib/go/thrift/messagetype.go deleted file mode 100644 index 25ab2e98a..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/messagetype.go +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Message type constants in the Thrift protocol. -type TMessageType int32 - -const ( - INVALID_TMESSAGE_TYPE TMessageType = 0 - CALL TMessageType = 1 - REPLY TMessageType = 2 - EXCEPTION TMessageType = 3 - ONEWAY TMessageType = 4 -) diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/multiplexed_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/multiplexed_protocol.go deleted file mode 100644 index d028a30b3..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/multiplexed_protocol.go +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "fmt" - "strings" -) - -/* -TMultiplexedProtocol is a protocol-independent concrete decorator -that allows a Thrift client to communicate with a multiplexing Thrift server, -by prepending the service name to the function name during function calls. - -NOTE: THIS IS NOT USED BY SERVERS. On the server, use TMultiplexedProcessor to handle request -from a multiplexing client. - -This example uses a single socket transport to invoke two services: - -socket := thrift.NewTSocketFromAddrTimeout(addr, TIMEOUT) -transport := thrift.NewTFramedTransport(socket) -protocol := thrift.NewTBinaryProtocolTransport(transport) - -mp := thrift.NewTMultiplexedProtocol(protocol, "Calculator") -service := Calculator.NewCalculatorClient(mp) - -mp2 := thrift.NewTMultiplexedProtocol(protocol, "WeatherReport") -service2 := WeatherReport.NewWeatherReportClient(mp2) - -err := transport.Open() -if err != nil { - t.Fatal("Unable to open client socket", err) -} - -fmt.Println(service.Add(2,2)) -fmt.Println(service2.GetTemperature()) -*/ - -type TMultiplexedProtocol struct { - TProtocol - serviceName string -} - -const MULTIPLEXED_SEPARATOR = ":" - -func NewTMultiplexedProtocol(protocol TProtocol, serviceName string) *TMultiplexedProtocol { - return &TMultiplexedProtocol{ - TProtocol: protocol, - serviceName: serviceName, - } -} - -func (t *TMultiplexedProtocol) WriteMessageBegin(name string, typeId TMessageType, seqid int32) error { - if typeId == CALL || typeId == ONEWAY { - return t.TProtocol.WriteMessageBegin(t.serviceName+MULTIPLEXED_SEPARATOR+name, typeId, seqid) - } else { - return t.TProtocol.WriteMessageBegin(name, typeId, seqid) - } -} - -/* -TMultiplexedProcessor is a TProcessor allowing -a single TServer to provide multiple services. - -To do so, you instantiate the processor and then register additional -processors with it, as shown in the following example: - -var processor = thrift.NewTMultiplexedProcessor() - -firstProcessor := -processor.RegisterProcessor("FirstService", firstProcessor) - -processor.registerProcessor( - "Calculator", - Calculator.NewCalculatorProcessor(&CalculatorHandler{}), -) - -processor.registerProcessor( - "WeatherReport", - WeatherReport.NewWeatherReportProcessor(&WeatherReportHandler{}), -) - -serverTransport, err := thrift.NewTServerSocketTimeout(addr, TIMEOUT) -if err != nil { - t.Fatal("Unable to create server socket", err) -} -server := thrift.NewTSimpleServer2(processor, serverTransport) -server.Serve(); -*/ - -type TMultiplexedProcessor struct { - serviceProcessorMap map[string]TProcessor - DefaultProcessor TProcessor -} - -func NewTMultiplexedProcessor() *TMultiplexedProcessor { - return &TMultiplexedProcessor{ - serviceProcessorMap: make(map[string]TProcessor), - } -} - -func (t *TMultiplexedProcessor) RegisterDefault(processor TProcessor) { - t.DefaultProcessor = processor -} - -func (t *TMultiplexedProcessor) RegisterProcessor(name string, processor TProcessor) { - if t.serviceProcessorMap == nil { - t.serviceProcessorMap = make(map[string]TProcessor) - } - t.serviceProcessorMap[name] = processor -} - -func (t *TMultiplexedProcessor) Process(ctx context.Context, in, out TProtocol) (bool, TException) { - name, typeId, seqid, err := in.ReadMessageBegin() - if err != nil { - return false, err - } - if typeId != CALL && typeId != ONEWAY { - return false, fmt.Errorf("Unexpected message type %v", typeId) - } - //extract the service name - v := strings.SplitN(name, MULTIPLEXED_SEPARATOR, 2) - if len(v) != 2 { - if t.DefaultProcessor != nil { - smb := NewStoredMessageProtocol(in, name, typeId, seqid) - return t.DefaultProcessor.Process(ctx, smb, out) - } - return false, fmt.Errorf("Service name not found in message name: %s. Did you forget to use a TMultiplexProtocol in your client?", name) - } - actualProcessor, ok := t.serviceProcessorMap[v[0]] - if !ok { - return false, fmt.Errorf("Service name not found: %s. Did you forget to call registerProcessor()?", v[0]) - } - smb := NewStoredMessageProtocol(in, v[1], typeId, seqid) - return actualProcessor.Process(ctx, smb, out) -} - -//Protocol that use stored message for ReadMessageBegin -type storedMessageProtocol struct { - TProtocol - name string - typeId TMessageType - seqid int32 -} - -func NewStoredMessageProtocol(protocol TProtocol, name string, typeId TMessageType, seqid int32) *storedMessageProtocol { - return &storedMessageProtocol{protocol, name, typeId, seqid} -} - -func (s *storedMessageProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqid int32, err error) { - return s.name, s.typeId, s.seqid, nil -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/numeric.go b/vendor/github.com/apache/thrift/lib/go/thrift/numeric.go deleted file mode 100644 index aa8daa9b5..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/numeric.go +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "math" - "strconv" -) - -type Numeric interface { - Int64() int64 - Int32() int32 - Int16() int16 - Byte() byte - Int() int - Float64() float64 - Float32() float32 - String() string - isNull() bool -} - -type numeric struct { - iValue int64 - dValue float64 - sValue string - isNil bool -} - -var ( - INFINITY Numeric - NEGATIVE_INFINITY Numeric - NAN Numeric - ZERO Numeric - NUMERIC_NULL Numeric -) - -func NewNumericFromDouble(dValue float64) Numeric { - if math.IsInf(dValue, 1) { - return INFINITY - } - if math.IsInf(dValue, -1) { - return NEGATIVE_INFINITY - } - if math.IsNaN(dValue) { - return NAN - } - iValue := int64(dValue) - sValue := strconv.FormatFloat(dValue, 'g', 10, 64) - isNil := false - return &numeric{iValue: iValue, dValue: dValue, sValue: sValue, isNil: isNil} -} - -func NewNumericFromI64(iValue int64) Numeric { - dValue := float64(iValue) - sValue := string(iValue) - isNil := false - return &numeric{iValue: iValue, dValue: dValue, sValue: sValue, isNil: isNil} -} - -func NewNumericFromI32(iValue int32) Numeric { - dValue := float64(iValue) - sValue := string(iValue) - isNil := false - return &numeric{iValue: int64(iValue), dValue: dValue, sValue: sValue, isNil: isNil} -} - -func NewNumericFromString(sValue string) Numeric { - if sValue == INFINITY.String() { - return INFINITY - } - if sValue == NEGATIVE_INFINITY.String() { - return NEGATIVE_INFINITY - } - if sValue == NAN.String() { - return NAN - } - iValue, _ := strconv.ParseInt(sValue, 10, 64) - dValue, _ := strconv.ParseFloat(sValue, 64) - isNil := len(sValue) == 0 - return &numeric{iValue: iValue, dValue: dValue, sValue: sValue, isNil: isNil} -} - -func NewNumericFromJSONString(sValue string, isNull bool) Numeric { - if isNull { - return NewNullNumeric() - } - if sValue == JSON_INFINITY { - return INFINITY - } - if sValue == JSON_NEGATIVE_INFINITY { - return NEGATIVE_INFINITY - } - if sValue == JSON_NAN { - return NAN - } - iValue, _ := strconv.ParseInt(sValue, 10, 64) - dValue, _ := strconv.ParseFloat(sValue, 64) - return &numeric{iValue: iValue, dValue: dValue, sValue: sValue, isNil: isNull} -} - -func NewNullNumeric() Numeric { - return &numeric{iValue: 0, dValue: 0.0, sValue: "", isNil: true} -} - -func (p *numeric) Int64() int64 { - return p.iValue -} - -func (p *numeric) Int32() int32 { - return int32(p.iValue) -} - -func (p *numeric) Int16() int16 { - return int16(p.iValue) -} - -func (p *numeric) Byte() byte { - return byte(p.iValue) -} - -func (p *numeric) Int() int { - return int(p.iValue) -} - -func (p *numeric) Float64() float64 { - return p.dValue -} - -func (p *numeric) Float32() float32 { - return float32(p.dValue) -} - -func (p *numeric) String() string { - return p.sValue -} - -func (p *numeric) isNull() bool { - return p.isNil -} - -func init() { - INFINITY = &numeric{iValue: 0, dValue: math.Inf(1), sValue: "Infinity", isNil: false} - NEGATIVE_INFINITY = &numeric{iValue: 0, dValue: math.Inf(-1), sValue: "-Infinity", isNil: false} - NAN = &numeric{iValue: 0, dValue: math.NaN(), sValue: "NaN", isNil: false} - ZERO = &numeric{iValue: 0, dValue: 0, sValue: "0", isNil: false} - NUMERIC_NULL = &numeric{iValue: 0, dValue: 0, sValue: "0", isNil: true} -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/pointerize.go b/vendor/github.com/apache/thrift/lib/go/thrift/pointerize.go deleted file mode 100644 index 8d6b2c215..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/pointerize.go +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -/////////////////////////////////////////////////////////////////////////////// -// This file is home to helpers that convert from various base types to -// respective pointer types. This is necessary because Go does not permit -// references to constants, nor can a pointer type to base type be allocated -// and initialized in a single expression. -// -// E.g., this is not allowed: -// -// var ip *int = &5 -// -// But this *is* allowed: -// -// func IntPtr(i int) *int { return &i } -// var ip *int = IntPtr(5) -// -// Since pointers to base types are commonplace as [optional] fields in -// exported thrift structs, we factor such helpers here. -/////////////////////////////////////////////////////////////////////////////// - -func Float32Ptr(v float32) *float32 { return &v } -func Float64Ptr(v float64) *float64 { return &v } -func IntPtr(v int) *int { return &v } -func Int32Ptr(v int32) *int32 { return &v } -func Int64Ptr(v int64) *int64 { return &v } -func StringPtr(v string) *string { return &v } -func Uint32Ptr(v uint32) *uint32 { return &v } -func Uint64Ptr(v uint64) *uint64 { return &v } -func BoolPtr(v bool) *bool { return &v } -func ByteSlicePtr(v []byte) *[]byte { return &v } diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/processor_factory.go b/vendor/github.com/apache/thrift/lib/go/thrift/processor_factory.go deleted file mode 100644 index e4b132b30..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/processor_factory.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import "context" - -// A processor is a generic object which operates upon an input stream and -// writes to some output stream. -type TProcessor interface { - Process(ctx context.Context, in, out TProtocol) (bool, TException) -} - -type TProcessorFunction interface { - Process(ctx context.Context, seqId int32, in, out TProtocol) (bool, TException) -} - -// The default processor factory just returns a singleton -// instance. -type TProcessorFactory interface { - GetProcessor(trans TTransport) TProcessor -} - -type tProcessorFactory struct { - processor TProcessor -} - -func NewTProcessorFactory(p TProcessor) TProcessorFactory { - return &tProcessorFactory{processor: p} -} - -func (p *tProcessorFactory) GetProcessor(trans TTransport) TProcessor { - return p.processor -} - -/** - * The default processor factory just returns a singleton - * instance. - */ -type TProcessorFunctionFactory interface { - GetProcessorFunction(trans TTransport) TProcessorFunction -} - -type tProcessorFunctionFactory struct { - processor TProcessorFunction -} - -func NewTProcessorFunctionFactory(p TProcessorFunction) TProcessorFunctionFactory { - return &tProcessorFunctionFactory{processor: p} -} - -func (p *tProcessorFunctionFactory) GetProcessorFunction(trans TTransport) TProcessorFunction { - return p.processor -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/protocol.go deleted file mode 100644 index 615b7a4a8..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/protocol.go +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "errors" - "fmt" -) - -const ( - VERSION_MASK = 0xffff0000 - VERSION_1 = 0x80010000 -) - -type TProtocol interface { - WriteMessageBegin(name string, typeId TMessageType, seqid int32) error - WriteMessageEnd() error - WriteStructBegin(name string) error - WriteStructEnd() error - WriteFieldBegin(name string, typeId TType, id int16) error - WriteFieldEnd() error - WriteFieldStop() error - WriteMapBegin(keyType TType, valueType TType, size int) error - WriteMapEnd() error - WriteListBegin(elemType TType, size int) error - WriteListEnd() error - WriteSetBegin(elemType TType, size int) error - WriteSetEnd() error - WriteBool(value bool) error - WriteByte(value int8) error - WriteI16(value int16) error - WriteI32(value int32) error - WriteI64(value int64) error - WriteDouble(value float64) error - WriteString(value string) error - WriteBinary(value []byte) error - - ReadMessageBegin() (name string, typeId TMessageType, seqid int32, err error) - ReadMessageEnd() error - ReadStructBegin() (name string, err error) - ReadStructEnd() error - ReadFieldBegin() (name string, typeId TType, id int16, err error) - ReadFieldEnd() error - ReadMapBegin() (keyType TType, valueType TType, size int, err error) - ReadMapEnd() error - ReadListBegin() (elemType TType, size int, err error) - ReadListEnd() error - ReadSetBegin() (elemType TType, size int, err error) - ReadSetEnd() error - ReadBool() (value bool, err error) - ReadByte() (value int8, err error) - ReadI16() (value int16, err error) - ReadI32() (value int32, err error) - ReadI64() (value int64, err error) - ReadDouble() (value float64, err error) - ReadString() (value string, err error) - ReadBinary() (value []byte, err error) - - Skip(fieldType TType) (err error) - Flush(ctx context.Context) (err error) - - Transport() TTransport -} - -// The maximum recursive depth the skip() function will traverse -const DEFAULT_RECURSION_DEPTH = 64 - -// Skips over the next data element from the provided input TProtocol object. -func SkipDefaultDepth(prot TProtocol, typeId TType) (err error) { - return Skip(prot, typeId, DEFAULT_RECURSION_DEPTH) -} - -// Skips over the next data element from the provided input TProtocol object. -func Skip(self TProtocol, fieldType TType, maxDepth int) (err error) { - - if maxDepth <= 0 { - return NewTProtocolExceptionWithType(DEPTH_LIMIT, errors.New("Depth limit exceeded")) - } - - switch fieldType { - case STOP: - return - case BOOL: - _, err = self.ReadBool() - return - case BYTE: - _, err = self.ReadByte() - return - case I16: - _, err = self.ReadI16() - return - case I32: - _, err = self.ReadI32() - return - case I64: - _, err = self.ReadI64() - return - case DOUBLE: - _, err = self.ReadDouble() - return - case STRING: - _, err = self.ReadString() - return - case STRUCT: - if _, err = self.ReadStructBegin(); err != nil { - return err - } - for { - _, typeId, _, _ := self.ReadFieldBegin() - if typeId == STOP { - break - } - err := Skip(self, typeId, maxDepth-1) - if err != nil { - return err - } - self.ReadFieldEnd() - } - return self.ReadStructEnd() - case MAP: - keyType, valueType, size, err := self.ReadMapBegin() - if err != nil { - return err - } - for i := 0; i < size; i++ { - err := Skip(self, keyType, maxDepth-1) - if err != nil { - return err - } - self.Skip(valueType) - } - return self.ReadMapEnd() - case SET: - elemType, size, err := self.ReadSetBegin() - if err != nil { - return err - } - for i := 0; i < size; i++ { - err := Skip(self, elemType, maxDepth-1) - if err != nil { - return err - } - } - return self.ReadSetEnd() - case LIST: - elemType, size, err := self.ReadListBegin() - if err != nil { - return err - } - for i := 0; i < size; i++ { - err := Skip(self, elemType, maxDepth-1) - if err != nil { - return err - } - } - return self.ReadListEnd() - default: - return NewTProtocolExceptionWithType(INVALID_DATA, errors.New(fmt.Sprintf("Unknown data type %d", fieldType))) - } - return nil -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/protocol_exception.go b/vendor/github.com/apache/thrift/lib/go/thrift/protocol_exception.go deleted file mode 100644 index 29ab75d92..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/protocol_exception.go +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "encoding/base64" -) - -// Thrift Protocol exception -type TProtocolException interface { - TException - TypeId() int -} - -const ( - UNKNOWN_PROTOCOL_EXCEPTION = 0 - INVALID_DATA = 1 - NEGATIVE_SIZE = 2 - SIZE_LIMIT = 3 - BAD_VERSION = 4 - NOT_IMPLEMENTED = 5 - DEPTH_LIMIT = 6 -) - -type tProtocolException struct { - typeId int - message string -} - -func (p *tProtocolException) TypeId() int { - return p.typeId -} - -func (p *tProtocolException) String() string { - return p.message -} - -func (p *tProtocolException) Error() string { - return p.message -} - -func NewTProtocolException(err error) TProtocolException { - if err == nil { - return nil - } - if e, ok := err.(TProtocolException); ok { - return e - } - if _, ok := err.(base64.CorruptInputError); ok { - return &tProtocolException{INVALID_DATA, err.Error()} - } - return &tProtocolException{UNKNOWN_PROTOCOL_EXCEPTION, err.Error()} -} - -func NewTProtocolExceptionWithType(errType int, err error) TProtocolException { - if err == nil { - return nil - } - return &tProtocolException{errType, err.Error()} -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/protocol_factory.go b/vendor/github.com/apache/thrift/lib/go/thrift/protocol_factory.go deleted file mode 100644 index c40f796d8..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/protocol_factory.go +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Factory interface for constructing protocol instances. -type TProtocolFactory interface { - GetProtocol(trans TTransport) TProtocol -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/rich_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/rich_transport.go deleted file mode 100644 index 4025bebea..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/rich_transport.go +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import "io" - -type RichTransport struct { - TTransport -} - -// Wraps Transport to provide TRichTransport interface -func NewTRichTransport(trans TTransport) *RichTransport { - return &RichTransport{trans} -} - -func (r *RichTransport) ReadByte() (c byte, err error) { - return readByte(r.TTransport) -} - -func (r *RichTransport) WriteByte(c byte) error { - return writeByte(r.TTransport, c) -} - -func (r *RichTransport) WriteString(s string) (n int, err error) { - return r.Write([]byte(s)) -} - -func (r *RichTransport) RemainingBytes() (num_bytes uint64) { - return r.TTransport.RemainingBytes() -} - -func readByte(r io.Reader) (c byte, err error) { - v := [1]byte{0} - n, err := r.Read(v[0:1]) - if n > 0 && (err == nil || err == io.EOF) { - return v[0], nil - } - if n > 0 && err != nil { - return v[0], err - } - if err != nil { - return 0, err - } - return v[0], nil -} - -func writeByte(w io.Writer, c byte) error { - v := [1]byte{c} - _, err := w.Write(v[0:1]) - return err -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/serializer.go b/vendor/github.com/apache/thrift/lib/go/thrift/serializer.go deleted file mode 100644 index 1ff4d3754..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/serializer.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" -) - -type TSerializer struct { - Transport *TMemoryBuffer - Protocol TProtocol -} - -type TStruct interface { - Write(p TProtocol) error - Read(p TProtocol) error -} - -func NewTSerializer() *TSerializer { - transport := NewTMemoryBufferLen(1024) - protocol := NewTBinaryProtocolFactoryDefault().GetProtocol(transport) - - return &TSerializer{ - transport, - protocol} -} - -func (t *TSerializer) WriteString(ctx context.Context, msg TStruct) (s string, err error) { - t.Transport.Reset() - - if err = msg.Write(t.Protocol); err != nil { - return - } - - if err = t.Protocol.Flush(ctx); err != nil { - return - } - if err = t.Transport.Flush(ctx); err != nil { - return - } - - return t.Transport.String(), nil -} - -func (t *TSerializer) Write(ctx context.Context, msg TStruct) (b []byte, err error) { - t.Transport.Reset() - - if err = msg.Write(t.Protocol); err != nil { - return - } - - if err = t.Protocol.Flush(ctx); err != nil { - return - } - - if err = t.Transport.Flush(ctx); err != nil { - return - } - - b = append(b, t.Transport.Bytes()...) - return -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/server.go b/vendor/github.com/apache/thrift/lib/go/thrift/server.go deleted file mode 100644 index f813fa353..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/server.go +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -type TServer interface { - ProcessorFactory() TProcessorFactory - ServerTransport() TServerTransport - InputTransportFactory() TTransportFactory - OutputTransportFactory() TTransportFactory - InputProtocolFactory() TProtocolFactory - OutputProtocolFactory() TProtocolFactory - - // Starts the server - Serve() error - // Stops the server. This is optional on a per-implementation basis. Not - // all servers are required to be cleanly stoppable. - Stop() error -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/server_socket.go b/vendor/github.com/apache/thrift/lib/go/thrift/server_socket.go deleted file mode 100644 index 7dd24ae36..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/server_socket.go +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "net" - "sync" - "time" -) - -type TServerSocket struct { - listener net.Listener - addr net.Addr - clientTimeout time.Duration - - // Protects the interrupted value to make it thread safe. - mu sync.RWMutex - interrupted bool -} - -func NewTServerSocket(listenAddr string) (*TServerSocket, error) { - return NewTServerSocketTimeout(listenAddr, 0) -} - -func NewTServerSocketTimeout(listenAddr string, clientTimeout time.Duration) (*TServerSocket, error) { - addr, err := net.ResolveTCPAddr("tcp", listenAddr) - if err != nil { - return nil, err - } - return &TServerSocket{addr: addr, clientTimeout: clientTimeout}, nil -} - -// Creates a TServerSocket from a net.Addr -func NewTServerSocketFromAddrTimeout(addr net.Addr, clientTimeout time.Duration) *TServerSocket { - return &TServerSocket{addr: addr, clientTimeout: clientTimeout} -} - -func (p *TServerSocket) Listen() error { - p.mu.Lock() - defer p.mu.Unlock() - if p.IsListening() { - return nil - } - l, err := net.Listen(p.addr.Network(), p.addr.String()) - if err != nil { - return err - } - p.listener = l - return nil -} - -func (p *TServerSocket) Accept() (TTransport, error) { - p.mu.RLock() - interrupted := p.interrupted - p.mu.RUnlock() - - if interrupted { - return nil, errTransportInterrupted - } - - p.mu.Lock() - listener := p.listener - p.mu.Unlock() - if listener == nil { - return nil, NewTTransportException(NOT_OPEN, "No underlying server socket") - } - - conn, err := listener.Accept() - if err != nil { - return nil, NewTTransportExceptionFromError(err) - } - return NewTSocketFromConnTimeout(conn, p.clientTimeout), nil -} - -// Checks whether the socket is listening. -func (p *TServerSocket) IsListening() bool { - return p.listener != nil -} - -// Connects the socket, creating a new socket object if necessary. -func (p *TServerSocket) Open() error { - p.mu.Lock() - defer p.mu.Unlock() - if p.IsListening() { - return NewTTransportException(ALREADY_OPEN, "Server socket already open") - } - if l, err := net.Listen(p.addr.Network(), p.addr.String()); err != nil { - return err - } else { - p.listener = l - } - return nil -} - -func (p *TServerSocket) Addr() net.Addr { - if p.listener != nil { - return p.listener.Addr() - } - return p.addr -} - -func (p *TServerSocket) Close() error { - var err error - p.mu.Lock() - if p.IsListening() { - err = p.listener.Close() - p.listener = nil - } - p.mu.Unlock() - return err -} - -func (p *TServerSocket) Interrupt() error { - p.mu.Lock() - p.interrupted = true - p.mu.Unlock() - p.Close() - - return nil -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/server_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/server_transport.go deleted file mode 100644 index 51c40b64a..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/server_transport.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Server transport. Object which provides client transports. -type TServerTransport interface { - Listen() error - Accept() (TTransport, error) - Close() error - - // Optional method implementation. This signals to the server transport - // that it should break out of any accept() or listen() that it is currently - // blocked on. This method, if implemented, MUST be thread safe, as it may - // be called from a different thread context than the other TServerTransport - // methods. - Interrupt() error -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/simple_json_protocol.go b/vendor/github.com/apache/thrift/lib/go/thrift/simple_json_protocol.go deleted file mode 100644 index 2e8a71112..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/simple_json_protocol.go +++ /dev/null @@ -1,1338 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "bufio" - "bytes" - "context" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "math" - "strconv" -) - -type _ParseContext int - -const ( - _CONTEXT_IN_TOPLEVEL _ParseContext = 1 - _CONTEXT_IN_LIST_FIRST _ParseContext = 2 - _CONTEXT_IN_LIST _ParseContext = 3 - _CONTEXT_IN_OBJECT_FIRST _ParseContext = 4 - _CONTEXT_IN_OBJECT_NEXT_KEY _ParseContext = 5 - _CONTEXT_IN_OBJECT_NEXT_VALUE _ParseContext = 6 -) - -func (p _ParseContext) String() string { - switch p { - case _CONTEXT_IN_TOPLEVEL: - return "TOPLEVEL" - case _CONTEXT_IN_LIST_FIRST: - return "LIST-FIRST" - case _CONTEXT_IN_LIST: - return "LIST" - case _CONTEXT_IN_OBJECT_FIRST: - return "OBJECT-FIRST" - case _CONTEXT_IN_OBJECT_NEXT_KEY: - return "OBJECT-NEXT-KEY" - case _CONTEXT_IN_OBJECT_NEXT_VALUE: - return "OBJECT-NEXT-VALUE" - } - return "UNKNOWN-PARSE-CONTEXT" -} - -// JSON protocol implementation for thrift. -// -// This protocol produces/consumes a simple output format -// suitable for parsing by scripting languages. It should not be -// confused with the full-featured TJSONProtocol. -// -type TSimpleJSONProtocol struct { - trans TTransport - - parseContextStack []int - dumpContext []int - - writer *bufio.Writer - reader *bufio.Reader -} - -// Constructor -func NewTSimpleJSONProtocol(t TTransport) *TSimpleJSONProtocol { - v := &TSimpleJSONProtocol{trans: t, - writer: bufio.NewWriter(t), - reader: bufio.NewReader(t), - } - v.parseContextStack = append(v.parseContextStack, int(_CONTEXT_IN_TOPLEVEL)) - v.dumpContext = append(v.dumpContext, int(_CONTEXT_IN_TOPLEVEL)) - return v -} - -// Factory -type TSimpleJSONProtocolFactory struct{} - -func (p *TSimpleJSONProtocolFactory) GetProtocol(trans TTransport) TProtocol { - return NewTSimpleJSONProtocol(trans) -} - -func NewTSimpleJSONProtocolFactory() *TSimpleJSONProtocolFactory { - return &TSimpleJSONProtocolFactory{} -} - -var ( - JSON_COMMA []byte - JSON_COLON []byte - JSON_LBRACE []byte - JSON_RBRACE []byte - JSON_LBRACKET []byte - JSON_RBRACKET []byte - JSON_QUOTE byte - JSON_QUOTE_BYTES []byte - JSON_NULL []byte - JSON_TRUE []byte - JSON_FALSE []byte - JSON_INFINITY string - JSON_NEGATIVE_INFINITY string - JSON_NAN string - JSON_INFINITY_BYTES []byte - JSON_NEGATIVE_INFINITY_BYTES []byte - JSON_NAN_BYTES []byte - json_nonbase_map_elem_bytes []byte -) - -func init() { - JSON_COMMA = []byte{','} - JSON_COLON = []byte{':'} - JSON_LBRACE = []byte{'{'} - JSON_RBRACE = []byte{'}'} - JSON_LBRACKET = []byte{'['} - JSON_RBRACKET = []byte{']'} - JSON_QUOTE = '"' - JSON_QUOTE_BYTES = []byte{'"'} - JSON_NULL = []byte{'n', 'u', 'l', 'l'} - JSON_TRUE = []byte{'t', 'r', 'u', 'e'} - JSON_FALSE = []byte{'f', 'a', 'l', 's', 'e'} - JSON_INFINITY = "Infinity" - JSON_NEGATIVE_INFINITY = "-Infinity" - JSON_NAN = "NaN" - JSON_INFINITY_BYTES = []byte{'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'} - JSON_NEGATIVE_INFINITY_BYTES = []byte{'-', 'I', 'n', 'f', 'i', 'n', 'i', 't', 'y'} - JSON_NAN_BYTES = []byte{'N', 'a', 'N'} - json_nonbase_map_elem_bytes = []byte{']', ',', '['} -} - -func jsonQuote(s string) string { - b, _ := json.Marshal(s) - s1 := string(b) - return s1 -} - -func jsonUnquote(s string) (string, bool) { - s1 := new(string) - err := json.Unmarshal([]byte(s), s1) - return *s1, err == nil -} - -func mismatch(expected, actual string) error { - return fmt.Errorf("Expected '%s' but found '%s' while parsing JSON.", expected, actual) -} - -func (p *TSimpleJSONProtocol) WriteMessageBegin(name string, typeId TMessageType, seqId int32) error { - p.resetContextStack() // THRIFT-3735 - if e := p.OutputListBegin(); e != nil { - return e - } - if e := p.WriteString(name); e != nil { - return e - } - if e := p.WriteByte(int8(typeId)); e != nil { - return e - } - if e := p.WriteI32(seqId); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) WriteMessageEnd() error { - return p.OutputListEnd() -} - -func (p *TSimpleJSONProtocol) WriteStructBegin(name string) error { - if e := p.OutputObjectBegin(); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) WriteStructEnd() error { - return p.OutputObjectEnd() -} - -func (p *TSimpleJSONProtocol) WriteFieldBegin(name string, typeId TType, id int16) error { - if e := p.WriteString(name); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) WriteFieldEnd() error { - //return p.OutputListEnd() - return nil -} - -func (p *TSimpleJSONProtocol) WriteFieldStop() error { return nil } - -func (p *TSimpleJSONProtocol) WriteMapBegin(keyType TType, valueType TType, size int) error { - if e := p.OutputListBegin(); e != nil { - return e - } - if e := p.WriteByte(int8(keyType)); e != nil { - return e - } - if e := p.WriteByte(int8(valueType)); e != nil { - return e - } - return p.WriteI32(int32(size)) -} - -func (p *TSimpleJSONProtocol) WriteMapEnd() error { - return p.OutputListEnd() -} - -func (p *TSimpleJSONProtocol) WriteListBegin(elemType TType, size int) error { - return p.OutputElemListBegin(elemType, size) -} - -func (p *TSimpleJSONProtocol) WriteListEnd() error { - return p.OutputListEnd() -} - -func (p *TSimpleJSONProtocol) WriteSetBegin(elemType TType, size int) error { - return p.OutputElemListBegin(elemType, size) -} - -func (p *TSimpleJSONProtocol) WriteSetEnd() error { - return p.OutputListEnd() -} - -func (p *TSimpleJSONProtocol) WriteBool(b bool) error { - return p.OutputBool(b) -} - -func (p *TSimpleJSONProtocol) WriteByte(b int8) error { - return p.WriteI32(int32(b)) -} - -func (p *TSimpleJSONProtocol) WriteI16(v int16) error { - return p.WriteI32(int32(v)) -} - -func (p *TSimpleJSONProtocol) WriteI32(v int32) error { - return p.OutputI64(int64(v)) -} - -func (p *TSimpleJSONProtocol) WriteI64(v int64) error { - return p.OutputI64(int64(v)) -} - -func (p *TSimpleJSONProtocol) WriteDouble(v float64) error { - return p.OutputF64(v) -} - -func (p *TSimpleJSONProtocol) WriteString(v string) error { - return p.OutputString(v) -} - -func (p *TSimpleJSONProtocol) WriteBinary(v []byte) error { - // JSON library only takes in a string, - // not an arbitrary byte array, to ensure bytes are transmitted - // efficiently we must convert this into a valid JSON string - // therefore we use base64 encoding to avoid excessive escaping/quoting - if e := p.OutputPreValue(); e != nil { - return e - } - if _, e := p.write(JSON_QUOTE_BYTES); e != nil { - return NewTProtocolException(e) - } - writer := base64.NewEncoder(base64.StdEncoding, p.writer) - if _, e := writer.Write(v); e != nil { - p.writer.Reset(p.trans) // THRIFT-3735 - return NewTProtocolException(e) - } - if e := writer.Close(); e != nil { - return NewTProtocolException(e) - } - if _, e := p.write(JSON_QUOTE_BYTES); e != nil { - return NewTProtocolException(e) - } - return p.OutputPostValue() -} - -// Reading methods. -func (p *TSimpleJSONProtocol) ReadMessageBegin() (name string, typeId TMessageType, seqId int32, err error) { - p.resetContextStack() // THRIFT-3735 - if isNull, err := p.ParseListBegin(); isNull || err != nil { - return name, typeId, seqId, err - } - if name, err = p.ReadString(); err != nil { - return name, typeId, seqId, err - } - bTypeId, err := p.ReadByte() - typeId = TMessageType(bTypeId) - if err != nil { - return name, typeId, seqId, err - } - if seqId, err = p.ReadI32(); err != nil { - return name, typeId, seqId, err - } - return name, typeId, seqId, nil -} - -func (p *TSimpleJSONProtocol) ReadMessageEnd() error { - return p.ParseListEnd() -} - -func (p *TSimpleJSONProtocol) ReadStructBegin() (name string, err error) { - _, err = p.ParseObjectStart() - return "", err -} - -func (p *TSimpleJSONProtocol) ReadStructEnd() error { - return p.ParseObjectEnd() -} - -func (p *TSimpleJSONProtocol) ReadFieldBegin() (string, TType, int16, error) { - if err := p.ParsePreValue(); err != nil { - return "", STOP, 0, err - } - b, _ := p.reader.Peek(1) - if len(b) > 0 { - switch b[0] { - case JSON_RBRACE[0]: - return "", STOP, 0, nil - case JSON_QUOTE: - p.reader.ReadByte() - name, err := p.ParseStringBody() - // simplejson is not meant to be read back into thrift - // - see http://wiki.apache.org/thrift/ThriftUsageJava - // - use JSON instead - if err != nil { - return name, STOP, 0, err - } - return name, STOP, -1, p.ParsePostValue() - /* - if err = p.ParsePostValue(); err != nil { - return name, STOP, 0, err - } - if isNull, err := p.ParseListBegin(); isNull || err != nil { - return name, STOP, 0, err - } - bType, err := p.ReadByte() - thetype := TType(bType) - if err != nil { - return name, thetype, 0, err - } - id, err := p.ReadI16() - return name, thetype, id, err - */ - } - e := fmt.Errorf("Expected \"}\" or '\"', but found: '%s'", string(b)) - return "", STOP, 0, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return "", STOP, 0, NewTProtocolException(io.EOF) -} - -func (p *TSimpleJSONProtocol) ReadFieldEnd() error { - return nil - //return p.ParseListEnd() -} - -func (p *TSimpleJSONProtocol) ReadMapBegin() (keyType TType, valueType TType, size int, e error) { - if isNull, e := p.ParseListBegin(); isNull || e != nil { - return VOID, VOID, 0, e - } - - // read keyType - bKeyType, e := p.ReadByte() - keyType = TType(bKeyType) - if e != nil { - return keyType, valueType, size, e - } - - // read valueType - bValueType, e := p.ReadByte() - valueType = TType(bValueType) - if e != nil { - return keyType, valueType, size, e - } - - // read size - iSize, err := p.ReadI64() - size = int(iSize) - return keyType, valueType, size, err -} - -func (p *TSimpleJSONProtocol) ReadMapEnd() error { - return p.ParseListEnd() -} - -func (p *TSimpleJSONProtocol) ReadListBegin() (elemType TType, size int, e error) { - return p.ParseElemListBegin() -} - -func (p *TSimpleJSONProtocol) ReadListEnd() error { - return p.ParseListEnd() -} - -func (p *TSimpleJSONProtocol) ReadSetBegin() (elemType TType, size int, e error) { - return p.ParseElemListBegin() -} - -func (p *TSimpleJSONProtocol) ReadSetEnd() error { - return p.ParseListEnd() -} - -func (p *TSimpleJSONProtocol) ReadBool() (bool, error) { - var value bool - - if err := p.ParsePreValue(); err != nil { - return value, err - } - f, _ := p.reader.Peek(1) - if len(f) > 0 { - switch f[0] { - case JSON_TRUE[0]: - b := make([]byte, len(JSON_TRUE)) - _, err := p.reader.Read(b) - if err != nil { - return false, NewTProtocolException(err) - } - if string(b) == string(JSON_TRUE) { - value = true - } else { - e := fmt.Errorf("Expected \"true\" but found: %s", string(b)) - return value, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - break - case JSON_FALSE[0]: - b := make([]byte, len(JSON_FALSE)) - _, err := p.reader.Read(b) - if err != nil { - return false, NewTProtocolException(err) - } - if string(b) == string(JSON_FALSE) { - value = false - } else { - e := fmt.Errorf("Expected \"false\" but found: %s", string(b)) - return value, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - break - case JSON_NULL[0]: - b := make([]byte, len(JSON_NULL)) - _, err := p.reader.Read(b) - if err != nil { - return false, NewTProtocolException(err) - } - if string(b) == string(JSON_NULL) { - value = false - } else { - e := fmt.Errorf("Expected \"null\" but found: %s", string(b)) - return value, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - default: - e := fmt.Errorf("Expected \"true\", \"false\", or \"null\" but found: %s", string(f)) - return value, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - return value, p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) ReadByte() (int8, error) { - v, err := p.ReadI64() - return int8(v), err -} - -func (p *TSimpleJSONProtocol) ReadI16() (int16, error) { - v, err := p.ReadI64() - return int16(v), err -} - -func (p *TSimpleJSONProtocol) ReadI32() (int32, error) { - v, err := p.ReadI64() - return int32(v), err -} - -func (p *TSimpleJSONProtocol) ReadI64() (int64, error) { - v, _, err := p.ParseI64() - return v, err -} - -func (p *TSimpleJSONProtocol) ReadDouble() (float64, error) { - v, _, err := p.ParseF64() - return v, err -} - -func (p *TSimpleJSONProtocol) ReadString() (string, error) { - var v string - if err := p.ParsePreValue(); err != nil { - return v, err - } - f, _ := p.reader.Peek(1) - if len(f) > 0 && f[0] == JSON_QUOTE { - p.reader.ReadByte() - value, err := p.ParseStringBody() - v = value - if err != nil { - return v, err - } - } else if len(f) > 0 && f[0] == JSON_NULL[0] { - b := make([]byte, len(JSON_NULL)) - _, err := p.reader.Read(b) - if err != nil { - return v, NewTProtocolException(err) - } - if string(b) != string(JSON_NULL) { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(b)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } else { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(f)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return v, p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) ReadBinary() ([]byte, error) { - var v []byte - if err := p.ParsePreValue(); err != nil { - return nil, err - } - f, _ := p.reader.Peek(1) - if len(f) > 0 && f[0] == JSON_QUOTE { - p.reader.ReadByte() - value, err := p.ParseBase64EncodedBody() - v = value - if err != nil { - return v, err - } - } else if len(f) > 0 && f[0] == JSON_NULL[0] { - b := make([]byte, len(JSON_NULL)) - _, err := p.reader.Read(b) - if err != nil { - return v, NewTProtocolException(err) - } - if string(b) != string(JSON_NULL) { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(b)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } else { - e := fmt.Errorf("Expected a JSON string, found unquoted data started with %s", string(f)) - return v, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - - return v, p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) Flush(ctx context.Context) (err error) { - return NewTProtocolException(p.writer.Flush()) -} - -func (p *TSimpleJSONProtocol) Skip(fieldType TType) (err error) { - return SkipDefaultDepth(p, fieldType) -} - -func (p *TSimpleJSONProtocol) Transport() TTransport { - return p.trans -} - -func (p *TSimpleJSONProtocol) OutputPreValue() error { - cxt := _ParseContext(p.dumpContext[len(p.dumpContext)-1]) - switch cxt { - case _CONTEXT_IN_LIST, _CONTEXT_IN_OBJECT_NEXT_KEY: - if _, e := p.write(JSON_COMMA); e != nil { - return NewTProtocolException(e) - } - break - case _CONTEXT_IN_OBJECT_NEXT_VALUE: - if _, e := p.write(JSON_COLON); e != nil { - return NewTProtocolException(e) - } - break - } - return nil -} - -func (p *TSimpleJSONProtocol) OutputPostValue() error { - cxt := _ParseContext(p.dumpContext[len(p.dumpContext)-1]) - switch cxt { - case _CONTEXT_IN_LIST_FIRST: - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_LIST)) - break - case _CONTEXT_IN_OBJECT_FIRST: - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_OBJECT_NEXT_VALUE)) - break - case _CONTEXT_IN_OBJECT_NEXT_KEY: - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_OBJECT_NEXT_VALUE)) - break - case _CONTEXT_IN_OBJECT_NEXT_VALUE: - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_OBJECT_NEXT_KEY)) - break - } - return nil -} - -func (p *TSimpleJSONProtocol) OutputBool(value bool) error { - if e := p.OutputPreValue(); e != nil { - return e - } - var v string - if value { - v = string(JSON_TRUE) - } else { - v = string(JSON_FALSE) - } - switch _ParseContext(p.dumpContext[len(p.dumpContext)-1]) { - case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY: - v = jsonQuote(v) - default: - } - if e := p.OutputStringData(v); e != nil { - return e - } - return p.OutputPostValue() -} - -func (p *TSimpleJSONProtocol) OutputNull() error { - if e := p.OutputPreValue(); e != nil { - return e - } - if _, e := p.write(JSON_NULL); e != nil { - return NewTProtocolException(e) - } - return p.OutputPostValue() -} - -func (p *TSimpleJSONProtocol) OutputF64(value float64) error { - if e := p.OutputPreValue(); e != nil { - return e - } - var v string - if math.IsNaN(value) { - v = string(JSON_QUOTE) + JSON_NAN + string(JSON_QUOTE) - } else if math.IsInf(value, 1) { - v = string(JSON_QUOTE) + JSON_INFINITY + string(JSON_QUOTE) - } else if math.IsInf(value, -1) { - v = string(JSON_QUOTE) + JSON_NEGATIVE_INFINITY + string(JSON_QUOTE) - } else { - v = strconv.FormatFloat(value, 'g', -1, 64) - switch _ParseContext(p.dumpContext[len(p.dumpContext)-1]) { - case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY: - v = string(JSON_QUOTE) + v + string(JSON_QUOTE) - default: - } - } - if e := p.OutputStringData(v); e != nil { - return e - } - return p.OutputPostValue() -} - -func (p *TSimpleJSONProtocol) OutputI64(value int64) error { - if e := p.OutputPreValue(); e != nil { - return e - } - v := strconv.FormatInt(value, 10) - switch _ParseContext(p.dumpContext[len(p.dumpContext)-1]) { - case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY: - v = jsonQuote(v) - default: - } - if e := p.OutputStringData(v); e != nil { - return e - } - return p.OutputPostValue() -} - -func (p *TSimpleJSONProtocol) OutputString(s string) error { - if e := p.OutputPreValue(); e != nil { - return e - } - if e := p.OutputStringData(jsonQuote(s)); e != nil { - return e - } - return p.OutputPostValue() -} - -func (p *TSimpleJSONProtocol) OutputStringData(s string) error { - _, e := p.write([]byte(s)) - return NewTProtocolException(e) -} - -func (p *TSimpleJSONProtocol) OutputObjectBegin() error { - if e := p.OutputPreValue(); e != nil { - return e - } - if _, e := p.write(JSON_LBRACE); e != nil { - return NewTProtocolException(e) - } - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_OBJECT_FIRST)) - return nil -} - -func (p *TSimpleJSONProtocol) OutputObjectEnd() error { - if _, e := p.write(JSON_RBRACE); e != nil { - return NewTProtocolException(e) - } - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - if e := p.OutputPostValue(); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) OutputListBegin() error { - if e := p.OutputPreValue(); e != nil { - return e - } - if _, e := p.write(JSON_LBRACKET); e != nil { - return NewTProtocolException(e) - } - p.dumpContext = append(p.dumpContext, int(_CONTEXT_IN_LIST_FIRST)) - return nil -} - -func (p *TSimpleJSONProtocol) OutputListEnd() error { - if _, e := p.write(JSON_RBRACKET); e != nil { - return NewTProtocolException(e) - } - p.dumpContext = p.dumpContext[:len(p.dumpContext)-1] - if e := p.OutputPostValue(); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) OutputElemListBegin(elemType TType, size int) error { - if e := p.OutputListBegin(); e != nil { - return e - } - if e := p.WriteByte(int8(elemType)); e != nil { - return e - } - if e := p.WriteI64(int64(size)); e != nil { - return e - } - return nil -} - -func (p *TSimpleJSONProtocol) ParsePreValue() error { - if e := p.readNonSignificantWhitespace(); e != nil { - return NewTProtocolException(e) - } - cxt := _ParseContext(p.parseContextStack[len(p.parseContextStack)-1]) - b, _ := p.reader.Peek(1) - switch cxt { - case _CONTEXT_IN_LIST: - if len(b) > 0 { - switch b[0] { - case JSON_RBRACKET[0]: - return nil - case JSON_COMMA[0]: - p.reader.ReadByte() - if e := p.readNonSignificantWhitespace(); e != nil { - return NewTProtocolException(e) - } - return nil - default: - e := fmt.Errorf("Expected \"]\" or \",\" in list context, but found \"%s\"", string(b)) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - break - case _CONTEXT_IN_OBJECT_NEXT_KEY: - if len(b) > 0 { - switch b[0] { - case JSON_RBRACE[0]: - return nil - case JSON_COMMA[0]: - p.reader.ReadByte() - if e := p.readNonSignificantWhitespace(); e != nil { - return NewTProtocolException(e) - } - return nil - default: - e := fmt.Errorf("Expected \"}\" or \",\" in object context, but found \"%s\"", string(b)) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - break - case _CONTEXT_IN_OBJECT_NEXT_VALUE: - if len(b) > 0 { - switch b[0] { - case JSON_COLON[0]: - p.reader.ReadByte() - if e := p.readNonSignificantWhitespace(); e != nil { - return NewTProtocolException(e) - } - return nil - default: - e := fmt.Errorf("Expected \":\" in object context, but found \"%s\"", string(b)) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - break - } - return nil -} - -func (p *TSimpleJSONProtocol) ParsePostValue() error { - if e := p.readNonSignificantWhitespace(); e != nil { - return NewTProtocolException(e) - } - cxt := _ParseContext(p.parseContextStack[len(p.parseContextStack)-1]) - switch cxt { - case _CONTEXT_IN_LIST_FIRST: - p.parseContextStack = p.parseContextStack[:len(p.parseContextStack)-1] - p.parseContextStack = append(p.parseContextStack, int(_CONTEXT_IN_LIST)) - break - case _CONTEXT_IN_OBJECT_FIRST, _CONTEXT_IN_OBJECT_NEXT_KEY: - p.parseContextStack = p.parseContextStack[:len(p.parseContextStack)-1] - p.parseContextStack = append(p.parseContextStack, int(_CONTEXT_IN_OBJECT_NEXT_VALUE)) - break - case _CONTEXT_IN_OBJECT_NEXT_VALUE: - p.parseContextStack = p.parseContextStack[:len(p.parseContextStack)-1] - p.parseContextStack = append(p.parseContextStack, int(_CONTEXT_IN_OBJECT_NEXT_KEY)) - break - } - return nil -} - -func (p *TSimpleJSONProtocol) readNonSignificantWhitespace() error { - for { - b, _ := p.reader.Peek(1) - if len(b) < 1 { - return nil - } - switch b[0] { - case ' ', '\r', '\n', '\t': - p.reader.ReadByte() - continue - default: - break - } - break - } - return nil -} - -func (p *TSimpleJSONProtocol) ParseStringBody() (string, error) { - line, err := p.reader.ReadString(JSON_QUOTE) - if err != nil { - return "", NewTProtocolException(err) - } - l := len(line) - // count number of escapes to see if we need to keep going - i := 1 - for ; i < l; i++ { - if line[l-i-1] != '\\' { - break - } - } - if i&0x01 == 1 { - v, ok := jsonUnquote(string(JSON_QUOTE) + line) - if !ok { - return "", NewTProtocolException(err) - } - return v, nil - } - s, err := p.ParseQuotedStringBody() - if err != nil { - return "", NewTProtocolException(err) - } - str := string(JSON_QUOTE) + line + s - v, ok := jsonUnquote(str) - if !ok { - e := fmt.Errorf("Unable to parse as JSON string %s", str) - return "", NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return v, nil -} - -func (p *TSimpleJSONProtocol) ParseQuotedStringBody() (string, error) { - line, err := p.reader.ReadString(JSON_QUOTE) - if err != nil { - return "", NewTProtocolException(err) - } - l := len(line) - // count number of escapes to see if we need to keep going - i := 1 - for ; i < l; i++ { - if line[l-i-1] != '\\' { - break - } - } - if i&0x01 == 1 { - return line, nil - } - s, err := p.ParseQuotedStringBody() - if err != nil { - return "", NewTProtocolException(err) - } - v := line + s - return v, nil -} - -func (p *TSimpleJSONProtocol) ParseBase64EncodedBody() ([]byte, error) { - line, err := p.reader.ReadBytes(JSON_QUOTE) - if err != nil { - return line, NewTProtocolException(err) - } - line2 := line[0 : len(line)-1] - l := len(line2) - if (l % 4) != 0 { - pad := 4 - (l % 4) - fill := [...]byte{'=', '=', '='} - line2 = append(line2, fill[:pad]...) - l = len(line2) - } - output := make([]byte, base64.StdEncoding.DecodedLen(l)) - n, err := base64.StdEncoding.Decode(output, line2) - return output[0:n], NewTProtocolException(err) -} - -func (p *TSimpleJSONProtocol) ParseI64() (int64, bool, error) { - if err := p.ParsePreValue(); err != nil { - return 0, false, err - } - var value int64 - var isnull bool - if p.safePeekContains(JSON_NULL) { - p.reader.Read(make([]byte, len(JSON_NULL))) - isnull = true - } else { - num, err := p.readNumeric() - isnull = (num == nil) - if !isnull { - value = num.Int64() - } - if err != nil { - return value, isnull, err - } - } - return value, isnull, p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) ParseF64() (float64, bool, error) { - if err := p.ParsePreValue(); err != nil { - return 0, false, err - } - var value float64 - var isnull bool - if p.safePeekContains(JSON_NULL) { - p.reader.Read(make([]byte, len(JSON_NULL))) - isnull = true - } else { - num, err := p.readNumeric() - isnull = (num == nil) - if !isnull { - value = num.Float64() - } - if err != nil { - return value, isnull, err - } - } - return value, isnull, p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) ParseObjectStart() (bool, error) { - if err := p.ParsePreValue(); err != nil { - return false, err - } - var b []byte - b, err := p.reader.Peek(1) - if err != nil { - return false, err - } - if len(b) > 0 && b[0] == JSON_LBRACE[0] { - p.reader.ReadByte() - p.parseContextStack = append(p.parseContextStack, int(_CONTEXT_IN_OBJECT_FIRST)) - return false, nil - } else if p.safePeekContains(JSON_NULL) { - return true, nil - } - e := fmt.Errorf("Expected '{' or null, but found '%s'", string(b)) - return false, NewTProtocolExceptionWithType(INVALID_DATA, e) -} - -func (p *TSimpleJSONProtocol) ParseObjectEnd() error { - if isNull, err := p.readIfNull(); isNull || err != nil { - return err - } - cxt := _ParseContext(p.parseContextStack[len(p.parseContextStack)-1]) - if (cxt != _CONTEXT_IN_OBJECT_FIRST) && (cxt != _CONTEXT_IN_OBJECT_NEXT_KEY) { - e := fmt.Errorf("Expected to be in the Object Context, but not in Object Context (%d)", cxt) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - } - line, err := p.reader.ReadString(JSON_RBRACE[0]) - if err != nil { - return NewTProtocolException(err) - } - for _, char := range line { - switch char { - default: - e := fmt.Errorf("Expecting end of object \"}\", but found: \"%s\"", line) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - case ' ', '\n', '\r', '\t', '}': - break - } - } - p.parseContextStack = p.parseContextStack[:len(p.parseContextStack)-1] - return p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) ParseListBegin() (isNull bool, err error) { - if e := p.ParsePreValue(); e != nil { - return false, e - } - var b []byte - b, err = p.reader.Peek(1) - if err != nil { - return false, err - } - if len(b) >= 1 && b[0] == JSON_LBRACKET[0] { - p.parseContextStack = append(p.parseContextStack, int(_CONTEXT_IN_LIST_FIRST)) - p.reader.ReadByte() - isNull = false - } else if p.safePeekContains(JSON_NULL) { - isNull = true - } else { - err = fmt.Errorf("Expected \"null\" or \"[\", received %q", b) - } - return isNull, NewTProtocolExceptionWithType(INVALID_DATA, err) -} - -func (p *TSimpleJSONProtocol) ParseElemListBegin() (elemType TType, size int, e error) { - if isNull, e := p.ParseListBegin(); isNull || e != nil { - return VOID, 0, e - } - bElemType, err := p.ReadByte() - elemType = TType(bElemType) - if err != nil { - return elemType, size, err - } - nSize, err2 := p.ReadI64() - size = int(nSize) - return elemType, size, err2 -} - -func (p *TSimpleJSONProtocol) ParseListEnd() error { - if isNull, err := p.readIfNull(); isNull || err != nil { - return err - } - cxt := _ParseContext(p.parseContextStack[len(p.parseContextStack)-1]) - if cxt != _CONTEXT_IN_LIST { - e := fmt.Errorf("Expected to be in the List Context, but not in List Context (%d)", cxt) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - } - line, err := p.reader.ReadString(JSON_RBRACKET[0]) - if err != nil { - return NewTProtocolException(err) - } - for _, char := range line { - switch char { - default: - e := fmt.Errorf("Expecting end of list \"]\", but found: \"%v\"", line) - return NewTProtocolExceptionWithType(INVALID_DATA, e) - case ' ', '\n', '\r', '\t', rune(JSON_RBRACKET[0]): - break - } - } - p.parseContextStack = p.parseContextStack[:len(p.parseContextStack)-1] - if _ParseContext(p.parseContextStack[len(p.parseContextStack)-1]) == _CONTEXT_IN_TOPLEVEL { - return nil - } - return p.ParsePostValue() -} - -func (p *TSimpleJSONProtocol) readSingleValue() (interface{}, TType, error) { - e := p.readNonSignificantWhitespace() - if e != nil { - return nil, VOID, NewTProtocolException(e) - } - b, e := p.reader.Peek(1) - if len(b) > 0 { - c := b[0] - switch c { - case JSON_NULL[0]: - buf := make([]byte, len(JSON_NULL)) - _, e := p.reader.Read(buf) - if e != nil { - return nil, VOID, NewTProtocolException(e) - } - if string(JSON_NULL) != string(buf) { - e = mismatch(string(JSON_NULL), string(buf)) - return nil, VOID, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return nil, VOID, nil - case JSON_QUOTE: - p.reader.ReadByte() - v, e := p.ParseStringBody() - if e != nil { - return v, UTF8, NewTProtocolException(e) - } - if v == JSON_INFINITY { - return INFINITY, DOUBLE, nil - } else if v == JSON_NEGATIVE_INFINITY { - return NEGATIVE_INFINITY, DOUBLE, nil - } else if v == JSON_NAN { - return NAN, DOUBLE, nil - } - return v, UTF8, nil - case JSON_TRUE[0]: - buf := make([]byte, len(JSON_TRUE)) - _, e := p.reader.Read(buf) - if e != nil { - return true, BOOL, NewTProtocolException(e) - } - if string(JSON_TRUE) != string(buf) { - e := mismatch(string(JSON_TRUE), string(buf)) - return true, BOOL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return true, BOOL, nil - case JSON_FALSE[0]: - buf := make([]byte, len(JSON_FALSE)) - _, e := p.reader.Read(buf) - if e != nil { - return false, BOOL, NewTProtocolException(e) - } - if string(JSON_FALSE) != string(buf) { - e := mismatch(string(JSON_FALSE), string(buf)) - return false, BOOL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return false, BOOL, nil - case JSON_LBRACKET[0]: - _, e := p.reader.ReadByte() - return make([]interface{}, 0), LIST, NewTProtocolException(e) - case JSON_LBRACE[0]: - _, e := p.reader.ReadByte() - return make(map[string]interface{}), STRUCT, NewTProtocolException(e) - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'e', 'E', '.', '+', '-', JSON_INFINITY[0], JSON_NAN[0]: - // assume numeric - v, e := p.readNumeric() - return v, DOUBLE, e - default: - e := fmt.Errorf("Expected element in list but found '%s' while parsing JSON.", string(c)) - return nil, VOID, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - e = fmt.Errorf("Cannot read a single element while parsing JSON.") - return nil, VOID, NewTProtocolExceptionWithType(INVALID_DATA, e) - -} - -func (p *TSimpleJSONProtocol) readIfNull() (bool, error) { - cont := true - for cont { - b, _ := p.reader.Peek(1) - if len(b) < 1 { - return false, nil - } - switch b[0] { - default: - return false, nil - case JSON_NULL[0]: - cont = false - break - case ' ', '\n', '\r', '\t': - p.reader.ReadByte() - break - } - } - if p.safePeekContains(JSON_NULL) { - p.reader.Read(make([]byte, len(JSON_NULL))) - return true, nil - } - return false, nil -} - -func (p *TSimpleJSONProtocol) readQuoteIfNext() { - b, _ := p.reader.Peek(1) - if len(b) > 0 && b[0] == JSON_QUOTE { - p.reader.ReadByte() - } -} - -func (p *TSimpleJSONProtocol) readNumeric() (Numeric, error) { - isNull, err := p.readIfNull() - if isNull || err != nil { - return NUMERIC_NULL, err - } - hasDecimalPoint := false - nextCanBeSign := true - hasE := false - MAX_LEN := 40 - buf := bytes.NewBuffer(make([]byte, 0, MAX_LEN)) - continueFor := true - inQuotes := false - for continueFor { - c, err := p.reader.ReadByte() - if err != nil { - if err == io.EOF { - break - } - return NUMERIC_NULL, NewTProtocolException(err) - } - switch c { - case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': - buf.WriteByte(c) - nextCanBeSign = false - case '.': - if hasDecimalPoint { - e := fmt.Errorf("Unable to parse number with multiple decimal points '%s.'", buf.String()) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - if hasE { - e := fmt.Errorf("Unable to parse number with decimal points in the exponent '%s.'", buf.String()) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - buf.WriteByte(c) - hasDecimalPoint, nextCanBeSign = true, false - case 'e', 'E': - if hasE { - e := fmt.Errorf("Unable to parse number with multiple exponents '%s%c'", buf.String(), c) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - buf.WriteByte(c) - hasE, nextCanBeSign = true, true - case '-', '+': - if !nextCanBeSign { - e := fmt.Errorf("Negative sign within number") - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - buf.WriteByte(c) - nextCanBeSign = false - case ' ', 0, '\t', '\n', '\r', JSON_RBRACE[0], JSON_RBRACKET[0], JSON_COMMA[0], JSON_COLON[0]: - p.reader.UnreadByte() - continueFor = false - case JSON_NAN[0]: - if buf.Len() == 0 { - buffer := make([]byte, len(JSON_NAN)) - buffer[0] = c - _, e := p.reader.Read(buffer[1:]) - if e != nil { - return NUMERIC_NULL, NewTProtocolException(e) - } - if JSON_NAN != string(buffer) { - e := mismatch(JSON_NAN, string(buffer)) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - if inQuotes { - p.readQuoteIfNext() - } - return NAN, nil - } else { - e := fmt.Errorf("Unable to parse number starting with character '%c'", c) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - case JSON_INFINITY[0]: - if buf.Len() == 0 || (buf.Len() == 1 && buf.Bytes()[0] == '+') { - buffer := make([]byte, len(JSON_INFINITY)) - buffer[0] = c - _, e := p.reader.Read(buffer[1:]) - if e != nil { - return NUMERIC_NULL, NewTProtocolException(e) - } - if JSON_INFINITY != string(buffer) { - e := mismatch(JSON_INFINITY, string(buffer)) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - if inQuotes { - p.readQuoteIfNext() - } - return INFINITY, nil - } else if buf.Len() == 1 && buf.Bytes()[0] == JSON_NEGATIVE_INFINITY[0] { - buffer := make([]byte, len(JSON_NEGATIVE_INFINITY)) - buffer[0] = JSON_NEGATIVE_INFINITY[0] - buffer[1] = c - _, e := p.reader.Read(buffer[2:]) - if e != nil { - return NUMERIC_NULL, NewTProtocolException(e) - } - if JSON_NEGATIVE_INFINITY != string(buffer) { - e := mismatch(JSON_NEGATIVE_INFINITY, string(buffer)) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - if inQuotes { - p.readQuoteIfNext() - } - return NEGATIVE_INFINITY, nil - } else { - e := fmt.Errorf("Unable to parse number starting with character '%c' due to existing buffer %s", c, buf.String()) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - case JSON_QUOTE: - if !inQuotes { - inQuotes = true - } else { - break - } - default: - e := fmt.Errorf("Unable to parse number starting with character '%c'", c) - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - } - if buf.Len() == 0 { - e := fmt.Errorf("Unable to parse number from empty string ''") - return NUMERIC_NULL, NewTProtocolExceptionWithType(INVALID_DATA, e) - } - return NewNumericFromJSONString(buf.String(), false), nil -} - -// Safely peeks into the buffer, reading only what is necessary -func (p *TSimpleJSONProtocol) safePeekContains(b []byte) bool { - for i := 0; i < len(b); i++ { - a, _ := p.reader.Peek(i + 1) - if len(a) == 0 || a[i] != b[i] { - return false - } - } - return true -} - -// Reset the context stack to its initial state. -func (p *TSimpleJSONProtocol) resetContextStack() { - p.parseContextStack = []int{int(_CONTEXT_IN_TOPLEVEL)} - p.dumpContext = []int{int(_CONTEXT_IN_TOPLEVEL)} -} - -func (p *TSimpleJSONProtocol) write(b []byte) (int, error) { - n, err := p.writer.Write(b) - if err != nil { - p.writer.Reset(p.trans) // THRIFT-3735 - } - return n, err -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/simple_server.go b/vendor/github.com/apache/thrift/lib/go/thrift/simple_server.go deleted file mode 100644 index 603580251..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/simple_server.go +++ /dev/null @@ -1,227 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "log" - "runtime/debug" - "sync" - "sync/atomic" -) - -/* - * This is not a typical TSimpleServer as it is not blocked after accept a socket. - * It is more like a TThreadedServer that can handle different connections in different goroutines. - * This will work if golang user implements a conn-pool like thing in client side. - */ -type TSimpleServer struct { - closed int32 - wg sync.WaitGroup - mu sync.Mutex - - processorFactory TProcessorFactory - serverTransport TServerTransport - inputTransportFactory TTransportFactory - outputTransportFactory TTransportFactory - inputProtocolFactory TProtocolFactory - outputProtocolFactory TProtocolFactory -} - -func NewTSimpleServer2(processor TProcessor, serverTransport TServerTransport) *TSimpleServer { - return NewTSimpleServerFactory2(NewTProcessorFactory(processor), serverTransport) -} - -func NewTSimpleServer4(processor TProcessor, serverTransport TServerTransport, transportFactory TTransportFactory, protocolFactory TProtocolFactory) *TSimpleServer { - return NewTSimpleServerFactory4(NewTProcessorFactory(processor), - serverTransport, - transportFactory, - protocolFactory, - ) -} - -func NewTSimpleServer6(processor TProcessor, serverTransport TServerTransport, inputTransportFactory TTransportFactory, outputTransportFactory TTransportFactory, inputProtocolFactory TProtocolFactory, outputProtocolFactory TProtocolFactory) *TSimpleServer { - return NewTSimpleServerFactory6(NewTProcessorFactory(processor), - serverTransport, - inputTransportFactory, - outputTransportFactory, - inputProtocolFactory, - outputProtocolFactory, - ) -} - -func NewTSimpleServerFactory2(processorFactory TProcessorFactory, serverTransport TServerTransport) *TSimpleServer { - return NewTSimpleServerFactory6(processorFactory, - serverTransport, - NewTTransportFactory(), - NewTTransportFactory(), - NewTBinaryProtocolFactoryDefault(), - NewTBinaryProtocolFactoryDefault(), - ) -} - -func NewTSimpleServerFactory4(processorFactory TProcessorFactory, serverTransport TServerTransport, transportFactory TTransportFactory, protocolFactory TProtocolFactory) *TSimpleServer { - return NewTSimpleServerFactory6(processorFactory, - serverTransport, - transportFactory, - transportFactory, - protocolFactory, - protocolFactory, - ) -} - -func NewTSimpleServerFactory6(processorFactory TProcessorFactory, serverTransport TServerTransport, inputTransportFactory TTransportFactory, outputTransportFactory TTransportFactory, inputProtocolFactory TProtocolFactory, outputProtocolFactory TProtocolFactory) *TSimpleServer { - return &TSimpleServer{ - processorFactory: processorFactory, - serverTransport: serverTransport, - inputTransportFactory: inputTransportFactory, - outputTransportFactory: outputTransportFactory, - inputProtocolFactory: inputProtocolFactory, - outputProtocolFactory: outputProtocolFactory, - } -} - -func (p *TSimpleServer) ProcessorFactory() TProcessorFactory { - return p.processorFactory -} - -func (p *TSimpleServer) ServerTransport() TServerTransport { - return p.serverTransport -} - -func (p *TSimpleServer) InputTransportFactory() TTransportFactory { - return p.inputTransportFactory -} - -func (p *TSimpleServer) OutputTransportFactory() TTransportFactory { - return p.outputTransportFactory -} - -func (p *TSimpleServer) InputProtocolFactory() TProtocolFactory { - return p.inputProtocolFactory -} - -func (p *TSimpleServer) OutputProtocolFactory() TProtocolFactory { - return p.outputProtocolFactory -} - -func (p *TSimpleServer) Listen() error { - return p.serverTransport.Listen() -} - -func (p *TSimpleServer) innerAccept() (int32, error) { - client, err := p.serverTransport.Accept() - p.mu.Lock() - defer p.mu.Unlock() - closed := atomic.LoadInt32(&p.closed) - if closed != 0 { - return closed, nil - } - if err != nil { - return 0, err - } - if client != nil { - p.wg.Add(1) - go func() { - defer p.wg.Done() - if err := p.processRequests(client); err != nil { - log.Println("error processing request:", err) - } - }() - } - return 0, nil -} - -func (p *TSimpleServer) AcceptLoop() error { - for { - closed, err := p.innerAccept() - if err != nil { - return err - } - if closed != 0 { - return nil - } - } -} - -func (p *TSimpleServer) Serve() error { - err := p.Listen() - if err != nil { - return err - } - p.AcceptLoop() - return nil -} - -func (p *TSimpleServer) Stop() error { - p.mu.Lock() - defer p.mu.Unlock() - if atomic.LoadInt32(&p.closed) != 0 { - return nil - } - atomic.StoreInt32(&p.closed, 1) - p.serverTransport.Interrupt() - p.wg.Wait() - return nil -} - -func (p *TSimpleServer) processRequests(client TTransport) error { - processor := p.processorFactory.GetProcessor(client) - inputTransport, err := p.inputTransportFactory.GetTransport(client) - if err != nil { - return err - } - outputTransport, err := p.outputTransportFactory.GetTransport(client) - if err != nil { - return err - } - inputProtocol := p.inputProtocolFactory.GetProtocol(inputTransport) - outputProtocol := p.outputProtocolFactory.GetProtocol(outputTransport) - defer func() { - if e := recover(); e != nil { - log.Printf("panic in processor: %s: %s", e, debug.Stack()) - } - }() - - if inputTransport != nil { - defer inputTransport.Close() - } - if outputTransport != nil { - defer outputTransport.Close() - } - for { - if atomic.LoadInt32(&p.closed) != 0 { - return nil - } - - ok, err := processor.Process(defaultCtx, inputProtocol, outputProtocol) - if err, ok := err.(TTransportException); ok && err.TypeId() == END_OF_FILE { - return nil - } else if err != nil { - return err - } - if err, ok := err.(TApplicationException); ok && err.TypeId() == UNKNOWN_METHOD { - continue - } - if !ok { - break - } - } - return nil -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/socket.go b/vendor/github.com/apache/thrift/lib/go/thrift/socket.go deleted file mode 100644 index 885427965..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/socket.go +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "net" - "time" -) - -type TSocket struct { - conn net.Conn - addr net.Addr - timeout time.Duration -} - -// NewTSocket creates a net.Conn-backed TTransport, given a host and port -// -// Example: -// trans, err := thrift.NewTSocket("localhost:9090") -func NewTSocket(hostPort string) (*TSocket, error) { - return NewTSocketTimeout(hostPort, 0) -} - -// NewTSocketTimeout creates a net.Conn-backed TTransport, given a host and port -// it also accepts a timeout as a time.Duration -func NewTSocketTimeout(hostPort string, timeout time.Duration) (*TSocket, error) { - //conn, err := net.DialTimeout(network, address, timeout) - addr, err := net.ResolveTCPAddr("tcp", hostPort) - if err != nil { - return nil, err - } - return NewTSocketFromAddrTimeout(addr, timeout), nil -} - -// Creates a TSocket from a net.Addr -func NewTSocketFromAddrTimeout(addr net.Addr, timeout time.Duration) *TSocket { - return &TSocket{addr: addr, timeout: timeout} -} - -// Creates a TSocket from an existing net.Conn -func NewTSocketFromConnTimeout(conn net.Conn, timeout time.Duration) *TSocket { - return &TSocket{conn: conn, addr: conn.RemoteAddr(), timeout: timeout} -} - -// Sets the socket timeout -func (p *TSocket) SetTimeout(timeout time.Duration) error { - p.timeout = timeout - return nil -} - -func (p *TSocket) pushDeadline(read, write bool) { - var t time.Time - if p.timeout > 0 { - t = time.Now().Add(time.Duration(p.timeout)) - } - if read && write { - p.conn.SetDeadline(t) - } else if read { - p.conn.SetReadDeadline(t) - } else if write { - p.conn.SetWriteDeadline(t) - } -} - -// Connects the socket, creating a new socket object if necessary. -func (p *TSocket) Open() error { - if p.IsOpen() { - return NewTTransportException(ALREADY_OPEN, "Socket already connected.") - } - if p.addr == nil { - return NewTTransportException(NOT_OPEN, "Cannot open nil address.") - } - if len(p.addr.Network()) == 0 { - return NewTTransportException(NOT_OPEN, "Cannot open bad network name.") - } - if len(p.addr.String()) == 0 { - return NewTTransportException(NOT_OPEN, "Cannot open bad address.") - } - var err error - if p.conn, err = net.DialTimeout(p.addr.Network(), p.addr.String(), p.timeout); err != nil { - return NewTTransportException(NOT_OPEN, err.Error()) - } - return nil -} - -// Retrieve the underlying net.Conn -func (p *TSocket) Conn() net.Conn { - return p.conn -} - -// Returns true if the connection is open -func (p *TSocket) IsOpen() bool { - if p.conn == nil { - return false - } - return true -} - -// Closes the socket. -func (p *TSocket) Close() error { - // Close the socket - if p.conn != nil { - err := p.conn.Close() - if err != nil { - return err - } - p.conn = nil - } - return nil -} - -//Returns the remote address of the socket. -func (p *TSocket) Addr() net.Addr { - return p.addr -} - -func (p *TSocket) Read(buf []byte) (int, error) { - if !p.IsOpen() { - return 0, NewTTransportException(NOT_OPEN, "Connection not open") - } - p.pushDeadline(true, false) - n, err := p.conn.Read(buf) - return n, NewTTransportExceptionFromError(err) -} - -func (p *TSocket) Write(buf []byte) (int, error) { - if !p.IsOpen() { - return 0, NewTTransportException(NOT_OPEN, "Connection not open") - } - p.pushDeadline(false, true) - return p.conn.Write(buf) -} - -func (p *TSocket) Flush(ctx context.Context) error { - return nil -} - -func (p *TSocket) Interrupt() error { - if !p.IsOpen() { - return nil - } - return p.conn.Close() -} - -func (p *TSocket) RemainingBytes() (num_bytes uint64) { - const maxSize = ^uint64(0) - return maxSize // the thruth is, we just don't know unless framed is used -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/ssl_server_socket.go b/vendor/github.com/apache/thrift/lib/go/thrift/ssl_server_socket.go deleted file mode 100644 index 907afca32..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/ssl_server_socket.go +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "crypto/tls" - "net" - "time" -) - -type TSSLServerSocket struct { - listener net.Listener - addr net.Addr - clientTimeout time.Duration - interrupted bool - cfg *tls.Config -} - -func NewTSSLServerSocket(listenAddr string, cfg *tls.Config) (*TSSLServerSocket, error) { - return NewTSSLServerSocketTimeout(listenAddr, cfg, 0) -} - -func NewTSSLServerSocketTimeout(listenAddr string, cfg *tls.Config, clientTimeout time.Duration) (*TSSLServerSocket, error) { - if cfg.MinVersion == 0 { - cfg.MinVersion = tls.VersionTLS10 - } - addr, err := net.ResolveTCPAddr("tcp", listenAddr) - if err != nil { - return nil, err - } - return &TSSLServerSocket{addr: addr, clientTimeout: clientTimeout, cfg: cfg}, nil -} - -func (p *TSSLServerSocket) Listen() error { - if p.IsListening() { - return nil - } - l, err := tls.Listen(p.addr.Network(), p.addr.String(), p.cfg) - if err != nil { - return err - } - p.listener = l - return nil -} - -func (p *TSSLServerSocket) Accept() (TTransport, error) { - if p.interrupted { - return nil, errTransportInterrupted - } - if p.listener == nil { - return nil, NewTTransportException(NOT_OPEN, "No underlying server socket") - } - conn, err := p.listener.Accept() - if err != nil { - return nil, NewTTransportExceptionFromError(err) - } - return NewTSSLSocketFromConnTimeout(conn, p.cfg, p.clientTimeout), nil -} - -// Checks whether the socket is listening. -func (p *TSSLServerSocket) IsListening() bool { - return p.listener != nil -} - -// Connects the socket, creating a new socket object if necessary. -func (p *TSSLServerSocket) Open() error { - if p.IsListening() { - return NewTTransportException(ALREADY_OPEN, "Server socket already open") - } - if l, err := tls.Listen(p.addr.Network(), p.addr.String(), p.cfg); err != nil { - return err - } else { - p.listener = l - } - return nil -} - -func (p *TSSLServerSocket) Addr() net.Addr { - return p.addr -} - -func (p *TSSLServerSocket) Close() error { - defer func() { - p.listener = nil - }() - if p.IsListening() { - return p.listener.Close() - } - return nil -} - -func (p *TSSLServerSocket) Interrupt() error { - p.interrupted = true - return nil -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/ssl_socket.go b/vendor/github.com/apache/thrift/lib/go/thrift/ssl_socket.go deleted file mode 100644 index ba6337726..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/ssl_socket.go +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "crypto/tls" - "net" - "time" -) - -type TSSLSocket struct { - conn net.Conn - // hostPort contains host:port (e.g. "asdf.com:12345"). The field is - // only valid if addr is nil. - hostPort string - // addr is nil when hostPort is not "", and is only used when the - // TSSLSocket is constructed from a net.Addr. - addr net.Addr - timeout time.Duration - cfg *tls.Config -} - -// NewTSSLSocket creates a net.Conn-backed TTransport, given a host and port and tls Configuration -// -// Example: -// trans, err := thrift.NewTSSLSocket("localhost:9090", nil) -func NewTSSLSocket(hostPort string, cfg *tls.Config) (*TSSLSocket, error) { - return NewTSSLSocketTimeout(hostPort, cfg, 0) -} - -// NewTSSLSocketTimeout creates a net.Conn-backed TTransport, given a host and port -// it also accepts a tls Configuration and a timeout as a time.Duration -func NewTSSLSocketTimeout(hostPort string, cfg *tls.Config, timeout time.Duration) (*TSSLSocket, error) { - if cfg.MinVersion == 0 { - cfg.MinVersion = tls.VersionTLS10 - } - return &TSSLSocket{hostPort: hostPort, timeout: timeout, cfg: cfg}, nil -} - -// Creates a TSSLSocket from a net.Addr -func NewTSSLSocketFromAddrTimeout(addr net.Addr, cfg *tls.Config, timeout time.Duration) *TSSLSocket { - return &TSSLSocket{addr: addr, timeout: timeout, cfg: cfg} -} - -// Creates a TSSLSocket from an existing net.Conn -func NewTSSLSocketFromConnTimeout(conn net.Conn, cfg *tls.Config, timeout time.Duration) *TSSLSocket { - return &TSSLSocket{conn: conn, addr: conn.RemoteAddr(), timeout: timeout, cfg: cfg} -} - -// Sets the socket timeout -func (p *TSSLSocket) SetTimeout(timeout time.Duration) error { - p.timeout = timeout - return nil -} - -func (p *TSSLSocket) pushDeadline(read, write bool) { - var t time.Time - if p.timeout > 0 { - t = time.Now().Add(time.Duration(p.timeout)) - } - if read && write { - p.conn.SetDeadline(t) - } else if read { - p.conn.SetReadDeadline(t) - } else if write { - p.conn.SetWriteDeadline(t) - } -} - -// Connects the socket, creating a new socket object if necessary. -func (p *TSSLSocket) Open() error { - var err error - // If we have a hostname, we need to pass the hostname to tls.Dial for - // certificate hostname checks. - if p.hostPort != "" { - if p.conn, err = tls.DialWithDialer(&net.Dialer{ - Timeout: p.timeout}, "tcp", p.hostPort, p.cfg); err != nil { - return NewTTransportException(NOT_OPEN, err.Error()) - } - } else { - if p.IsOpen() { - return NewTTransportException(ALREADY_OPEN, "Socket already connected.") - } - if p.addr == nil { - return NewTTransportException(NOT_OPEN, "Cannot open nil address.") - } - if len(p.addr.Network()) == 0 { - return NewTTransportException(NOT_OPEN, "Cannot open bad network name.") - } - if len(p.addr.String()) == 0 { - return NewTTransportException(NOT_OPEN, "Cannot open bad address.") - } - if p.conn, err = tls.DialWithDialer(&net.Dialer{ - Timeout: p.timeout}, p.addr.Network(), p.addr.String(), p.cfg); err != nil { - return NewTTransportException(NOT_OPEN, err.Error()) - } - } - return nil -} - -// Retrieve the underlying net.Conn -func (p *TSSLSocket) Conn() net.Conn { - return p.conn -} - -// Returns true if the connection is open -func (p *TSSLSocket) IsOpen() bool { - if p.conn == nil { - return false - } - return true -} - -// Closes the socket. -func (p *TSSLSocket) Close() error { - // Close the socket - if p.conn != nil { - err := p.conn.Close() - if err != nil { - return err - } - p.conn = nil - } - return nil -} - -func (p *TSSLSocket) Read(buf []byte) (int, error) { - if !p.IsOpen() { - return 0, NewTTransportException(NOT_OPEN, "Connection not open") - } - p.pushDeadline(true, false) - n, err := p.conn.Read(buf) - return n, NewTTransportExceptionFromError(err) -} - -func (p *TSSLSocket) Write(buf []byte) (int, error) { - if !p.IsOpen() { - return 0, NewTTransportException(NOT_OPEN, "Connection not open") - } - p.pushDeadline(false, true) - return p.conn.Write(buf) -} - -func (p *TSSLSocket) Flush(ctx context.Context) error { - return nil -} - -func (p *TSSLSocket) Interrupt() error { - if !p.IsOpen() { - return nil - } - return p.conn.Close() -} - -func (p *TSSLSocket) RemainingBytes() (num_bytes uint64) { - const maxSize = ^uint64(0) - return maxSize // the thruth is, we just don't know unless framed is used -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/transport.go deleted file mode 100644 index ba2738a8d..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/transport.go +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "context" - "errors" - "io" -) - -var errTransportInterrupted = errors.New("Transport Interrupted") - -type Flusher interface { - Flush() (err error) -} - -type ContextFlusher interface { - Flush(ctx context.Context) (err error) -} - -type ReadSizeProvider interface { - RemainingBytes() (num_bytes uint64) -} - -// Encapsulates the I/O layer -type TTransport interface { - io.ReadWriteCloser - ContextFlusher - ReadSizeProvider - - // Opens the transport for communication - Open() error - - // Returns true if the transport is open - IsOpen() bool -} - -type stringWriter interface { - WriteString(s string) (n int, err error) -} - -// This is "enchanced" transport with extra capabilities. You need to use one of these -// to construct protocol. -// Notably, TSocket does not implement this interface, and it is always a mistake to use -// TSocket directly in protocol. -type TRichTransport interface { - io.ReadWriter - io.ByteReader - io.ByteWriter - stringWriter - ContextFlusher - ReadSizeProvider -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/transport_exception.go b/vendor/github.com/apache/thrift/lib/go/thrift/transport_exception.go deleted file mode 100644 index 9505b4461..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/transport_exception.go +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -import ( - "errors" - "io" -) - -type timeoutable interface { - Timeout() bool -} - -// Thrift Transport exception -type TTransportException interface { - TException - TypeId() int - Err() error -} - -const ( - UNKNOWN_TRANSPORT_EXCEPTION = 0 - NOT_OPEN = 1 - ALREADY_OPEN = 2 - TIMED_OUT = 3 - END_OF_FILE = 4 -) - -type tTransportException struct { - typeId int - err error -} - -func (p *tTransportException) TypeId() int { - return p.typeId -} - -func (p *tTransportException) Error() string { - return p.err.Error() -} - -func (p *tTransportException) Err() error { - return p.err -} - -func NewTTransportException(t int, e string) TTransportException { - return &tTransportException{typeId: t, err: errors.New(e)} -} - -func NewTTransportExceptionFromError(e error) TTransportException { - if e == nil { - return nil - } - - if t, ok := e.(TTransportException); ok { - return t - } - - switch v := e.(type) { - case TTransportException: - return v - case timeoutable: - if v.Timeout() { - return &tTransportException{typeId: TIMED_OUT, err: e} - } - } - - if e == io.EOF { - return &tTransportException{typeId: END_OF_FILE, err: e} - } - - return &tTransportException{typeId: UNKNOWN_TRANSPORT_EXCEPTION, err: e} -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/transport_factory.go b/vendor/github.com/apache/thrift/lib/go/thrift/transport_factory.go deleted file mode 100644 index c80580794..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/transport_factory.go +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Factory class used to create wrapped instance of Transports. -// This is used primarily in servers, which get Transports from -// a ServerTransport and then may want to mutate them (i.e. create -// a BufferedTransport from the underlying base transport) -type TTransportFactory interface { - GetTransport(trans TTransport) (TTransport, error) -} - -type tTransportFactory struct{} - -// Return a wrapped instance of the base Transport. -func (p *tTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - return trans, nil -} - -func NewTTransportFactory() TTransportFactory { - return &tTransportFactory{} -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/type.go b/vendor/github.com/apache/thrift/lib/go/thrift/type.go deleted file mode 100644 index 4292ffcad..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/type.go +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package thrift - -// Type constants in the Thrift protocol -type TType byte - -const ( - STOP = 0 - VOID = 1 - BOOL = 2 - BYTE = 3 - I08 = 3 - DOUBLE = 4 - I16 = 6 - I32 = 8 - I64 = 10 - STRING = 11 - UTF7 = 11 - STRUCT = 12 - MAP = 13 - SET = 14 - LIST = 15 - UTF8 = 16 - UTF16 = 17 - //BINARY = 18 wrong and unusued -) - -var typeNames = map[int]string{ - STOP: "STOP", - VOID: "VOID", - BOOL: "BOOL", - BYTE: "BYTE", - DOUBLE: "DOUBLE", - I16: "I16", - I32: "I32", - I64: "I64", - STRING: "STRING", - STRUCT: "STRUCT", - MAP: "MAP", - SET: "SET", - LIST: "LIST", - UTF8: "UTF8", - UTF16: "UTF16", -} - -func (p TType) String() string { - if s, ok := typeNames[int(p)]; ok { - return s - } - return "Unknown" -} diff --git a/vendor/github.com/apache/thrift/lib/go/thrift/zlib_transport.go b/vendor/github.com/apache/thrift/lib/go/thrift/zlib_transport.go deleted file mode 100644 index f3d42673a..000000000 --- a/vendor/github.com/apache/thrift/lib/go/thrift/zlib_transport.go +++ /dev/null @@ -1,132 +0,0 @@ -/* -* Licensed to the Apache Software Foundation (ASF) under one -* or more contributor license agreements. See the NOTICE file -* distributed with this work for additional information -* regarding copyright ownership. The ASF licenses this file -* to you under the Apache License, Version 2.0 (the -* "License"); you may not use this file except in compliance -* with the License. You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, -* software distributed under the License is distributed on an -* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -* KIND, either express or implied. See the License for the -* specific language governing permissions and limitations -* under the License. - */ - -package thrift - -import ( - "compress/zlib" - "context" - "io" - "log" -) - -// TZlibTransportFactory is a factory for TZlibTransport instances -type TZlibTransportFactory struct { - level int - factory TTransportFactory -} - -// TZlibTransport is a TTransport implementation that makes use of zlib compression. -type TZlibTransport struct { - reader io.ReadCloser - transport TTransport - writer *zlib.Writer -} - -// GetTransport constructs a new instance of NewTZlibTransport -func (p *TZlibTransportFactory) GetTransport(trans TTransport) (TTransport, error) { - if p.factory != nil { - // wrap other factory - var err error - trans, err = p.factory.GetTransport(trans) - if err != nil { - return nil, err - } - } - return NewTZlibTransport(trans, p.level) -} - -// NewTZlibTransportFactory constructs a new instance of NewTZlibTransportFactory -func NewTZlibTransportFactory(level int) *TZlibTransportFactory { - return &TZlibTransportFactory{level: level, factory: nil} -} - -// NewTZlibTransportFactory constructs a new instance of TZlibTransportFactory -// as a wrapper over existing transport factory -func NewTZlibTransportFactoryWithFactory(level int, factory TTransportFactory) *TZlibTransportFactory { - return &TZlibTransportFactory{level: level, factory: factory} -} - -// NewTZlibTransport constructs a new instance of TZlibTransport -func NewTZlibTransport(trans TTransport, level int) (*TZlibTransport, error) { - w, err := zlib.NewWriterLevel(trans, level) - if err != nil { - log.Println(err) - return nil, err - } - - return &TZlibTransport{ - writer: w, - transport: trans, - }, nil -} - -// Close closes the reader and writer (flushing any unwritten data) and closes -// the underlying transport. -func (z *TZlibTransport) Close() error { - if z.reader != nil { - if err := z.reader.Close(); err != nil { - return err - } - } - if err := z.writer.Close(); err != nil { - return err - } - return z.transport.Close() -} - -// Flush flushes the writer and its underlying transport. -func (z *TZlibTransport) Flush(ctx context.Context) error { - if err := z.writer.Flush(); err != nil { - return err - } - return z.transport.Flush(ctx) -} - -// IsOpen returns true if the transport is open -func (z *TZlibTransport) IsOpen() bool { - return z.transport.IsOpen() -} - -// Open opens the transport for communication -func (z *TZlibTransport) Open() error { - return z.transport.Open() -} - -func (z *TZlibTransport) Read(p []byte) (int, error) { - if z.reader == nil { - r, err := zlib.NewReader(z.transport) - if err != nil { - return 0, NewTTransportExceptionFromError(err) - } - z.reader = r - } - - return z.reader.Read(p) -} - -// RemainingBytes returns the size in bytes of the data that is still to be -// read. -func (z *TZlibTransport) RemainingBytes() uint64 { - return z.transport.RemainingBytes() -} - -func (z *TZlibTransport) Write(p []byte) (int, error) { - return z.writer.Write(p) -} diff --git a/vendor/github.com/apache/thrift/lib/hs/LICENSE b/vendor/github.com/apache/thrift/lib/hs/LICENSE deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/apache/thrift/lib/hs/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/apache/thrift/tutorial/hs/LICENSE b/vendor/github.com/apache/thrift/tutorial/hs/LICENSE deleted file mode 100644 index 3b6d7d74c..000000000 --- a/vendor/github.com/apache/thrift/tutorial/hs/LICENSE +++ /dev/null @@ -1,239 +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. - --------------------------------------------------- -SOFTWARE DISTRIBUTED WITH THRIFT: - -The Apache Thrift software includes a number of subcomponents with -separate copyright notices and license terms. Your use of the source -code for the these subcomponents is subject to the terms and -conditions of the following licenses. - --------------------------------------------------- -Portions of the following files are licensed under the MIT License: - - lib/erl/src/Makefile.am - -Please see doc/otp-base-license.txt for the full terms of this license. - --------------------------------------------------- -For the aclocal/ax_boost_base.m4 and contrib/fb303/aclocal/ax_boost_base.m4 components: - -# Copyright (c) 2007 Thomas Porschberg -# -# Copying and distribution of this file, with or without -# modification, are permitted in any medium without royalty provided -# the copyright notice and this notice are preserved. - --------------------------------------------------- -For the lib/nodejs/lib/thrift/json_parse.js: - -/* - json_parse.js - 2015-05-02 - Public Domain. - NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. - -*/ -(By Douglas Crockford ) --------------------------------------------------- diff --git a/vendor/github.com/armon/go-proxyproto/LICENSE b/vendor/github.com/armon/go-proxyproto/LICENSE deleted file mode 100644 index 3ed5f4302..000000000 --- a/vendor/github.com/armon/go-proxyproto/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Armon Dadgar - -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/armon/go-proxyproto/protocol.go b/vendor/github.com/armon/go-proxyproto/protocol.go deleted file mode 100644 index 576507294..000000000 --- a/vendor/github.com/armon/go-proxyproto/protocol.go +++ /dev/null @@ -1,244 +0,0 @@ -package proxyproto - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "log" - "net" - "strconv" - "strings" - "sync" - "time" -) - -var ( - // prefix is the string we look for at the start of a connection - // to check if this connection is using the proxy protocol - prefix = []byte("PROXY ") - prefixLen = len(prefix) - - ErrInvalidUpstream = errors.New("upstream connection address not trusted for PROXY information") -) - -// SourceChecker can be used to decide whether to trust the PROXY info or pass -// the original connection address through. If set, the connecting address is -// passed in as an argument. If the function returns an error due to the source -// being disallowed, it should return ErrInvalidUpstream. -// -// Behavior is as follows: -// * If error is not nil, the call to Accept() will fail. If the reason for -// triggering this failure is due to a disallowed source, it should return -// ErrInvalidUpstream. -// * If bool is true, the PROXY-set address is used. -// * If bool is false, the connection's remote address is used, rather than the -// address claimed in the PROXY info. -type SourceChecker func(net.Addr) (bool, error) - -// Listener is used to wrap an underlying listener, -// whose connections may be using the HAProxy Proxy Protocol (version 1). -// If the connection is using the protocol, the RemoteAddr() will return -// the correct client address. -// -// Optionally define ProxyHeaderTimeout to set a maximum time to -// receive the Proxy Protocol Header. Zero means no timeout. -type Listener struct { - Listener net.Listener - ProxyHeaderTimeout time.Duration - SourceCheck SourceChecker -} - -// Conn is used to wrap and underlying connection which -// may be speaking the Proxy Protocol. If it is, the RemoteAddr() will -// return the address of the client instead of the proxy address. -type Conn struct { - bufReader *bufio.Reader - conn net.Conn - dstAddr *net.TCPAddr - srcAddr *net.TCPAddr - useConnRemoteAddr bool - once sync.Once - proxyHeaderTimeout time.Duration -} - -// Accept waits for and returns the next connection to the listener. -func (p *Listener) Accept() (net.Conn, error) { - // Get the underlying connection - conn, err := p.Listener.Accept() - if err != nil { - return nil, err - } - var useConnRemoteAddr bool - if p.SourceCheck != nil { - allowed, err := p.SourceCheck(conn.RemoteAddr()) - if err != nil { - return nil, err - } - if !allowed { - useConnRemoteAddr = true - } - } - newConn := NewConn(conn, p.ProxyHeaderTimeout) - newConn.useConnRemoteAddr = useConnRemoteAddr - return newConn, nil -} - -// Close closes the underlying listener. -func (p *Listener) Close() error { - return p.Listener.Close() -} - -// Addr returns the underlying listener's network address. -func (p *Listener) Addr() net.Addr { - return p.Listener.Addr() -} - -// NewConn is used to wrap a net.Conn that may be speaking -// the proxy protocol into a proxyproto.Conn -func NewConn(conn net.Conn, timeout time.Duration) *Conn { - pConn := &Conn{ - bufReader: bufio.NewReader(conn), - conn: conn, - proxyHeaderTimeout: timeout, - } - return pConn -} - -// Read is check for the proxy protocol header when doing -// the initial scan. If there is an error parsing the header, -// it is returned and the socket is closed. -func (p *Conn) Read(b []byte) (int, error) { - var err error - p.once.Do(func() { err = p.checkPrefix() }) - if err != nil { - return 0, err - } - return p.bufReader.Read(b) -} - -func (p *Conn) Write(b []byte) (int, error) { - return p.conn.Write(b) -} - -func (p *Conn) Close() error { - return p.conn.Close() -} - -func (p *Conn) LocalAddr() net.Addr { - return p.conn.LocalAddr() -} - -// RemoteAddr returns the address of the client if the proxy -// protocol is being used, otherwise just returns the address of -// the socket peer. If there is an error parsing the header, the -// address of the client is not returned, and the socket is closed. -// Once implication of this is that the call could block if the -// client is slow. Using a Deadline is recommended if this is called -// before Read() -func (p *Conn) RemoteAddr() net.Addr { - p.once.Do(func() { - if err := p.checkPrefix(); err != nil && err != io.EOF { - log.Printf("[ERR] Failed to read proxy prefix: %v", err) - p.Close() - p.bufReader = bufio.NewReader(p.conn) - } - }) - if p.srcAddr != nil && !p.useConnRemoteAddr { - return p.srcAddr - } - return p.conn.RemoteAddr() -} - -func (p *Conn) SetDeadline(t time.Time) error { - return p.conn.SetDeadline(t) -} - -func (p *Conn) SetReadDeadline(t time.Time) error { - return p.conn.SetReadDeadline(t) -} - -func (p *Conn) SetWriteDeadline(t time.Time) error { - return p.conn.SetWriteDeadline(t) -} - -func (p *Conn) checkPrefix() error { - if p.proxyHeaderTimeout != 0 { - readDeadLine := time.Now().Add(p.proxyHeaderTimeout) - p.conn.SetReadDeadline(readDeadLine) - defer p.conn.SetReadDeadline(time.Time{}) - } - - // Incrementally check each byte of the prefix - for i := 1; i <= prefixLen; i++ { - inp, err := p.bufReader.Peek(i) - - if err != nil { - if neterr, ok := err.(net.Error); ok && neterr.Timeout() { - return nil - } else { - return err - } - } - - // Check for a prefix mis-match, quit early - if !bytes.Equal(inp, prefix[:i]) { - return nil - } - } - - // Read the header line - header, err := p.bufReader.ReadString('\n') - if err != nil { - p.conn.Close() - return err - } - - // Strip the carriage return and new line - header = header[:len(header)-2] - - // Split on spaces, should be (PROXY ) - parts := strings.Split(header, " ") - if len(parts) != 6 { - p.conn.Close() - return fmt.Errorf("Invalid header line: %s", header) - } - - // Verify the type is known - switch parts[1] { - case "TCP4": - case "TCP6": - default: - p.conn.Close() - return fmt.Errorf("Unhandled address type: %s", parts[1]) - } - - // Parse out the source address - ip := net.ParseIP(parts[2]) - if ip == nil { - p.conn.Close() - return fmt.Errorf("Invalid source ip: %s", parts[2]) - } - port, err := strconv.Atoi(parts[4]) - if err != nil { - p.conn.Close() - return fmt.Errorf("Invalid source port: %s", parts[4]) - } - p.srcAddr = &net.TCPAddr{IP: ip, Port: port} - - // Parse out the destination address - ip = net.ParseIP(parts[3]) - if ip == nil { - p.conn.Close() - return fmt.Errorf("Invalid destination ip: %s", parts[3]) - } - port, err = strconv.Atoi(parts[5]) - if err != nil { - p.conn.Close() - return fmt.Errorf("Invalid destination port: %s", parts[5]) - } - p.dstAddr = &net.TCPAddr{IP: ip, Port: port} - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/LICENSE.txt b/vendor/github.com/aws/aws-sdk-go/LICENSE.txt deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/aws/aws-sdk-go/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/NOTICE.txt b/vendor/github.com/aws/aws-sdk-go/NOTICE.txt deleted file mode 100644 index 5f14d1162..000000000 --- a/vendor/github.com/aws/aws-sdk-go/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/aws/awserr/error.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go deleted file mode 100644 index 56fdfc2bf..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/error.go +++ /dev/null @@ -1,145 +0,0 @@ -// Package awserr represents API error interface accessors for the SDK. -package awserr - -// An Error wraps lower level errors with code, message and an original error. -// The underlying concrete error type may also satisfy other interfaces which -// can be to used to obtain more specific information about the error. -// -// Calling Error() or String() will always include the full information about -// an error based on its underlying type. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Get error details -// log.Println("Error:", awsErr.Code(), awsErr.Message()) -// -// // Prints out full error message, including original error if there was one. -// log.Println("Error:", awsErr.Error()) -// -// // Get original error -// if origErr := awsErr.OrigErr(); origErr != nil { -// // operate on original error. -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type Error interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErr() error -} - -// BatchError is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Deprecated: Replaced with BatchedErrors. Only defined for backwards -// compatibility. -type BatchError interface { - // Satisfy the generic error interface. - error - - // Returns the short phrase depicting the classification of the error. - Code() string - - // Returns the error details message. - Message() string - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// BatchedErrors is a batch of errors which also wraps lower level errors with -// code, message, and original errors. Calling Error() will include all errors -// that occurred in the batch. -// -// Replaces BatchError -type BatchedErrors interface { - // Satisfy the base Error interface. - Error - - // Returns the original error if one was set. Nil is returned if not set. - OrigErrs() []error -} - -// New returns an Error object described by the code, message, and origErr. -// -// If origErr satisfies the Error interface it will not be wrapped within a new -// Error object and will instead be returned. -func New(code, message string, origErr error) Error { - var errs []error - if origErr != nil { - errs = append(errs, origErr) - } - return newBaseError(code, message, errs) -} - -// NewBatchError returns an BatchedErrors with a collection of errors as an -// array of errors. -func NewBatchError(code, message string, errs []error) BatchedErrors { - return newBaseError(code, message, errs) -} - -// A RequestFailure is an interface to extract request failure information from -// an Error such as the request ID of the failed request returned by a service. -// RequestFailures may not always have a requestID value if the request failed -// prior to reaching the service such as a connection error. -// -// Example: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if reqerr, ok := err.(RequestFailure); ok { -// log.Println("Request failed", reqerr.Code(), reqerr.Message(), reqerr.RequestID()) -// } else { -// log.Println("Error:", err.Error()) -// } -// } -// -// Combined with awserr.Error: -// -// output, err := s3manage.Upload(svc, input, opts) -// if err != nil { -// if awsErr, ok := err.(awserr.Error); ok { -// // Generic AWS Error with Code, Message, and original error (if any) -// fmt.Println(awsErr.Code(), awsErr.Message(), awsErr.OrigErr()) -// -// if reqErr, ok := err.(awserr.RequestFailure); ok { -// // A service error occurred -// fmt.Println(reqErr.StatusCode(), reqErr.RequestID()) -// } -// } else { -// fmt.Println(err.Error()) -// } -// } -// -type RequestFailure interface { - Error - - // The status code of the HTTP response. - StatusCode() int - - // The request ID returned by the service for a request failure. This will - // be empty if no request ID is available such as the request failed due - // to a connection error. - RequestID() string -} - -// NewRequestFailure returns a new request error wrapper for the given Error -// provided. -func NewRequestFailure(err Error, statusCode int, reqID string) RequestFailure { - return newRequestError(err, statusCode, reqID) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go b/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go deleted file mode 100644 index 0202a008f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awserr/types.go +++ /dev/null @@ -1,194 +0,0 @@ -package awserr - -import "fmt" - -// SprintError returns a string of the formatted error code. -// -// Both extra and origErr are optional. If they are included their lines -// will be added, but if they are not included their lines will be ignored. -func SprintError(code, message, extra string, origErr error) string { - msg := fmt.Sprintf("%s: %s", code, message) - if extra != "" { - msg = fmt.Sprintf("%s\n\t%s", msg, extra) - } - if origErr != nil { - msg = fmt.Sprintf("%s\ncaused by: %s", msg, origErr.Error()) - } - return msg -} - -// A baseError wraps the code and message which defines an error. It also -// can be used to wrap an original error object. -// -// Should be used as the root for errors satisfying the awserr.Error. Also -// for any error which does not fit into a specific error wrapper type. -type baseError struct { - // Classification of error - code string - - // Detailed information about error - message string - - // Optional original error this error is based off of. Allows building - // chained errors. - errs []error -} - -// newBaseError returns an error object for the code, message, and errors. -// -// code is a short no whitespace phrase depicting the classification of -// the error that is being created. -// -// message is the free flow string containing detailed information about the -// error. -// -// origErrs is the error objects which will be nested under the new errors to -// be returned. -func newBaseError(code, message string, origErrs []error) *baseError { - b := &baseError{ - code: code, - message: message, - errs: origErrs, - } - - return b -} - -// Error returns the string representation of the error. -// -// See ErrorWithExtra for formatting. -// -// Satisfies the error interface. -func (b baseError) Error() string { - size := len(b.errs) - if size > 0 { - return SprintError(b.code, b.message, "", errorList(b.errs)) - } - - return SprintError(b.code, b.message, "", nil) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (b baseError) String() string { - return b.Error() -} - -// Code returns the short phrase depicting the classification of the error. -func (b baseError) Code() string { - return b.code -} - -// Message returns the error details message. -func (b baseError) Message() string { - return b.message -} - -// OrigErr returns the original error if one was set. Nil is returned if no -// error was set. This only returns the first element in the list. If the full -// list is needed, use BatchedErrors. -func (b baseError) OrigErr() error { - switch len(b.errs) { - case 0: - return nil - case 1: - return b.errs[0] - default: - if err, ok := b.errs[0].(Error); ok { - return NewBatchError(err.Code(), err.Message(), b.errs[1:]) - } - return NewBatchError("BatchedErrors", - "multiple errors occurred", b.errs) - } -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (b baseError) OrigErrs() []error { - return b.errs -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError Error - -// A requestError wraps a request or service error. -// -// Composed of baseError for code, message, and original error. -type requestError struct { - awsError - statusCode int - requestID string -} - -// newRequestError returns a wrapped error with additional information for -// request status code, and service requestID. -// -// Should be used to wrap all request which involve service requests. Even if -// the request failed without a service response, but had an HTTP status code -// that may be meaningful. -// -// Also wraps original errors via the baseError. -func newRequestError(err Error, statusCode int, requestID string) *requestError { - return &requestError{ - awsError: err, - statusCode: statusCode, - requestID: requestID, - } -} - -// Error returns the string representation of the error. -// Satisfies the error interface. -func (r requestError) Error() string { - extra := fmt.Sprintf("status code: %d, request id: %s", - r.statusCode, r.requestID) - return SprintError(r.Code(), r.Message(), extra, r.OrigErr()) -} - -// String returns the string representation of the error. -// Alias for Error to satisfy the stringer interface. -func (r requestError) String() string { - return r.Error() -} - -// StatusCode returns the wrapped status code for the error -func (r requestError) StatusCode() int { - return r.statusCode -} - -// RequestID returns the wrapped requestID -func (r requestError) RequestID() string { - return r.requestID -} - -// OrigErrs returns the original errors if one was set. An empty slice is -// returned if no error was set. -func (r requestError) OrigErrs() []error { - if b, ok := r.awsError.(BatchedErrors); ok { - return b.OrigErrs() - } - return []error{r.OrigErr()} -} - -// An error list that satisfies the golang interface -type errorList []error - -// Error returns the string representation of the error. -// -// Satisfies the error interface. -func (e errorList) Error() string { - msg := "" - // How do we want to handle the array size being zero - if size := len(e); size > 0 { - for i := 0; i < size; i++ { - msg += fmt.Sprintf("%s", e[i].Error()) - // We check the next index to see if it is within the slice. - // If it is, then we append a newline. We do this, because unit tests - // could be broken with the additional '\n' - if i+1 < size { - msg += "\n" - } - } - } - return msg -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go deleted file mode 100644 index 1a3d106d5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/copy.go +++ /dev/null @@ -1,108 +0,0 @@ -package awsutil - -import ( - "io" - "reflect" - "time" -) - -// Copy deeply copies a src structure to dst. Useful for copying request and -// response structures. -// -// Can copy between structs of different type, but will only copy fields which -// are assignable, and exist in both structs. Fields which are not assignable, -// or do not exist in both structs are ignored. -func Copy(dst, src interface{}) { - dstval := reflect.ValueOf(dst) - if !dstval.IsValid() { - panic("Copy dst cannot be nil") - } - - rcopy(dstval, reflect.ValueOf(src), true) -} - -// CopyOf returns a copy of src while also allocating the memory for dst. -// src must be a pointer type or this operation will fail. -func CopyOf(src interface{}) (dst interface{}) { - dsti := reflect.New(reflect.TypeOf(src).Elem()) - dst = dsti.Interface() - rcopy(dsti, reflect.ValueOf(src), true) - return -} - -// rcopy performs a recursive copy of values from the source to destination. -// -// root is used to skip certain aspects of the copy which are not valid -// for the root node of a object. -func rcopy(dst, src reflect.Value, root bool) { - if !src.IsValid() { - return - } - - switch src.Kind() { - case reflect.Ptr: - if _, ok := src.Interface().(io.Reader); ok { - if dst.Kind() == reflect.Ptr && dst.Elem().CanSet() { - dst.Elem().Set(src) - } else if dst.CanSet() { - dst.Set(src) - } - } else { - e := src.Type().Elem() - if dst.CanSet() && !src.IsNil() { - if _, ok := src.Interface().(*time.Time); !ok { - dst.Set(reflect.New(e)) - } else { - tempValue := reflect.New(e) - tempValue.Elem().Set(src.Elem()) - // Sets time.Time's unexported values - dst.Set(tempValue) - } - } - if src.Elem().IsValid() { - // Keep the current root state since the depth hasn't changed - rcopy(dst.Elem(), src.Elem(), root) - } - } - case reflect.Struct: - t := dst.Type() - for i := 0; i < t.NumField(); i++ { - name := t.Field(i).Name - srcVal := src.FieldByName(name) - dstVal := dst.FieldByName(name) - if srcVal.IsValid() && dstVal.CanSet() { - rcopy(dstVal, srcVal, false) - } - } - case reflect.Slice: - if src.IsNil() { - break - } - - s := reflect.MakeSlice(src.Type(), src.Len(), src.Cap()) - dst.Set(s) - for i := 0; i < src.Len(); i++ { - rcopy(dst.Index(i), src.Index(i), false) - } - case reflect.Map: - if src.IsNil() { - break - } - - s := reflect.MakeMap(src.Type()) - dst.Set(s) - for _, k := range src.MapKeys() { - v := src.MapIndex(k) - v2 := reflect.New(v.Type()).Elem() - rcopy(v2, v, false) - dst.SetMapIndex(k, v2) - } - default: - // Assign the value if possible. If its not assignable, the value would - // need to be converted and the impact of that may be unexpected, or is - // not compatible with the dst type. - if src.Type().AssignableTo(dst.Type()) { - dst.Set(src) - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go deleted file mode 100644 index 59fa4a558..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/equal.go +++ /dev/null @@ -1,27 +0,0 @@ -package awsutil - -import ( - "reflect" -) - -// DeepEqual returns if the two values are deeply equal like reflect.DeepEqual. -// In addition to this, this method will also dereference the input values if -// possible so the DeepEqual performed will not fail if one parameter is a -// pointer and the other is not. -// -// DeepEqual will not perform indirection of nested values of the input parameters. -func DeepEqual(a, b interface{}) bool { - ra := reflect.Indirect(reflect.ValueOf(a)) - rb := reflect.Indirect(reflect.ValueOf(b)) - - if raValid, rbValid := ra.IsValid(), rb.IsValid(); !raValid && !rbValid { - // If the elements are both nil, and of the same type the are equal - // If they are of different types they are not equal - return reflect.TypeOf(a) == reflect.TypeOf(b) - } else if raValid != rbValid { - // Both values must be valid to be equal - return false - } - - return reflect.DeepEqual(ra.Interface(), rb.Interface()) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go deleted file mode 100644 index 11c52c389..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/path_value.go +++ /dev/null @@ -1,222 +0,0 @@ -package awsutil - -import ( - "reflect" - "regexp" - "strconv" - "strings" - - "github.com/jmespath/go-jmespath" -) - -var indexRe = regexp.MustCompile(`(.+)\[(-?\d+)?\]$`) - -// rValuesAtPath returns a slice of values found in value v. The values -// in v are explored recursively so all nested values are collected. -func rValuesAtPath(v interface{}, path string, createPath, caseSensitive, nilTerm bool) []reflect.Value { - pathparts := strings.Split(path, "||") - if len(pathparts) > 1 { - for _, pathpart := range pathparts { - vals := rValuesAtPath(v, pathpart, createPath, caseSensitive, nilTerm) - if len(vals) > 0 { - return vals - } - } - return nil - } - - values := []reflect.Value{reflect.Indirect(reflect.ValueOf(v))} - components := strings.Split(path, ".") - for len(values) > 0 && len(components) > 0 { - var index *int64 - var indexStar bool - c := strings.TrimSpace(components[0]) - if c == "" { // no actual component, illegal syntax - return nil - } else if caseSensitive && c != "*" && strings.ToLower(c[0:1]) == c[0:1] { - // TODO normalize case for user - return nil // don't support unexported fields - } - - // parse this component - if m := indexRe.FindStringSubmatch(c); m != nil { - c = m[1] - if m[2] == "" { - index = nil - indexStar = true - } else { - i, _ := strconv.ParseInt(m[2], 10, 32) - index = &i - indexStar = false - } - } - - nextvals := []reflect.Value{} - for _, value := range values { - // pull component name out of struct member - if value.Kind() != reflect.Struct { - continue - } - - if c == "*" { // pull all members - for i := 0; i < value.NumField(); i++ { - if f := reflect.Indirect(value.Field(i)); f.IsValid() { - nextvals = append(nextvals, f) - } - } - continue - } - - value = value.FieldByNameFunc(func(name string) bool { - if c == name { - return true - } else if !caseSensitive && strings.ToLower(name) == strings.ToLower(c) { - return true - } - return false - }) - - if nilTerm && value.Kind() == reflect.Ptr && len(components[1:]) == 0 { - if !value.IsNil() { - value.Set(reflect.Zero(value.Type())) - } - return []reflect.Value{value} - } - - if createPath && value.Kind() == reflect.Ptr && value.IsNil() { - // TODO if the value is the terminus it should not be created - // if the value to be set to its position is nil. - value.Set(reflect.New(value.Type().Elem())) - value = value.Elem() - } else { - value = reflect.Indirect(value) - } - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - - if indexStar || index != nil { - nextvals = []reflect.Value{} - for _, valItem := range values { - value := reflect.Indirect(valItem) - if value.Kind() != reflect.Slice { - continue - } - - if indexStar { // grab all indices - for i := 0; i < value.Len(); i++ { - idx := reflect.Indirect(value.Index(i)) - if idx.IsValid() { - nextvals = append(nextvals, idx) - } - } - continue - } - - // pull out index - i := int(*index) - if i >= value.Len() { // check out of bounds - if createPath { - // TODO resize slice - } else { - continue - } - } else if i < 0 { // support negative indexing - i = value.Len() + i - } - value = reflect.Indirect(value.Index(i)) - - if value.Kind() == reflect.Slice || value.Kind() == reflect.Map { - if !createPath && value.IsNil() { - value = reflect.ValueOf(nil) - } - } - - if value.IsValid() { - nextvals = append(nextvals, value) - } - } - values = nextvals - } - - components = components[1:] - } - return values -} - -// ValuesAtPath returns a list of values at the case insensitive lexical -// path inside of a structure. -func ValuesAtPath(i interface{}, path string) ([]interface{}, error) { - result, err := jmespath.Search(path, i) - if err != nil { - return nil, err - } - - v := reflect.ValueOf(result) - if !v.IsValid() || (v.Kind() == reflect.Ptr && v.IsNil()) { - return nil, nil - } - if s, ok := result.([]interface{}); ok { - return s, err - } - if v.Kind() == reflect.Map && v.Len() == 0 { - return nil, nil - } - if v.Kind() == reflect.Slice { - out := make([]interface{}, v.Len()) - for i := 0; i < v.Len(); i++ { - out[i] = v.Index(i).Interface() - } - return out, nil - } - - return []interface{}{result}, nil -} - -// SetValueAtPath sets a value at the case insensitive lexical path inside -// of a structure. -func SetValueAtPath(i interface{}, path string, v interface{}) { - if rvals := rValuesAtPath(i, path, true, false, v == nil); rvals != nil { - for _, rval := range rvals { - if rval.Kind() == reflect.Ptr && rval.IsNil() { - continue - } - setValue(rval, v) - } - } -} - -func setValue(dstVal reflect.Value, src interface{}) { - if dstVal.Kind() == reflect.Ptr { - dstVal = reflect.Indirect(dstVal) - } - srcVal := reflect.ValueOf(src) - - if !srcVal.IsValid() { // src is literal nil - if dstVal.CanAddr() { - // Convert to pointer so that pointer's value can be nil'ed - // dstVal = dstVal.Addr() - } - dstVal.Set(reflect.Zero(dstVal.Type())) - - } else if srcVal.Kind() == reflect.Ptr { - if srcVal.IsNil() { - srcVal = reflect.Zero(dstVal.Type()) - } else { - srcVal = reflect.ValueOf(src).Elem() - } - dstVal.Set(srcVal) - } else { - dstVal.Set(srcVal) - } - -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go deleted file mode 100644 index 710eb432f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/prettify.go +++ /dev/null @@ -1,113 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" -) - -// Prettify returns the string representation of a value. -func Prettify(i interface{}) string { - var buf bytes.Buffer - prettify(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -// prettify will recursively walk value v to build a textual -// representation of the value. -func prettify(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - strtype := v.Type().String() - if strtype == "time.Time" { - fmt.Fprintf(buf, "%s", v.Interface()) - break - } else if strings.HasPrefix(strtype, "io.") { - buf.WriteString("") - break - } - - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice || f.Kind() == reflect.Map) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - prettify(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - strtype := v.Type().String() - if strtype == "[]uint8" { - fmt.Fprintf(buf, " len %d", v.Len()) - break - } - - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - prettify(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - prettify(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - if !v.IsValid() { - fmt.Fprint(buf, "") - return - } - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - case io.ReadSeeker, io.Reader: - format = "buffer(%p)" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go b/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go deleted file mode 100644 index b6432f1a1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/awsutil/string_value.go +++ /dev/null @@ -1,89 +0,0 @@ -package awsutil - -import ( - "bytes" - "fmt" - "reflect" - "strings" -) - -// StringValue returns the string representation of a value. -func StringValue(i interface{}) string { - var buf bytes.Buffer - stringValue(reflect.ValueOf(i), 0, &buf) - return buf.String() -} - -func stringValue(v reflect.Value, indent int, buf *bytes.Buffer) { - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - buf.WriteString("{\n") - - names := []string{} - for i := 0; i < v.Type().NumField(); i++ { - name := v.Type().Field(i).Name - f := v.Field(i) - if name[0:1] == strings.ToLower(name[0:1]) { - continue // ignore unexported fields - } - if (f.Kind() == reflect.Ptr || f.Kind() == reflect.Slice) && f.IsNil() { - continue // ignore unset fields - } - names = append(names, name) - } - - for i, n := range names { - val := v.FieldByName(n) - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(n + ": ") - stringValue(val, indent+2, buf) - - if i < len(names)-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - case reflect.Slice: - nl, id, id2 := "", "", "" - if v.Len() > 3 { - nl, id, id2 = "\n", strings.Repeat(" ", indent), strings.Repeat(" ", indent+2) - } - buf.WriteString("[" + nl) - for i := 0; i < v.Len(); i++ { - buf.WriteString(id2) - stringValue(v.Index(i), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString("," + nl) - } - } - - buf.WriteString(nl + id + "]") - case reflect.Map: - buf.WriteString("{\n") - - for i, k := range v.MapKeys() { - buf.WriteString(strings.Repeat(" ", indent+2)) - buf.WriteString(k.String() + ": ") - stringValue(v.MapIndex(k), indent+2, buf) - - if i < v.Len()-1 { - buf.WriteString(",\n") - } - } - - buf.WriteString("\n" + strings.Repeat(" ", indent) + "}") - default: - format := "%v" - switch v.Interface().(type) { - case string: - format = "%q" - } - fmt.Fprintf(buf, format, v.Interface()) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go b/vendor/github.com/aws/aws-sdk-go/aws/client/client.go deleted file mode 100644 index 3271a18e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/client.go +++ /dev/null @@ -1,96 +0,0 @@ -package client - -import ( - "fmt" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Config provides configuration to a service client instance. -type Config struct { - Config *aws.Config - Handlers request.Handlers - Endpoint string - SigningRegion string - SigningName string - - // States that the signing name did not come from a modeled source but - // was derived based on other data. Used by service client constructors - // to determine if the signin name can be overriden based on metadata the - // service has. - SigningNameDerived bool -} - -// ConfigProvider provides a generic way for a service client to receive -// the ClientConfig without circular dependencies. -type ConfigProvider interface { - ClientConfig(serviceName string, cfgs ...*aws.Config) Config -} - -// ConfigNoResolveEndpointProvider same as ConfigProvider except it will not -// resolve the endpoint automatically. The service client's endpoint must be -// provided via the aws.Config.Endpoint field. -type ConfigNoResolveEndpointProvider interface { - ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) Config -} - -// A Client implements the base client request and response handling -// used by all service clients. -type Client struct { - request.Retryer - metadata.ClientInfo - - Config aws.Config - Handlers request.Handlers -} - -// New will return a pointer to a new initialized service client. -func New(cfg aws.Config, info metadata.ClientInfo, handlers request.Handlers, options ...func(*Client)) *Client { - svc := &Client{ - Config: cfg, - ClientInfo: info, - Handlers: handlers.Copy(), - } - - switch retryer, ok := cfg.Retryer.(request.Retryer); { - case ok: - svc.Retryer = retryer - case cfg.Retryer != nil && cfg.Logger != nil: - s := fmt.Sprintf("WARNING: %T does not implement request.Retryer; using DefaultRetryer instead", cfg.Retryer) - cfg.Logger.Log(s) - fallthrough - default: - maxRetries := aws.IntValue(cfg.MaxRetries) - if cfg.MaxRetries == nil || maxRetries == aws.UseServiceDefaultRetries { - maxRetries = 3 - } - svc.Retryer = DefaultRetryer{NumMaxRetries: maxRetries} - } - - svc.AddDebugHandlers() - - for _, option := range options { - option(svc) - } - - return svc -} - -// NewRequest returns a new Request pointer for the service API -// operation and parameters. -func (c *Client) NewRequest(operation *request.Operation, params interface{}, data interface{}) *request.Request { - return request.New(c.Config, c.ClientInfo, c.Handlers, c.Retryer, operation, params, data) -} - -// AddDebugHandlers injects debug logging handlers into the service to log request -// debug information. -func (c *Client) AddDebugHandlers() { - if !c.Config.LogLevel.AtLeast(aws.LogDebug) { - return - } - - c.Handlers.Send.PushFrontNamed(request.NamedHandler{Name: "awssdk.client.LogRequest", Fn: logRequest}) - c.Handlers.Send.PushBackNamed(request.NamedHandler{Name: "awssdk.client.LogResponse", Fn: logResponse}) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go deleted file mode 100644 index a397b0d04..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/default_retryer.go +++ /dev/null @@ -1,116 +0,0 @@ -package client - -import ( - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkrand" -) - -// DefaultRetryer implements basic retry logic using exponential backoff for -// most services. If you want to implement custom retry logic, implement the -// request.Retryer interface or create a structure type that composes this -// struct and override the specific methods. For example, to override only -// the MaxRetries method: -// -// type retryer struct { -// client.DefaultRetryer -// } -// -// // This implementation always has 100 max retries -// func (d retryer) MaxRetries() int { return 100 } -type DefaultRetryer struct { - NumMaxRetries int -} - -// MaxRetries returns the number of maximum returns the service will use to make -// an individual API request. -func (d DefaultRetryer) MaxRetries() int { - return d.NumMaxRetries -} - -// RetryRules returns the delay duration before retrying this request again -func (d DefaultRetryer) RetryRules(r *request.Request) time.Duration { - // Set the upper limit of delay in retrying at ~five minutes - minTime := 30 - throttle := d.shouldThrottle(r) - if throttle { - if delay, ok := getRetryDelay(r); ok { - return delay - } - - minTime = 500 - } - - retryCount := r.RetryCount - if throttle && retryCount > 8 { - retryCount = 8 - } else if retryCount > 13 { - retryCount = 13 - } - - delay := (1 << uint(retryCount)) * (sdkrand.SeededRand.Intn(minTime) + minTime) - return time.Duration(delay) * time.Millisecond -} - -// ShouldRetry returns true if the request should be retried. -func (d DefaultRetryer) ShouldRetry(r *request.Request) bool { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable != nil { - return *r.Retryable - } - - if r.HTTPResponse.StatusCode >= 500 && r.HTTPResponse.StatusCode != 501 { - return true - } - return r.IsErrorRetryable() || d.shouldThrottle(r) -} - -// ShouldThrottle returns true if the request should be throttled. -func (d DefaultRetryer) shouldThrottle(r *request.Request) bool { - switch r.HTTPResponse.StatusCode { - case 429: - case 502: - case 503: - case 504: - default: - return r.IsErrorThrottle() - } - - return true -} - -// This will look in the Retry-After header, RFC 7231, for how long -// it will wait before attempting another request -func getRetryDelay(r *request.Request) (time.Duration, bool) { - if !canUseRetryAfterHeader(r) { - return 0, false - } - - delayStr := r.HTTPResponse.Header.Get("Retry-After") - if len(delayStr) == 0 { - return 0, false - } - - delay, err := strconv.Atoi(delayStr) - if err != nil { - return 0, false - } - - return time.Duration(delay) * time.Second, true -} - -// Will look at the status code to see if the retry header pertains to -// the status code. -func canUseRetryAfterHeader(r *request.Request) bool { - switch r.HTTPResponse.StatusCode { - case 429: - case 503: - default: - return false - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go deleted file mode 100644 index e223c54cc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/logger.go +++ /dev/null @@ -1,112 +0,0 @@ -package client - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http/httputil" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -const logReqMsg = `DEBUG: Request %s/%s Details: ----[ REQUEST POST-SIGN ]----------------------------- -%s ------------------------------------------------------` - -const logReqErrMsg = `DEBUG ERROR: Request %s/%s: ----[ REQUEST DUMP ERROR ]----------------------------- -%s -------------------------------------------------------` - -type logWriter struct { - // Logger is what we will use to log the payload of a response. - Logger aws.Logger - // buf stores the contents of what has been read - buf *bytes.Buffer -} - -func (logger *logWriter) Write(b []byte) (int, error) { - return logger.buf.Write(b) -} - -type teeReaderCloser struct { - // io.Reader will be a tee reader that is used during logging. - // This structure will read from a body and write the contents to a logger. - io.Reader - // Source is used just to close when we are done reading. - Source io.ReadCloser -} - -func (reader *teeReaderCloser) Close() error { - return reader.Source.Close() -} - -func logRequest(r *request.Request) { - logBody := r.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) - bodySeekable := aws.IsReaderSeekable(r.Body) - dumpedBody, err := httputil.DumpRequestOut(r.HTTPRequest, logBody) - if err != nil { - r.Config.Logger.Log(fmt.Sprintf(logReqErrMsg, r.ClientInfo.ServiceName, r.Operation.Name, err)) - return - } - - if logBody { - if !bodySeekable { - r.SetReaderBody(aws.ReadSeekCloser(r.HTTPRequest.Body)) - } - // Reset the request body because dumpRequest will re-wrap the r.HTTPRequest's - // Body as a NoOpCloser and will not be reset after read by the HTTP - // client reader. - r.ResetBody() - } - - r.Config.Logger.Log(fmt.Sprintf(logReqMsg, r.ClientInfo.ServiceName, r.Operation.Name, string(dumpedBody))) -} - -const logRespMsg = `DEBUG: Response %s/%s Details: ----[ RESPONSE ]-------------------------------------- -%s ------------------------------------------------------` - -const logRespErrMsg = `DEBUG ERROR: Response %s/%s: ----[ RESPONSE DUMP ERROR ]----------------------------- -%s ------------------------------------------------------` - -func logResponse(r *request.Request) { - lw := &logWriter{r.Config.Logger, bytes.NewBuffer(nil)} - r.HTTPResponse.Body = &teeReaderCloser{ - Reader: io.TeeReader(r.HTTPResponse.Body, lw), - Source: r.HTTPResponse.Body, - } - - handlerFn := func(req *request.Request) { - body, err := httputil.DumpResponse(req.HTTPResponse, false) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - - b, err := ioutil.ReadAll(lw.buf) - if err != nil { - lw.Logger.Log(fmt.Sprintf(logRespErrMsg, req.ClientInfo.ServiceName, req.Operation.Name, err)) - return - } - lw.Logger.Log(fmt.Sprintf(logRespMsg, req.ClientInfo.ServiceName, req.Operation.Name, string(body))) - if req.Config.LogLevel.Matches(aws.LogDebugWithHTTPBody) { - lw.Logger.Log(string(b)) - } - } - - const handlerName = "awsdk.client.LogResponse.ResponseBody" - - r.Handlers.Unmarshal.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) - r.Handlers.UnmarshalError.SetBackNamed(request.NamedHandler{ - Name: handlerName, Fn: handlerFn, - }) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go b/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go deleted file mode 100644 index 4778056dd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/client/metadata/client_info.go +++ /dev/null @@ -1,12 +0,0 @@ -package metadata - -// ClientInfo wraps immutable data from the client.Client structure. -type ClientInfo struct { - ServiceName string - APIVersion string - Endpoint string - SigningName string - SigningRegion string - JSONVersion string - TargetPrefix string -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/config.go b/vendor/github.com/aws/aws-sdk-go/aws/config.go deleted file mode 100644 index 5421b5d4e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/config.go +++ /dev/null @@ -1,492 +0,0 @@ -package aws - -import ( - "net/http" - "time" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/endpoints" -) - -// UseServiceDefaultRetries instructs the config to use the service's own -// default number of retries. This will be the default action if -// Config.MaxRetries is nil also. -const UseServiceDefaultRetries = -1 - -// RequestRetryer is an alias for a type that implements the request.Retryer -// interface. -type RequestRetryer interface{} - -// A Config provides service configuration for service clients. By default, -// all clients will use the defaults.DefaultConfig tructure. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(&aws.Config{ -// MaxRetries: aws.Int(3), -// })) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, &aws.Config{ -// Region: aws.String("us-west-2"), -// }) -type Config struct { - // Enables verbose error printing of all credential chain errors. - // Should be used when wanting to see all errors while attempting to - // retrieve credentials. - CredentialsChainVerboseErrors *bool - - // The credentials object to use when signing requests. Defaults to a - // chain of credential providers to search for credentials in environment - // variables, shared credential file, and EC2 Instance Roles. - Credentials *credentials.Credentials - - // An optional endpoint URL (hostname only or fully qualified URI) - // that overrides the default generated endpoint for a client. Set this - // to `""` to use the default generated endpoint. - // - // @note You must still provide a `Region` value when specifying an - // endpoint for a client. - Endpoint *string - - // The resolver to use for looking up endpoints for AWS service clients - // to use based on region. - EndpointResolver endpoints.Resolver - - // EnforceShouldRetryCheck is used in the AfterRetryHandler to always call - // ShouldRetry regardless of whether or not if request.Retryable is set. - // This will utilize ShouldRetry method of custom retryers. If EnforceShouldRetryCheck - // is not set, then ShouldRetry will only be called if request.Retryable is nil. - // Proper handling of the request.Retryable field is important when setting this field. - EnforceShouldRetryCheck *bool - - // The region to send requests to. This parameter is required and must - // be configured globally or on a per-client basis unless otherwise - // noted. A full list of regions is found in the "Regions and Endpoints" - // document. - // - // @see http://docs.aws.amazon.com/general/latest/gr/rande.html - // AWS Regions and Endpoints - Region *string - - // Set this to `true` to disable SSL when sending requests. Defaults - // to `false`. - DisableSSL *bool - - // The HTTP client to use when sending requests. Defaults to - // `http.DefaultClient`. - HTTPClient *http.Client - - // An integer value representing the logging level. The default log level - // is zero (LogOff), which represents no logging. To enable logging set - // to a LogLevel Value. - LogLevel *LogLevelType - - // The logger writer interface to write logging messages to. Defaults to - // standard out. - Logger Logger - - // The maximum number of times that a request will be retried for failures. - // Defaults to -1, which defers the max retry setting to the service - // specific configuration. - MaxRetries *int - - // Retryer guides how HTTP requests should be retried in case of - // recoverable failures. - // - // When nil or the value does not implement the request.Retryer interface, - // the client.DefaultRetryer will be used. - // - // When both Retryer and MaxRetries are non-nil, the former is used and - // the latter ignored. - // - // To set the Retryer field in a type-safe manner and with chaining, use - // the request.WithRetryer helper function: - // - // cfg := request.WithRetryer(aws.NewConfig(), myRetryer) - // - Retryer RequestRetryer - - // Disables semantic parameter validation, which validates input for - // missing required fields and/or other semantic request input errors. - DisableParamValidation *bool - - // Disables the computation of request and response checksums, e.g., - // CRC32 checksums in Amazon DynamoDB. - DisableComputeChecksums *bool - - // Set this to `true` to force the request to use path-style addressing, - // i.e., `http://s3.amazonaws.com/BUCKET/KEY`. By default, the S3 client - // will use virtual hosted bucket addressing when possible - // (`http://BUCKET.s3.amazonaws.com/KEY`). - // - // @note This configuration option is specific to the Amazon S3 service. - // @see http://docs.aws.amazon.com/AmazonS3/latest/dev/VirtualHosting.html - // Amazon S3: Virtual Hosting of Buckets - S3ForcePathStyle *bool - - // Set this to `true` to disable the SDK adding the `Expect: 100-Continue` - // header to PUT requests over 2MB of content. 100-Continue instructs the - // HTTP client not to send the body until the service responds with a - // `continue` status. This is useful to prevent sending the request body - // until after the request is authenticated, and validated. - // - // http://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html - // - // 100-Continue is only enabled for Go 1.6 and above. See `http.Transport`'s - // `ExpectContinueTimeout` for information on adjusting the continue wait - // timeout. https://golang.org/pkg/net/http/#Transport - // - // You should use this flag to disble 100-Continue if you experience issues - // with proxies or third party S3 compatible services. - S3Disable100Continue *bool - - // Set this to `true` to enable S3 Accelerate feature. For all operations - // compatible with S3 Accelerate will use the accelerate endpoint for - // requests. Requests not compatible will fall back to normal S3 requests. - // - // The bucket must be enable for accelerate to be used with S3 client with - // accelerate enabled. If the bucket is not enabled for accelerate an error - // will be returned. The bucket name must be DNS compatible to also work - // with accelerate. - S3UseAccelerate *bool - - // S3DisableContentMD5Validation config option is temporarily disabled, - // For S3 GetObject API calls, #1837. - // - // Set this to `true` to disable the S3 service client from automatically - // adding the ContentMD5 to S3 Object Put and Upload API calls. This option - // will also disable the SDK from performing object ContentMD5 validation - // on GetObject API calls. - S3DisableContentMD5Validation *bool - - // Set this to `true` to disable the EC2Metadata client from overriding the - // default http.Client's Timeout. This is helpful if you do not want the - // EC2Metadata client to create a new http.Client. This options is only - // meaningful if you're not already using a custom HTTP client with the - // SDK. Enabled by default. - // - // Must be set and provided to the session.NewSession() in order to disable - // the EC2Metadata overriding the timeout for default credentials chain. - // - // Example: - // sess := session.Must(session.NewSession(aws.NewConfig() - // .WithEC2MetadataDiableTimeoutOverride(true))) - // - // svc := s3.New(sess) - // - EC2MetadataDisableTimeoutOverride *bool - - // Instructs the endpoint to be generated for a service client to - // be the dual stack endpoint. The dual stack endpoint will support - // both IPv4 and IPv6 addressing. - // - // Setting this for a service which does not support dual stack will fail - // to make requets. It is not recommended to set this value on the session - // as it will apply to all service clients created with the session. Even - // services which don't support dual stack endpoints. - // - // If the Endpoint config value is also provided the UseDualStack flag - // will be ignored. - // - // Only supported with. - // - // sess := session.Must(session.NewSession()) - // - // svc := s3.New(sess, &aws.Config{ - // UseDualStack: aws.Bool(true), - // }) - UseDualStack *bool - - // SleepDelay is an override for the func the SDK will call when sleeping - // during the lifecycle of a request. Specifically this will be used for - // request delays. This value should only be used for testing. To adjust - // the delay of a request see the aws/client.DefaultRetryer and - // aws/request.Retryer. - // - // SleepDelay will prevent any Context from being used for canceling retry - // delay of an API operation. It is recommended to not use SleepDelay at all - // and specify a Retryer instead. - SleepDelay func(time.Duration) - - // DisableRestProtocolURICleaning will not clean the URL path when making rest protocol requests. - // Will default to false. This would only be used for empty directory names in s3 requests. - // - // Example: - // sess := session.Must(session.NewSession(&aws.Config{ - // DisableRestProtocolURICleaning: aws.Bool(true), - // })) - // - // svc := s3.New(sess) - // out, err := svc.GetObject(&s3.GetObjectInput { - // Bucket: aws.String("bucketname"), - // Key: aws.String("//foo//bar//moo"), - // }) - DisableRestProtocolURICleaning *bool -} - -// NewConfig returns a new Config pointer that can be chained with builder -// methods to set multiple configuration values inline without using pointers. -// -// // Create Session with MaxRetry configuration to be shared by multiple -// // service clients. -// sess := session.Must(session.NewSession(aws.NewConfig(). -// WithMaxRetries(3), -// )) -// -// // Create S3 service client with a specific Region. -// svc := s3.New(sess, aws.NewConfig(). -// WithRegion("us-west-2"), -// ) -func NewConfig() *Config { - return &Config{} -} - -// WithCredentialsChainVerboseErrors sets a config verbose errors boolean and returning -// a Config pointer. -func (c *Config) WithCredentialsChainVerboseErrors(verboseErrs bool) *Config { - c.CredentialsChainVerboseErrors = &verboseErrs - return c -} - -// WithCredentials sets a config Credentials value returning a Config pointer -// for chaining. -func (c *Config) WithCredentials(creds *credentials.Credentials) *Config { - c.Credentials = creds - return c -} - -// WithEndpoint sets a config Endpoint value returning a Config pointer for -// chaining. -func (c *Config) WithEndpoint(endpoint string) *Config { - c.Endpoint = &endpoint - return c -} - -// WithEndpointResolver sets a config EndpointResolver value returning a -// Config pointer for chaining. -func (c *Config) WithEndpointResolver(resolver endpoints.Resolver) *Config { - c.EndpointResolver = resolver - return c -} - -// WithRegion sets a config Region value returning a Config pointer for -// chaining. -func (c *Config) WithRegion(region string) *Config { - c.Region = ®ion - return c -} - -// WithDisableSSL sets a config DisableSSL value returning a Config pointer -// for chaining. -func (c *Config) WithDisableSSL(disable bool) *Config { - c.DisableSSL = &disable - return c -} - -// WithHTTPClient sets a config HTTPClient value returning a Config pointer -// for chaining. -func (c *Config) WithHTTPClient(client *http.Client) *Config { - c.HTTPClient = client - return c -} - -// WithMaxRetries sets a config MaxRetries value returning a Config pointer -// for chaining. -func (c *Config) WithMaxRetries(max int) *Config { - c.MaxRetries = &max - return c -} - -// WithDisableParamValidation sets a config DisableParamValidation value -// returning a Config pointer for chaining. -func (c *Config) WithDisableParamValidation(disable bool) *Config { - c.DisableParamValidation = &disable - return c -} - -// WithDisableComputeChecksums sets a config DisableComputeChecksums value -// returning a Config pointer for chaining. -func (c *Config) WithDisableComputeChecksums(disable bool) *Config { - c.DisableComputeChecksums = &disable - return c -} - -// WithLogLevel sets a config LogLevel value returning a Config pointer for -// chaining. -func (c *Config) WithLogLevel(level LogLevelType) *Config { - c.LogLevel = &level - return c -} - -// WithLogger sets a config Logger value returning a Config pointer for -// chaining. -func (c *Config) WithLogger(logger Logger) *Config { - c.Logger = logger - return c -} - -// WithS3ForcePathStyle sets a config S3ForcePathStyle value returning a Config -// pointer for chaining. -func (c *Config) WithS3ForcePathStyle(force bool) *Config { - c.S3ForcePathStyle = &force - return c -} - -// WithS3Disable100Continue sets a config S3Disable100Continue value returning -// a Config pointer for chaining. -func (c *Config) WithS3Disable100Continue(disable bool) *Config { - c.S3Disable100Continue = &disable - return c -} - -// WithS3UseAccelerate sets a config S3UseAccelerate value returning a Config -// pointer for chaining. -func (c *Config) WithS3UseAccelerate(enable bool) *Config { - c.S3UseAccelerate = &enable - return c - -} - -// WithS3DisableContentMD5Validation sets a config -// S3DisableContentMD5Validation value returning a Config pointer for chaining. -func (c *Config) WithS3DisableContentMD5Validation(enable bool) *Config { - c.S3DisableContentMD5Validation = &enable - return c - -} - -// WithUseDualStack sets a config UseDualStack value returning a Config -// pointer for chaining. -func (c *Config) WithUseDualStack(enable bool) *Config { - c.UseDualStack = &enable - return c -} - -// WithEC2MetadataDisableTimeoutOverride sets a config EC2MetadataDisableTimeoutOverride value -// returning a Config pointer for chaining. -func (c *Config) WithEC2MetadataDisableTimeoutOverride(enable bool) *Config { - c.EC2MetadataDisableTimeoutOverride = &enable - return c -} - -// WithSleepDelay overrides the function used to sleep while waiting for the -// next retry. Defaults to time.Sleep. -func (c *Config) WithSleepDelay(fn func(time.Duration)) *Config { - c.SleepDelay = fn - return c -} - -// MergeIn merges the passed in configs into the existing config object. -func (c *Config) MergeIn(cfgs ...*Config) { - for _, other := range cfgs { - mergeInConfig(c, other) - } -} - -func mergeInConfig(dst *Config, other *Config) { - if other == nil { - return - } - - if other.CredentialsChainVerboseErrors != nil { - dst.CredentialsChainVerboseErrors = other.CredentialsChainVerboseErrors - } - - if other.Credentials != nil { - dst.Credentials = other.Credentials - } - - if other.Endpoint != nil { - dst.Endpoint = other.Endpoint - } - - if other.EndpointResolver != nil { - dst.EndpointResolver = other.EndpointResolver - } - - if other.Region != nil { - dst.Region = other.Region - } - - if other.DisableSSL != nil { - dst.DisableSSL = other.DisableSSL - } - - if other.HTTPClient != nil { - dst.HTTPClient = other.HTTPClient - } - - if other.LogLevel != nil { - dst.LogLevel = other.LogLevel - } - - if other.Logger != nil { - dst.Logger = other.Logger - } - - if other.MaxRetries != nil { - dst.MaxRetries = other.MaxRetries - } - - if other.Retryer != nil { - dst.Retryer = other.Retryer - } - - if other.DisableParamValidation != nil { - dst.DisableParamValidation = other.DisableParamValidation - } - - if other.DisableComputeChecksums != nil { - dst.DisableComputeChecksums = other.DisableComputeChecksums - } - - if other.S3ForcePathStyle != nil { - dst.S3ForcePathStyle = other.S3ForcePathStyle - } - - if other.S3Disable100Continue != nil { - dst.S3Disable100Continue = other.S3Disable100Continue - } - - if other.S3UseAccelerate != nil { - dst.S3UseAccelerate = other.S3UseAccelerate - } - - if other.S3DisableContentMD5Validation != nil { - dst.S3DisableContentMD5Validation = other.S3DisableContentMD5Validation - } - - if other.UseDualStack != nil { - dst.UseDualStack = other.UseDualStack - } - - if other.EC2MetadataDisableTimeoutOverride != nil { - dst.EC2MetadataDisableTimeoutOverride = other.EC2MetadataDisableTimeoutOverride - } - - if other.SleepDelay != nil { - dst.SleepDelay = other.SleepDelay - } - - if other.DisableRestProtocolURICleaning != nil { - dst.DisableRestProtocolURICleaning = other.DisableRestProtocolURICleaning - } - - if other.EnforceShouldRetryCheck != nil { - dst.EnforceShouldRetryCheck = other.EnforceShouldRetryCheck - } -} - -// Copy will return a shallow copy of the Config object. If any additional -// configurations are provided they will be merged into the new config returned. -func (c *Config) Copy(cfgs ...*Config) *Config { - dst := &Config{} - dst.MergeIn(c) - - for _, cfg := range cfgs { - dst.MergeIn(cfg) - } - - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context.go b/vendor/github.com/aws/aws-sdk-go/aws/context.go deleted file mode 100644 index 79f426853..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context.go +++ /dev/null @@ -1,71 +0,0 @@ -package aws - -import ( - "time" -) - -// Context is an copy of the Go v1.7 stdlib's context.Context interface. -// It is represented as a SDK interface to enable you to use the "WithContext" -// API methods with Go v1.6 and a Context type such as golang.org/x/net/context. -// -// See https://golang.org/pkg/context on how to use contexts. -type Context interface { - // Deadline returns the time when work done on behalf of this context - // should be canceled. Deadline returns ok==false when no deadline is - // set. Successive calls to Deadline return the same results. - Deadline() (deadline time.Time, ok bool) - - // Done returns a channel that's closed when work done on behalf of this - // context should be canceled. Done may return nil if this context can - // never be canceled. Successive calls to Done return the same value. - Done() <-chan struct{} - - // Err returns a non-nil error value after Done is closed. Err returns - // Canceled if the context was canceled or DeadlineExceeded if the - // context's deadline passed. No other values for Err are defined. - // After Done is closed, successive calls to Err return the same value. - Err() error - - // Value returns the value associated with this context for key, or nil - // if no value is associated with key. Successive calls to Value with - // the same key returns the same result. - // - // Use context values only for request-scoped data that transits - // processes and API boundaries, not for passing optional parameters to - // functions. - Value(key interface{}) interface{} -} - -// BackgroundContext returns a context that will never be canceled, has no -// values, and no deadline. This context is used by the SDK to provide -// backwards compatibility with non-context API operations and functionality. -// -// Go 1.6 and before: -// This context function is equivalent to context.Background in the Go stdlib. -// -// Go 1.7 and later: -// The context returned will be the value returned by context.Background() -// -// See https://golang.org/pkg/context for more information on Contexts. -func BackgroundContext() Context { - return backgroundCtx -} - -// SleepWithContext will wait for the timer duration to expire, or the context -// is canceled. Which ever happens first. If the context is canceled the Context's -// error will be returned. -// -// Expects Context to always return a non-nil error if the Done channel is closed. -func SleepWithContext(ctx Context, dur time.Duration) error { - t := time.NewTimer(dur) - defer t.Stop() - - select { - case <-t.C: - break - case <-ctx.Done(): - return ctx.Err() - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go deleted file mode 100644 index 8fdda5303..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_6.go +++ /dev/null @@ -1,41 +0,0 @@ -// +build !go1.7 - -package aws - -import "time" - -// An emptyCtx is a copy of the Go 1.7 context.emptyCtx type. This is copied to -// provide a 1.6 and 1.5 safe version of context that is compatible with Go -// 1.7's Context. -// -// An emptyCtx is never canceled, has no values, and has no deadline. It is not -// struct{}, since vars of this type must have distinct addresses. -type emptyCtx int - -func (*emptyCtx) Deadline() (deadline time.Time, ok bool) { - return -} - -func (*emptyCtx) Done() <-chan struct{} { - return nil -} - -func (*emptyCtx) Err() error { - return nil -} - -func (*emptyCtx) Value(key interface{}) interface{} { - return nil -} - -func (e *emptyCtx) String() string { - switch e { - case backgroundCtx: - return "aws.BackgroundContext" - } - return "unknown empty Context" -} - -var ( - backgroundCtx = new(emptyCtx) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go deleted file mode 100644 index 064f75c92..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/context_1_7.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build go1.7 - -package aws - -import "context" - -var ( - backgroundCtx = context.Background() -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go b/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go deleted file mode 100644 index ff5d58e06..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/convert_types.go +++ /dev/null @@ -1,387 +0,0 @@ -package aws - -import "time" - -// String returns a pointer to the string value passed in. -func String(v string) *string { - return &v -} - -// StringValue returns the value of the string pointer passed in or -// "" if the pointer is nil. -func StringValue(v *string) string { - if v != nil { - return *v - } - return "" -} - -// StringSlice converts a slice of string values into a slice of -// string pointers -func StringSlice(src []string) []*string { - dst := make([]*string, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// StringValueSlice converts a slice of string pointers into a slice of -// string values -func StringValueSlice(src []*string) []string { - dst := make([]string, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// StringMap converts a string map of string values into a string -// map of string pointers -func StringMap(src map[string]string) map[string]*string { - dst := make(map[string]*string) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// StringValueMap converts a string map of string pointers into a string -// map of string values -func StringValueMap(src map[string]*string) map[string]string { - dst := make(map[string]string) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Bool returns a pointer to the bool value passed in. -func Bool(v bool) *bool { - return &v -} - -// BoolValue returns the value of the bool pointer passed in or -// false if the pointer is nil. -func BoolValue(v *bool) bool { - if v != nil { - return *v - } - return false -} - -// BoolSlice converts a slice of bool values into a slice of -// bool pointers -func BoolSlice(src []bool) []*bool { - dst := make([]*bool, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// BoolValueSlice converts a slice of bool pointers into a slice of -// bool values -func BoolValueSlice(src []*bool) []bool { - dst := make([]bool, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// BoolMap converts a string map of bool values into a string -// map of bool pointers -func BoolMap(src map[string]bool) map[string]*bool { - dst := make(map[string]*bool) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// BoolValueMap converts a string map of bool pointers into a string -// map of bool values -func BoolValueMap(src map[string]*bool) map[string]bool { - dst := make(map[string]bool) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int returns a pointer to the int value passed in. -func Int(v int) *int { - return &v -} - -// IntValue returns the value of the int pointer passed in or -// 0 if the pointer is nil. -func IntValue(v *int) int { - if v != nil { - return *v - } - return 0 -} - -// IntSlice converts a slice of int values into a slice of -// int pointers -func IntSlice(src []int) []*int { - dst := make([]*int, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// IntValueSlice converts a slice of int pointers into a slice of -// int values -func IntValueSlice(src []*int) []int { - dst := make([]int, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// IntMap converts a string map of int values into a string -// map of int pointers -func IntMap(src map[string]int) map[string]*int { - dst := make(map[string]*int) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// IntValueMap converts a string map of int pointers into a string -// map of int values -func IntValueMap(src map[string]*int) map[string]int { - dst := make(map[string]int) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Int64 returns a pointer to the int64 value passed in. -func Int64(v int64) *int64 { - return &v -} - -// Int64Value returns the value of the int64 pointer passed in or -// 0 if the pointer is nil. -func Int64Value(v *int64) int64 { - if v != nil { - return *v - } - return 0 -} - -// Int64Slice converts a slice of int64 values into a slice of -// int64 pointers -func Int64Slice(src []int64) []*int64 { - dst := make([]*int64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Int64ValueSlice converts a slice of int64 pointers into a slice of -// int64 values -func Int64ValueSlice(src []*int64) []int64 { - dst := make([]int64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Int64Map converts a string map of int64 values into a string -// map of int64 pointers -func Int64Map(src map[string]int64) map[string]*int64 { - dst := make(map[string]*int64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Int64ValueMap converts a string map of int64 pointers into a string -// map of int64 values -func Int64ValueMap(src map[string]*int64) map[string]int64 { - dst := make(map[string]int64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Float64 returns a pointer to the float64 value passed in. -func Float64(v float64) *float64 { - return &v -} - -// Float64Value returns the value of the float64 pointer passed in or -// 0 if the pointer is nil. -func Float64Value(v *float64) float64 { - if v != nil { - return *v - } - return 0 -} - -// Float64Slice converts a slice of float64 values into a slice of -// float64 pointers -func Float64Slice(src []float64) []*float64 { - dst := make([]*float64, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// Float64ValueSlice converts a slice of float64 pointers into a slice of -// float64 values -func Float64ValueSlice(src []*float64) []float64 { - dst := make([]float64, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// Float64Map converts a string map of float64 values into a string -// map of float64 pointers -func Float64Map(src map[string]float64) map[string]*float64 { - dst := make(map[string]*float64) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// Float64ValueMap converts a string map of float64 pointers into a string -// map of float64 values -func Float64ValueMap(src map[string]*float64) map[string]float64 { - dst := make(map[string]float64) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} - -// Time returns a pointer to the time.Time value passed in. -func Time(v time.Time) *time.Time { - return &v -} - -// TimeValue returns the value of the time.Time pointer passed in or -// time.Time{} if the pointer is nil. -func TimeValue(v *time.Time) time.Time { - if v != nil { - return *v - } - return time.Time{} -} - -// SecondsTimeValue converts an int64 pointer to a time.Time value -// representing seconds since Epoch or time.Time{} if the pointer is nil. -func SecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix((*v / 1000), 0) - } - return time.Time{} -} - -// MillisecondsTimeValue converts an int64 pointer to a time.Time value -// representing milliseconds sinch Epoch or time.Time{} if the pointer is nil. -func MillisecondsTimeValue(v *int64) time.Time { - if v != nil { - return time.Unix(0, (*v * 1000000)) - } - return time.Time{} -} - -// TimeUnixMilli returns a Unix timestamp in milliseconds from "January 1, 1970 UTC". -// The result is undefined if the Unix time cannot be represented by an int64. -// Which includes calling TimeUnixMilli on a zero Time is undefined. -// -// This utility is useful for service API's such as CloudWatch Logs which require -// their unix time values to be in milliseconds. -// -// See Go stdlib https://golang.org/pkg/time/#Time.UnixNano for more information. -func TimeUnixMilli(t time.Time) int64 { - return t.UnixNano() / int64(time.Millisecond/time.Nanosecond) -} - -// TimeSlice converts a slice of time.Time values into a slice of -// time.Time pointers -func TimeSlice(src []time.Time) []*time.Time { - dst := make([]*time.Time, len(src)) - for i := 0; i < len(src); i++ { - dst[i] = &(src[i]) - } - return dst -} - -// TimeValueSlice converts a slice of time.Time pointers into a slice of -// time.Time values -func TimeValueSlice(src []*time.Time) []time.Time { - dst := make([]time.Time, len(src)) - for i := 0; i < len(src); i++ { - if src[i] != nil { - dst[i] = *(src[i]) - } - } - return dst -} - -// TimeMap converts a string map of time.Time values into a string -// map of time.Time pointers -func TimeMap(src map[string]time.Time) map[string]*time.Time { - dst := make(map[string]*time.Time) - for k, val := range src { - v := val - dst[k] = &v - } - return dst -} - -// TimeValueMap converts a string map of time.Time pointers into a string -// map of time.Time values -func TimeValueMap(src map[string]*time.Time) map[string]time.Time { - dst := make(map[string]time.Time) - for k, val := range src { - if val != nil { - dst[k] = *val - } - } - return dst -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go deleted file mode 100644 index cfcddf3dc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/handlers.go +++ /dev/null @@ -1,228 +0,0 @@ -package corehandlers - -import ( - "bytes" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "regexp" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// Interface for matching types which also have a Len method. -type lener interface { - Len() int -} - -// BuildContentLengthHandler builds the content length of a request based on the body, -// or will use the HTTPRequest.Header's "Content-Length" if defined. If unable -// to determine request body length and no "Content-Length" was specified it will panic. -// -// The Content-Length will only be added to the request if the length of the body -// is greater than 0. If the body is empty or the current `Content-Length` -// header is <= 0, the header will also be stripped. -var BuildContentLengthHandler = request.NamedHandler{Name: "core.BuildContentLengthHandler", Fn: func(r *request.Request) { - var length int64 - - if slength := r.HTTPRequest.Header.Get("Content-Length"); slength != "" { - length, _ = strconv.ParseInt(slength, 10, 64) - } else { - if r.Body != nil { - var err error - length, err = aws.SeekerLen(r.Body) - if err != nil { - r.Error = awserr.New(request.ErrCodeSerialization, "failed to get request body's length", err) - return - } - } - } - - if length > 0 { - r.HTTPRequest.ContentLength = length - r.HTTPRequest.Header.Set("Content-Length", fmt.Sprintf("%d", length)) - } else { - r.HTTPRequest.ContentLength = 0 - r.HTTPRequest.Header.Del("Content-Length") - } -}} - -var reStatusCode = regexp.MustCompile(`^(\d{3})`) - -// ValidateReqSigHandler is a request handler to ensure that the request's -// signature doesn't expire before it is sent. This can happen when a request -// is built and signed significantly before it is sent. Or significant delays -// occur when retrying requests that would cause the signature to expire. -var ValidateReqSigHandler = request.NamedHandler{ - Name: "core.ValidateReqSigHandler", - Fn: func(r *request.Request) { - // Unsigned requests are not signed - if r.Config.Credentials == credentials.AnonymousCredentials { - return - } - - signedTime := r.Time - if !r.LastSignedAt.IsZero() { - signedTime = r.LastSignedAt - } - - // 10 minutes to allow for some clock skew/delays in transmission. - // Would be improved with aws/aws-sdk-go#423 - if signedTime.Add(10 * time.Minute).After(time.Now()) { - return - } - - fmt.Println("request expired, resigning") - r.Sign() - }, -} - -// SendHandler is a request handler to send service request using HTTP client. -var SendHandler = request.NamedHandler{ - Name: "core.SendHandler", - Fn: func(r *request.Request) { - sender := sendFollowRedirects - if r.DisableFollowRedirects { - sender = sendWithoutFollowRedirects - } - - if request.NoBody == r.HTTPRequest.Body { - // Strip off the request body if the NoBody reader was used as a - // place holder for a request body. This prevents the SDK from - // making requests with a request body when it would be invalid - // to do so. - // - // Use a shallow copy of the http.Request to ensure the race condition - // of transport on Body will not trigger - reqOrig, reqCopy := r.HTTPRequest, *r.HTTPRequest - reqCopy.Body = nil - r.HTTPRequest = &reqCopy - defer func() { - r.HTTPRequest = reqOrig - }() - } - - var err error - r.HTTPResponse, err = sender(r) - if err != nil { - handleSendError(r, err) - } - }, -} - -func sendFollowRedirects(r *request.Request) (*http.Response, error) { - return r.Config.HTTPClient.Do(r.HTTPRequest) -} - -func sendWithoutFollowRedirects(r *request.Request) (*http.Response, error) { - transport := r.Config.HTTPClient.Transport - if transport == nil { - transport = http.DefaultTransport - } - - return transport.RoundTrip(r.HTTPRequest) -} - -func handleSendError(r *request.Request, err error) { - // Prevent leaking if an HTTPResponse was returned. Clean up - // the body. - if r.HTTPResponse != nil { - r.HTTPResponse.Body.Close() - } - // Capture the case where url.Error is returned for error processing - // response. e.g. 301 without location header comes back as string - // error and r.HTTPResponse is nil. Other URL redirect errors will - // comeback in a similar method. - if e, ok := err.(*url.Error); ok && e.Err != nil { - if s := reStatusCode.FindStringSubmatch(e.Err.Error()); s != nil { - code, _ := strconv.ParseInt(s[1], 10, 64) - r.HTTPResponse = &http.Response{ - StatusCode: int(code), - Status: http.StatusText(int(code)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - return - } - } - if r.HTTPResponse == nil { - // Add a dummy request response object to ensure the HTTPResponse - // value is consistent. - r.HTTPResponse = &http.Response{ - StatusCode: int(0), - Status: http.StatusText(int(0)), - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), - } - } - // Catch all other request errors. - r.Error = awserr.New("RequestError", "send request failed", err) - r.Retryable = aws.Bool(true) // network errors are retryable - - // Override the error with a context canceled error, if that was canceled. - ctx := r.Context() - select { - case <-ctx.Done(): - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", ctx.Err()) - r.Retryable = aws.Bool(false) - default: - } -} - -// ValidateResponseHandler is a request handler to validate service response. -var ValidateResponseHandler = request.NamedHandler{Name: "core.ValidateResponseHandler", Fn: func(r *request.Request) { - if r.HTTPResponse.StatusCode == 0 || r.HTTPResponse.StatusCode >= 300 { - // this may be replaced by an UnmarshalError handler - r.Error = awserr.New("UnknownError", "unknown error", nil) - } -}} - -// AfterRetryHandler performs final checks to determine if the request should -// be retried and how long to delay. -var AfterRetryHandler = request.NamedHandler{Name: "core.AfterRetryHandler", Fn: func(r *request.Request) { - // If one of the other handlers already set the retry state - // we don't want to override it based on the service's state - if r.Retryable == nil || aws.BoolValue(r.Config.EnforceShouldRetryCheck) { - r.Retryable = aws.Bool(r.ShouldRetry(r)) - } - - if r.WillRetry() { - r.RetryDelay = r.RetryRules(r) - - if sleepFn := r.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(r.RetryDelay) - } else if err := aws.SleepWithContext(r.Context(), r.RetryDelay); err != nil { - r.Error = awserr.New(request.CanceledErrorCode, - "request context canceled", err) - r.Retryable = aws.Bool(false) - return - } - - // when the expired token exception occurs the credentials - // need to be expired locally so that the next request to - // get credentials will trigger a credentials refresh. - if r.IsErrorExpired() { - r.Config.Credentials.Expire() - } - - r.RetryCount++ - r.Error = nil - } -}} - -// ValidateEndpointHandler is a request handler to validate a request had the -// appropriate Region and Endpoint set. Will set r.Error if the endpoint or -// region is not valid. -var ValidateEndpointHandler = request.NamedHandler{Name: "core.ValidateEndpointHandler", Fn: func(r *request.Request) { - if r.ClientInfo.SigningRegion == "" && aws.StringValue(r.Config.Region) == "" { - r.Error = aws.ErrMissingRegion - } else if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go deleted file mode 100644 index 7d50b1557..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/param_validator.go +++ /dev/null @@ -1,17 +0,0 @@ -package corehandlers - -import "github.com/aws/aws-sdk-go/aws/request" - -// ValidateParametersHandler is a request handler to validate the input parameters. -// Validating parameters only has meaning if done prior to the request being sent. -var ValidateParametersHandler = request.NamedHandler{Name: "core.ValidateParametersHandler", Fn: func(r *request.Request) { - if !r.ParamsFilled() { - return - } - - if v, ok := r.Params.(request.Validator); ok { - if err := v.Validate(); err != nil { - r.Error = err - } - } -}} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go b/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go deleted file mode 100644 index a15f496bc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/corehandlers/user_agent.go +++ /dev/null @@ -1,37 +0,0 @@ -package corehandlers - -import ( - "os" - "runtime" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// SDKVersionUserAgentHandler is a request handler for adding the SDK Version -// to the user agent. -var SDKVersionUserAgentHandler = request.NamedHandler{ - Name: "core.SDKVersionUserAgentHandler", - Fn: request.MakeAddToUserAgentHandler(aws.SDKName, aws.SDKVersion, - runtime.Version(), runtime.GOOS, runtime.GOARCH), -} - -const execEnvVar = `AWS_EXECUTION_ENV` -const execEnvUAKey = `exec_env` - -// AddHostExecEnvUserAgentHander is a request handler appending the SDK's -// execution environment to the user agent. -// -// If the environment variable AWS_EXECUTION_ENV is set, its value will be -// appended to the user agent string. -var AddHostExecEnvUserAgentHander = request.NamedHandler{ - Name: "core.AddHostExecEnvUserAgentHander", - Fn: func(r *request.Request) { - v := os.Getenv(execEnvVar) - if len(v) == 0 { - return - } - - request.AddToUserAgent(r, execEnvUAKey+"/"+v) - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go deleted file mode 100644 index f298d6596..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/chain_provider.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var ( - // ErrNoValidProvidersFoundInChain Is returned when there are no valid - // providers in the ChainProvider. - // - // This has been deprecated. For verbose error messaging set - // aws.Config.CredentialsChainVerboseErrors to true - // - // @readonly - ErrNoValidProvidersFoundInChain = awserr.New("NoCredentialProviders", - `no valid providers in chain. Deprecated. - For verbose messaging see aws.Config.CredentialsChainVerboseErrors`, - nil) -) - -// A ChainProvider will search for a provider which returns credentials -// and cache that provider until Retrieve is called again. -// -// The ChainProvider provides a way of chaining multiple providers together -// which will pick the first available using priority order of the Providers -// in the list. -// -// If none of the Providers retrieve valid credentials Value, ChainProvider's -// Retrieve() will return the error ErrNoValidProvidersFoundInChain. -// -// If a Provider is found which returns valid credentials Value ChainProvider -// will cache that Provider for all calls to IsExpired(), until Retrieve is -// called again. -// -// Example of ChainProvider to be used with an EnvProvider and EC2RoleProvider. -// In this example EnvProvider will first check if any credentials are available -// via the environment variables. If there are none ChainProvider will check -// the next Provider in the list, EC2RoleProvider in this case. If EC2RoleProvider -// does not return any credentials ChainProvider will return the error -// ErrNoValidProvidersFoundInChain -// -// creds := credentials.NewChainCredentials( -// []credentials.Provider{ -// &credentials.EnvProvider{}, -// &ec2rolecreds.EC2RoleProvider{ -// Client: ec2metadata.New(sess), -// }, -// }) -// -// // Usage of ChainCredentials with aws.Config -// svc := ec2.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: creds, -// }))) -// -type ChainProvider struct { - Providers []Provider - curr Provider - VerboseErrors bool -} - -// NewChainCredentials returns a pointer to a new Credentials object -// wrapping a chain of providers. -func NewChainCredentials(providers []Provider) *Credentials { - return NewCredentials(&ChainProvider{ - Providers: append([]Provider{}, providers...), - }) -} - -// Retrieve returns the credentials value or error if no provider returned -// without error. -// -// If a provider is found it will be cached and any calls to IsExpired() -// will return the expired state of the cached provider. -func (c *ChainProvider) Retrieve() (Value, error) { - var errs []error - for _, p := range c.Providers { - creds, err := p.Retrieve() - if err == nil { - c.curr = p - return creds, nil - } - errs = append(errs, err) - } - c.curr = nil - - var err error - err = ErrNoValidProvidersFoundInChain - if c.VerboseErrors { - err = awserr.NewBatchError("NoCredentialProviders", "no valid providers in chain", errs) - } - return Value{}, err -} - -// IsExpired will returned the expired state of the currently cached provider -// if there is one. If there is no current provider, true will be returned. -func (c *ChainProvider) IsExpired() bool { - if c.curr != nil { - return c.curr.IsExpired() - } - - return true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go deleted file mode 100644 index 42416fc2f..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/credentials.go +++ /dev/null @@ -1,246 +0,0 @@ -// Package credentials provides credential retrieval and management -// -// The Credentials is the primary method of getting access to and managing -// credentials Values. Using dependency injection retrieval of the credential -// values is handled by a object which satisfies the Provider interface. -// -// By default the Credentials.Get() will cache the successful result of a -// Provider's Retrieve() until Provider.IsExpired() returns true. At which -// point Credentials will call Provider's Retrieve() to get new credential Value. -// -// The Provider is responsible for determining when credentials Value have expired. -// It is also important to note that Credentials will always call Retrieve the -// first time Credentials.Get() is called. -// -// Example of using the environment variable credentials. -// -// creds := credentials.NewEnvCredentials() -// -// // Retrieve the credentials value -// credValue, err := creds.Get() -// if err != nil { -// // handle error -// } -// -// Example of forcing credentials to expire and be refreshed on the next Get(). -// This may be helpful to proactively expire credentials and refresh them sooner -// than they would naturally expire on their own. -// -// creds := credentials.NewCredentials(&ec2rolecreds.EC2RoleProvider{}) -// creds.Expire() -// credsValue, err := creds.Get() -// // New credentials will be retrieved instead of from cache. -// -// -// Custom Provider -// -// Each Provider built into this package also provides a helper method to generate -// a Credentials pointer setup with the provider. To use a custom Provider just -// create a type which satisfies the Provider interface and pass it to the -// NewCredentials method. -// -// type MyProvider struct{} -// func (m *MyProvider) Retrieve() (Value, error) {...} -// func (m *MyProvider) IsExpired() bool {...} -// -// creds := credentials.NewCredentials(&MyProvider{}) -// credValue, err := creds.Get() -// -package credentials - -import ( - "sync" - "time" -) - -// AnonymousCredentials is an empty Credential object that can be used as -// dummy placeholder credentials for requests that do not need signed. -// -// This Credentials can be used to configure a service to not sign requests -// when making service API calls. For example, when accessing public -// s3 buckets. -// -// svc := s3.New(session.Must(session.NewSession(&aws.Config{ -// Credentials: credentials.AnonymousCredentials, -// }))) -// // Access public S3 buckets. -// -// @readonly -var AnonymousCredentials = NewStaticCredentials("", "", "") - -// A Value is the AWS credentials value for individual credential fields. -type Value struct { - // AWS Access key ID - AccessKeyID string - - // AWS Secret Access Key - SecretAccessKey string - - // AWS Session Token - SessionToken string - - // Provider used to get credentials - ProviderName string -} - -// A Provider is the interface for any component which will provide credentials -// Value. A provider is required to manage its own Expired state, and what to -// be expired means. -// -// The Provider should not need to implement its own mutexes, because -// that will be managed by Credentials. -type Provider interface { - // Retrieve returns nil if it successfully retrieved the value. - // Error is returned if the value were not obtainable, or empty. - Retrieve() (Value, error) - - // IsExpired returns if the credentials are no longer valid, and need - // to be retrieved. - IsExpired() bool -} - -// An ErrorProvider is a stub credentials provider that always returns an error -// this is used by the SDK when construction a known provider is not possible -// due to an error. -type ErrorProvider struct { - // The error to be returned from Retrieve - Err error - - // The provider name to set on the Retrieved returned Value - ProviderName string -} - -// Retrieve will always return the error that the ErrorProvider was created with. -func (p ErrorProvider) Retrieve() (Value, error) { - return Value{ProviderName: p.ProviderName}, p.Err -} - -// IsExpired will always return not expired. -func (p ErrorProvider) IsExpired() bool { - return false -} - -// A Expiry provides shared expiration logic to be used by credentials -// providers to implement expiry functionality. -// -// The best method to use this struct is as an anonymous field within the -// provider's struct. -// -// Example: -// type EC2RoleProvider struct { -// Expiry -// ... -// } -type Expiry struct { - // The date/time when to expire on - expiration time.Time - - // If set will be used by IsExpired to determine the current time. - // Defaults to time.Now if CurrentTime is not set. Available for testing - // to be able to mock out the current time. - CurrentTime func() time.Time -} - -// SetExpiration sets the expiration IsExpired will check when called. -// -// If window is greater than 0 the expiration time will be reduced by the -// window value. -// -// Using a window is helpful to trigger credentials to expire sooner than -// the expiration time given to ensure no requests are made with expired -// tokens. -func (e *Expiry) SetExpiration(expiration time.Time, window time.Duration) { - e.expiration = expiration - if window > 0 { - e.expiration = e.expiration.Add(-window) - } -} - -// IsExpired returns if the credentials are expired. -func (e *Expiry) IsExpired() bool { - if e.CurrentTime == nil { - e.CurrentTime = time.Now - } - return e.expiration.Before(e.CurrentTime()) -} - -// A Credentials provides synchronous safe retrieval of AWS credentials Value. -// Credentials will cache the credentials value until they expire. Once the value -// expires the next Get will attempt to retrieve valid credentials. -// -// Credentials is safe to use across multiple goroutines and will manage the -// synchronous state so the Providers do not need to implement their own -// synchronization. -// -// The first Credentials.Get() will always call Provider.Retrieve() to get the -// first instance of the credentials Value. All calls to Get() after that -// will return the cached credentials Value until IsExpired() returns true. -type Credentials struct { - creds Value - forceRefresh bool - m sync.Mutex - - provider Provider -} - -// NewCredentials returns a pointer to a new Credentials with the provider set. -func NewCredentials(provider Provider) *Credentials { - return &Credentials{ - provider: provider, - forceRefresh: true, - } -} - -// Get returns the credentials value, or error if the credentials Value failed -// to be retrieved. -// -// Will return the cached credentials Value if it has not expired. If the -// credentials Value has expired the Provider's Retrieve() will be called -// to refresh the credentials. -// -// If Credentials.Expire() was called the credentials Value will be force -// expired, and the next call to Get() will cause them to be refreshed. -func (c *Credentials) Get() (Value, error) { - c.m.Lock() - defer c.m.Unlock() - - if c.isExpired() { - creds, err := c.provider.Retrieve() - if err != nil { - return Value{}, err - } - c.creds = creds - c.forceRefresh = false - } - - return c.creds, nil -} - -// Expire expires the credentials and forces them to be retrieved on the -// next call to Get(). -// -// This will override the Provider's expired state, and force Credentials -// to call the Provider's Retrieve(). -func (c *Credentials) Expire() { - c.m.Lock() - defer c.m.Unlock() - - c.forceRefresh = true -} - -// IsExpired returns if the credentials are no longer valid, and need -// to be retrieved. -// -// If the Credentials were forced to be expired with Expire() this will -// reflect that override. -func (c *Credentials) IsExpired() bool { - c.m.Lock() - defer c.m.Unlock() - - return c.isExpired() -} - -// isExpired helper method wrapping the definition of expired credentials. -func (c *Credentials) isExpired() bool { - return c.forceRefresh || c.provider.IsExpired() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go deleted file mode 100644 index c39749524..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds/ec2_role_provider.go +++ /dev/null @@ -1,178 +0,0 @@ -package ec2rolecreds - -import ( - "bufio" - "encoding/json" - "fmt" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/ec2metadata" -) - -// ProviderName provides a name of EC2Role provider -const ProviderName = "EC2RoleProvider" - -// A EC2RoleProvider retrieves credentials from the EC2 service, and keeps track if -// those credentials are expired. -// -// Example how to configure the EC2RoleProvider with custom http Client, Endpoint -// or ExpiryWindow -// -// p := &ec2rolecreds.EC2RoleProvider{ -// // Pass in a custom timeout to be used when requesting -// // IAM EC2 Role credentials. -// Client: ec2metadata.New(sess, aws.Config{ -// HTTPClient: &http.Client{Timeout: 10 * time.Second}, -// }), -// -// // Do not use early expiry of credentials. If a non zero value is -// // specified the credentials will be expired early -// ExpiryWindow: 0, -// } -type EC2RoleProvider struct { - credentials.Expiry - - // Required EC2Metadata client to use when connecting to EC2 metadata service. - Client *ec2metadata.EC2Metadata - - // 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. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a ConfigProvider to create a EC2Metadata client. -// The ConfigProvider is satisfied by the session.Session type. -func NewCredentials(c client.ConfigProvider, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: ec2metadata.New(c), - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping -// the EC2RoleProvider. Takes a EC2Metadata client to use when connecting to EC2 -// metadata service. -func NewCredentialsWithClient(client *ec2metadata.EC2Metadata, options ...func(*EC2RoleProvider)) *credentials.Credentials { - p := &EC2RoleProvider{ - Client: client, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve retrieves credentials from the EC2 service. -// Error will be returned if the request fails, or unable to extract -// the desired credentials. -func (m *EC2RoleProvider) Retrieve() (credentials.Value, error) { - credsList, err := requestCredList(m.Client) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - if len(credsList) == 0 { - return credentials.Value{ProviderName: ProviderName}, awserr.New("EmptyEC2RoleList", "empty EC2 Role list", nil) - } - credsName := credsList[0] - - roleCreds, err := requestCred(m.Client, credsName) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - m.SetExpiration(roleCreds.Expiration, m.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: roleCreds.AccessKeyID, - SecretAccessKey: roleCreds.SecretAccessKey, - SessionToken: roleCreds.Token, - ProviderName: ProviderName, - }, nil -} - -// A 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(client *ec2metadata.EC2Metadata) ([]string, error) { - resp, err := client.GetMetadata(iamSecurityCredsPath) - if err != nil { - return nil, awserr.New("EC2RoleRequestError", "no EC2 instance role found", err) - } - - credsList := []string{} - s := bufio.NewScanner(strings.NewReader(resp)) - for s.Scan() { - credsList = append(credsList, s.Text()) - } - - if err := s.Err(); err != nil { - return nil, awserr.New("SerializationError", "failed to read EC2 instance role from metadata service", 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(client *ec2metadata.EC2Metadata, credsName string) (ec2RoleCredRespBody, error) { - resp, err := client.GetMetadata(path.Join(iamSecurityCredsPath, credsName)) - if err != nil { - return ec2RoleCredRespBody{}, - awserr.New("EC2RoleRequestError", - fmt.Sprintf("failed to get %s EC2 instance role credentials", credsName), - err) - } - - respCreds := ec2RoleCredRespBody{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&respCreds); err != nil { - return ec2RoleCredRespBody{}, - awserr.New("SerializationError", - fmt.Sprintf("failed to decode %s EC2 instance role credentials", credsName), - err) - } - - if respCreds.Code != "Success" { - // If an error code was returned something failed requesting the role. - return ec2RoleCredRespBody{}, awserr.New(respCreds.Code, respCreds.Message, nil) - } - - return respCreds, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go deleted file mode 100644 index a4cec5c55..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/endpointcreds/provider.go +++ /dev/null @@ -1,191 +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 ( - "encoding/json" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ProviderName is the name of the credentials provider. -const ProviderName = `CredentialsEndpointProvider` - -// Provider satisfies the credentials.Provider interface, and is a client to -// retrieve credentials from an arbitrary endpoint. -type Provider struct { - staticCreds bool - credentials.Expiry - - // Requires a 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 - // Endpoint value. - Client *client.Client - - // 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. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewProviderClient returns a credentials Provider for retrieving AWS credentials -// from arbitrary endpoint. -func NewProviderClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) credentials.Provider { - p := &Provider{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: "CredentialsEndpoint", - Endpoint: endpoint, - }, - handlers, - ), - } - - p.Client.Handlers.Unmarshal.PushBack(unmarshalHandler) - p.Client.Handlers.UnmarshalError.PushBack(unmarshalError) - p.Client.Handlers.Validate.Clear() - p.Client.Handlers.Validate.PushBack(validateEndpointHandler) - - for _, option := range options { - option(p) - } - - return p -} - -// NewCredentialsClient returns a Credentials wrapper for retrieving credentials -// from an arbitrary endpoint concurrently. The client will request the -func NewCredentialsClient(cfg aws.Config, handlers request.Handlers, endpoint string, options ...func(*Provider)) *credentials.Credentials { - return credentials.NewCredentials(NewProviderClient(cfg, handlers, endpoint, options...)) -} - -// IsExpired returns true if the credentials retrieved are expired, or not yet -// retrieved. -func (p *Provider) IsExpired() bool { - if p.staticCreds { - return false - } - return p.Expiry.IsExpired() -} - -// 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() (credentials.Value, error) { - resp, err := p.getCredentials() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("CredentialsEndpointError", "failed to load credentials", err) - } - - if resp.Expiration != nil { - p.SetExpiration(*resp.Expiration, p.ExpiryWindow) - } else { - p.staticCreds = true - } - - return credentials.Value{ - AccessKeyID: resp.AccessKeyID, - SecretAccessKey: resp.SecretAccessKey, - SessionToken: resp.Token, - ProviderName: ProviderName, - }, nil -} - -type getCredentialsOutput struct { - Expiration *time.Time - AccessKeyID string - SecretAccessKey string - Token string -} - -type errorOutput struct { - Code string `json:"code"` - Message string `json:"message"` -} - -func (p *Provider) getCredentials() (*getCredentialsOutput, error) { - op := &request.Operation{ - Name: "GetCredentials", - HTTPMethod: "GET", - } - - out := &getCredentialsOutput{} - req := p.Client.NewRequest(op, nil, out) - req.HTTPRequest.Header.Set("Accept", "application/json") - - return out, req.Send() -} - -func validateEndpointHandler(r *request.Request) { - if len(r.ClientInfo.Endpoint) == 0 { - r.Error = aws.ErrMissingEndpoint - } -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - out := r.Data.(*getCredentialsOutput) - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&out); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - var errOut errorOutput - if err := json.NewDecoder(r.HTTPResponse.Body).Decode(&errOut); err != nil { - r.Error = awserr.New("SerializationError", - "failed to decode endpoint credentials", - err, - ) - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New(errOut.Code, errOut.Message, nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go deleted file mode 100644 index c14231a16..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/env_provider.go +++ /dev/null @@ -1,78 +0,0 @@ -package credentials - -import ( - "os" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// EnvProviderName provides a name of Env provider -const EnvProviderName = "EnvProvider" - -var ( - // ErrAccessKeyIDNotFound is returned when the AWS Access Key ID can't be - // found in the process's environment. - // - // @readonly - ErrAccessKeyIDNotFound = awserr.New("EnvAccessKeyNotFound", "AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY not found in environment", nil) - - // ErrSecretAccessKeyNotFound is returned when the AWS Secret Access Key - // can't be found in the process's environment. - // - // @readonly - ErrSecretAccessKeyNotFound = awserr.New("EnvSecretNotFound", "AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY not found in environment", nil) -) - -// A EnvProvider retrieves credentials from the environment variables of the -// running process. Environment credentials never expire. -// -// Environment variables used: -// -// * Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY -// -// * Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY -type EnvProvider struct { - retrieved bool -} - -// NewEnvCredentials returns a pointer to a new Credentials object -// wrapping the environment variable provider. -func NewEnvCredentials() *Credentials { - return NewCredentials(&EnvProvider{}) -} - -// Retrieve retrieves the keys from the environment. -func (e *EnvProvider) Retrieve() (Value, error) { - e.retrieved = false - - id := os.Getenv("AWS_ACCESS_KEY_ID") - if id == "" { - id = os.Getenv("AWS_ACCESS_KEY") - } - - secret := os.Getenv("AWS_SECRET_ACCESS_KEY") - if secret == "" { - secret = os.Getenv("AWS_SECRET_KEY") - } - - if id == "" { - return Value{ProviderName: EnvProviderName}, ErrAccessKeyIDNotFound - } - - if secret == "" { - return Value{ProviderName: EnvProviderName}, ErrSecretAccessKeyNotFound - } - - e.retrieved = true - return Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: os.Getenv("AWS_SESSION_TOKEN"), - ProviderName: EnvProviderName, - }, nil -} - -// IsExpired returns if the credentials have been retrieved. -func (e *EnvProvider) IsExpired() bool { - return !e.retrieved -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go deleted file mode 100644 index 51e21e0f3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/shared_credentials_provider.go +++ /dev/null @@ -1,150 +0,0 @@ -package credentials - -import ( - "fmt" - "os" - - "github.com/go-ini/ini" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// SharedCredsProviderName provides a name of SharedCreds provider -const SharedCredsProviderName = "SharedCredentialsProvider" - -var ( - // ErrSharedCredentialsHomeNotFound is emitted when the user directory cannot be found. - ErrSharedCredentialsHomeNotFound = awserr.New("UserHomeNotFound", "user home directory not found.", nil) -) - -// A SharedCredentialsProvider retrieves credentials from the current user's home -// directory, and keeps track if those credentials are expired. -// -// Profile ini file example: $HOME/.aws/credentials -type SharedCredentialsProvider struct { - // Path to the shared credentials file. - // - // If empty will look for "AWS_SHARED_CREDENTIALS_FILE" env variable. If the - // env value is empty will default to current user's home directory. - // Linux/OSX: "$HOME/.aws/credentials" - // Windows: "%USERPROFILE%\.aws\credentials" - Filename string - - // AWS Profile to extract credentials from the shared credentials file. If empty - // will default to environment variable "AWS_PROFILE" or "default" if - // environment variable is also not set. - Profile string - - // retrieved states if the credentials have been successfully retrieved. - retrieved bool -} - -// NewSharedCredentials returns a pointer to a new Credentials object -// wrapping the Profile file provider. -func NewSharedCredentials(filename, profile string) *Credentials { - return NewCredentials(&SharedCredentialsProvider{ - Filename: filename, - Profile: profile, - }) -} - -// Retrieve reads and extracts the shared credentials from the current -// users home directory. -func (p *SharedCredentialsProvider) Retrieve() (Value, error) { - p.retrieved = false - - filename, err := p.filename() - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - creds, err := loadProfile(filename, p.profile()) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, err - } - - p.retrieved = true - return creds, nil -} - -// IsExpired returns if the shared credentials have expired. -func (p *SharedCredentialsProvider) IsExpired() bool { - return !p.retrieved -} - -// loadProfiles loads from the file pointed to by shared credentials filename for profile. -// The credentials retrieved from the profile will be returned or error. Error will be -// returned if it fails to read from the file, or the data is invalid. -func loadProfile(filename, profile string) (Value, error) { - config, err := ini.Load(filename) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to load shared credentials file", err) - } - iniProfile, err := config.GetSection(profile) - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsLoad", "failed to get profile", err) - } - - id, err := iniProfile.GetKey("aws_access_key_id") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsAccessKey", - fmt.Sprintf("shared credentials %s in %s did not contain aws_access_key_id", profile, filename), - err) - } - - secret, err := iniProfile.GetKey("aws_secret_access_key") - if err != nil { - return Value{ProviderName: SharedCredsProviderName}, awserr.New("SharedCredsSecret", - fmt.Sprintf("shared credentials %s in %s did not contain aws_secret_access_key", profile, filename), - nil) - } - - // Default to empty string if not found - token := iniProfile.Key("aws_session_token") - - return Value{ - AccessKeyID: id.String(), - SecretAccessKey: secret.String(), - SessionToken: token.String(), - ProviderName: SharedCredsProviderName, - }, nil -} - -// filename returns the filename to use to read AWS shared credentials. -// -// Will return an error if the user's home directory path cannot be found. -func (p *SharedCredentialsProvider) filename() (string, error) { - if len(p.Filename) != 0 { - return p.Filename, nil - } - - if p.Filename = os.Getenv("AWS_SHARED_CREDENTIALS_FILE"); len(p.Filename) != 0 { - return p.Filename, nil - } - - if home := shareddefaults.UserHomeDir(); len(home) == 0 { - // Backwards compatibility of home directly not found error being returned. - // This error is too verbose, failure when opening the file would of been - // a better error to return. - return "", ErrSharedCredentialsHomeNotFound - } - - p.Filename = shareddefaults.SharedCredentialsFilename() - - return p.Filename, nil -} - -// profile returns the AWS shared credentials profile. If empty will read -// environment variable "AWS_PROFILE". If that is not set profile will -// return "default". -func (p *SharedCredentialsProvider) profile() string { - if p.Profile == "" { - p.Profile = os.Getenv("AWS_PROFILE") - } - if p.Profile == "" { - p.Profile = "default" - } - - return p.Profile -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go deleted file mode 100644 index 4f5dab3fc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/static_provider.go +++ /dev/null @@ -1,57 +0,0 @@ -package credentials - -import ( - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// StaticProviderName provides a name of Static provider -const StaticProviderName = "StaticProvider" - -var ( - // ErrStaticCredentialsEmpty is emitted when static credentials are empty. - // - // @readonly - ErrStaticCredentialsEmpty = awserr.New("EmptyStaticCreds", "static credentials are empty", nil) -) - -// A StaticProvider is a set of credentials which are set programmatically, -// and will never expire. -type StaticProvider struct { - Value -} - -// NewStaticCredentials returns a pointer to a new Credentials object -// wrapping a static credentials value provider. -func NewStaticCredentials(id, secret, token string) *Credentials { - return NewCredentials(&StaticProvider{Value: Value{ - AccessKeyID: id, - SecretAccessKey: secret, - SessionToken: token, - }}) -} - -// NewStaticCredentialsFromCreds returns a pointer to a new Credentials object -// wrapping the static credentials value provide. Same as NewStaticCredentials -// but takes the creds Value instead of individual fields -func NewStaticCredentialsFromCreds(creds Value) *Credentials { - return NewCredentials(&StaticProvider{Value: creds}) -} - -// Retrieve returns the credentials or error if the credentials are invalid. -func (s *StaticProvider) Retrieve() (Value, error) { - if s.AccessKeyID == "" || s.SecretAccessKey == "" { - return Value{ProviderName: StaticProviderName}, ErrStaticCredentialsEmpty - } - - if len(s.Value.ProviderName) == 0 { - s.Value.ProviderName = StaticProviderName - } - return s.Value, nil -} - -// IsExpired returns if the credentials are expired. -// -// For StaticProvider, the credentials never expired. -func (s *StaticProvider) IsExpired() bool { - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go b/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go deleted file mode 100644 index 4108e433e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/credentials/stscreds/assume_role_provider.go +++ /dev/null @@ -1,298 +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, Sessions or service clients. - -Assume Role - -To assume an IAM role using STS with the SDK you can create a new Credentials -with the SDKs's stscreds package. - - // Initial credentials loaded from SDK's default credential chain. Such as - // the environment, shared credentials (~/.aws/credentials), or EC2 Instance - // Role. These credentials will be used to to make the STS Assume Role API. - sess := session.Must(session.NewSession()) - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. - creds := stscreds.NewCredentials(sess, "myRoleArn") - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with static MFA Token - -To assume an IAM role with a MFA token you can either specify a MFA token code -directly or provide a function to prompt the user each time the credentials -need to refresh the role's credentials. Specifying the TokenCode should be used -for short lived operations that will not need to be refreshed, and when you do -not want to have direct control over the user provides their MFA token. - -With TokenCode the AssumeRoleProvider will be not be able to refresh the role's -credentials. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN using the MFA token code provided. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenCode = aws.String("00000000") - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -Assume Role with MFA Token Provider - -To assume an IAM role with MFA for longer running tasks where the credentials -may need to be refreshed setting the TokenProvider field of AssumeRoleProvider -will allow the credential provider to prompt for new MFA token code when the -role's credentials need to be refreshed. - -The StdinTokenProvider function is available to prompt on stdin to retrieve -the MFA token code from the user. You can also implement custom prompts by -satisfing the TokenProvider function signature. - -Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -have undesirable results as the StdinTokenProvider will not be synchronized. A -single Credentials with an AssumeRoleProvider can be shared safely. - - // Create the credentials from AssumeRoleProvider to assume the role - // referenced by the "myRoleARN" ARN. Prompting for MFA token from stdin. - creds := stscreds.NewCredentials(sess, "myRoleArn", func(p *stscreds.AssumeRoleProvider) { - p.SerialNumber = aws.String("myTokenSerialNumber") - p.TokenProvider = stscreds.StdinTokenProvider - }) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess, &aws.Config{Credentials: creds}) - -*/ -package stscreds - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/service/sts" -) - -// StdinTokenProvider will prompt on stdout and read from stdin for a string value. -// An error is returned if reading from stdin fails. -// -// Use this function go read MFA tokens from stdin. The function makes no attempt -// to make atomic prompts from stdin across multiple gorouties. -// -// Using StdinTokenProvider with multiple AssumeRoleProviders, or Credentials will -// have undesirable results as the StdinTokenProvider will not be synchronized. A -// single Credentials with an AssumeRoleProvider can be shared safely -// -// Will wait forever until something is provided on the stdin. -func StdinTokenProvider() (string, error) { - var v string - fmt.Printf("Assume Role MFA token code: ") - _, err := fmt.Scanln(&v) - - return v, err -} - -// ProviderName provides a name of AssumeRole provider -const ProviderName = "AssumeRoleProvider" - -// AssumeRoler represents the minimal subset of the STS client API used by this provider. -type AssumeRoler interface { - AssumeRole(input *sts.AssumeRoleInput) (*sts.AssumeRoleOutput, error) -} - -// DefaultDuration is the default amount of time in minutes that the credentials -// will be valid for. -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 { - credentials.Expiry - - // STS client to make assume role request with. - Client AssumeRoler - - // Role to be assumed. - RoleARN string - - // Session name, if you wish to reuse the credentials elsewhere. - 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 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 value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // If SerialNumber is set and neither TokenCode nor TokenProvider are also - // set an error will be returned. - TokenCode *string - - // Async method of providing MFA token code for assuming an IAM role with MFA. - // The value returned by the function will be used as the TokenCode in the Retrieve - // call. See StdinTokenProvider for a provider that prompts and reads from stdin. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed when SerialNumber is also set and - // TokenCode is not set. - // - // If both TokenCode and TokenProvider is set, TokenProvider will be used and - // TokenCode is ignored. - TokenProvider func() (string, error) - - // ExpiryWindow will allow the credentials to trigger refreshing prior to - // the credentials actually expiring. This is beneficial so race conditions - // with expiring credentials do not cause request to fail unexpectedly - // due to ExpiredTokenException exceptions. - // - // So a ExpiryWindow of 10s would cause calls to IsExpired() to return true - // 10 seconds before the credentials are actually expired. - // - // If ExpiryWindow is 0 or less it will be ignored. - ExpiryWindow time.Duration -} - -// NewCredentials returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes a Config provider to create the STS client. The ConfigProvider is -// satisfied by the session.Session type. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentials(c client.ConfigProvider, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: sts.New(c), - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// NewCredentialsWithClient returns a pointer to a new Credentials object wrapping the -// AssumeRoleProvider. The credentials will expire every 15 minutes and the -// role will be named after a nanosecond timestamp of this operation. -// -// Takes an AssumeRoler which can be satisfied by the STS client. -// -// It is safe to share the returned Credentials with multiple Sessions and -// service clients. All access to the credentials and refreshing them -// will be synchronized. -func NewCredentialsWithClient(svc AssumeRoler, roleARN string, options ...func(*AssumeRoleProvider)) *credentials.Credentials { - p := &AssumeRoleProvider{ - Client: svc, - RoleARN: roleARN, - Duration: DefaultDuration, - } - - for _, option := range options { - option(p) - } - - return credentials.NewCredentials(p) -} - -// Retrieve generates a new set of temporary credentials using STS. -func (p *AssumeRoleProvider) Retrieve() (credentials.Value, error) { - - // Apply defaults where parameters are not set. - if p.RoleSessionName == "" { - // Try to work out a role name that will hopefully end up unique. - p.RoleSessionName = fmt.Sprintf("%d", time.Now().UTC().UnixNano()) - } - if p.Duration == 0 { - // Expire as often as AWS permits. - p.Duration = DefaultDuration - } - input := &sts.AssumeRoleInput{ - DurationSeconds: aws.Int64(int64(p.Duration / time.Second)), - RoleArn: aws.String(p.RoleARN), - RoleSessionName: aws.String(p.RoleSessionName), - ExternalId: p.ExternalID, - } - if p.Policy != nil { - input.Policy = p.Policy - } - if p.SerialNumber != nil { - if p.TokenCode != nil { - input.SerialNumber = p.SerialNumber - input.TokenCode = p.TokenCode - } else if p.TokenProvider != nil { - input.SerialNumber = p.SerialNumber - code, err := p.TokenProvider() - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - input.TokenCode = aws.String(code) - } else { - return credentials.Value{ProviderName: ProviderName}, - awserr.New("AssumeRoleTokenNotAvailable", - "assume role with MFA enabled, but neither TokenCode nor TokenProvider are set", nil) - } - } - - roleOutput, err := p.Client.AssumeRole(input) - if err != nil { - return credentials.Value{ProviderName: ProviderName}, err - } - - // We will proactively generate new credentials before they expire. - p.SetExpiration(*roleOutput.Credentials.Expiration, p.ExpiryWindow) - - return credentials.Value{ - AccessKeyID: *roleOutput.Credentials.AccessKeyId, - SecretAccessKey: *roleOutput.Credentials.SecretAccessKey, - SessionToken: *roleOutput.Credentials.SessionToken, - ProviderName: ProviderName, - }, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go deleted file mode 100644 index 3cf1036b6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/defaults.go +++ /dev/null @@ -1,194 +0,0 @@ -// Package defaults is a collection of helpers to retrieve the SDK's default -// configuration and handlers. -// -// Generally this package shouldn't be used directly, but session.Session -// instead. This package is useful when you need to reset the defaults -// of a session or service client to the SDK defaults before setting -// additional parameters. -package defaults - -import ( - "fmt" - "net" - "net/http" - "net/url" - "os" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds" - "github.com/aws/aws-sdk-go/aws/credentials/endpointcreds" - "github.com/aws/aws-sdk-go/aws/ec2metadata" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Defaults provides a collection of default values for SDK clients. -type Defaults struct { - Config *aws.Config - Handlers request.Handlers -} - -// Get returns the SDK's default values with Config and handlers pre-configured. -func Get() Defaults { - cfg := Config() - handlers := Handlers() - cfg.Credentials = CredChain(cfg, handlers) - - return Defaults{ - Config: cfg, - Handlers: handlers, - } -} - -// Config returns the default configuration without credentials. -// To retrieve a config with credentials also included use -// `defaults.Get().Config` instead. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the configuration of an -// existing service client or session. -func Config() *aws.Config { - return aws.NewConfig(). - WithCredentials(credentials.AnonymousCredentials). - WithRegion(os.Getenv("AWS_REGION")). - WithHTTPClient(http.DefaultClient). - WithMaxRetries(aws.UseServiceDefaultRetries). - WithLogger(aws.NewDefaultLogger()). - WithLogLevel(aws.LogOff). - WithEndpointResolver(endpoints.DefaultResolver()) -} - -// Handlers returns the default request handlers. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the request handlers of an -// existing service client or session. -func Handlers() request.Handlers { - var handlers request.Handlers - - handlers.Validate.PushBackNamed(corehandlers.ValidateEndpointHandler) - handlers.Validate.AfterEachFn = request.HandlerListStopOnError - handlers.Build.PushBackNamed(corehandlers.SDKVersionUserAgentHandler) - handlers.Build.PushBackNamed(corehandlers.AddHostExecEnvUserAgentHander) - handlers.Build.AfterEachFn = request.HandlerListStopOnError - handlers.Sign.PushBackNamed(corehandlers.BuildContentLengthHandler) - handlers.Send.PushBackNamed(corehandlers.ValidateReqSigHandler) - handlers.Send.PushBackNamed(corehandlers.SendHandler) - handlers.AfterRetry.PushBackNamed(corehandlers.AfterRetryHandler) - handlers.ValidateResponse.PushBackNamed(corehandlers.ValidateResponseHandler) - - return handlers -} - -// CredChain returns the default credential chain. -// -// Generally you shouldn't need to use this method directly, but -// is available if you need to reset the credentials of an -// existing service client or session's Config. -func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials { - return credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credentials.EnvProvider{}, - &credentials.SharedCredentialsProvider{Filename: "", Profile: ""}, - RemoteCredProvider(*cfg, handlers), - }, - }) -} - -const ( - httpProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_FULL_URI" - ecsCredsProviderEnvVar = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI" -) - -// RemoteCredProvider returns a credentials provider for the default remote -// endpoints such as EC2 or ECS Roles. -func RemoteCredProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - if u := os.Getenv(httpProviderEnvVar); len(u) > 0 { - return localHTTPCredProvider(cfg, handlers, u) - } - - if uri := os.Getenv(ecsCredsProviderEnvVar); len(uri) > 0 { - u := fmt.Sprintf("http://169.254.170.2%s", uri) - return httpCredProvider(cfg, handlers, u) - } - - return ec2RoleProvider(cfg, handlers) -} - -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 - } - for _, addr := range addrs { - if !net.ParseIP(addr).IsLoopback() { - return false, nil - } - } - - return true, nil -} - -func localHTTPCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - var errMsg string - - parsed, err := url.Parse(u) - if err != nil { - errMsg = fmt.Sprintf("invalid URL, %v", err) - } else { - host := aws.URLHostname(parsed) - if len(host) == 0 { - errMsg = "unable to parse host from local HTTP cred provider URL" - } else if isLoopback, loopbackErr := isLoopbackHost(host); loopbackErr != nil { - errMsg = fmt.Sprintf("failed to resolve host %q, %v", host, loopbackErr) - } else if !isLoopback { - errMsg = fmt.Sprintf("invalid endpoint host, %q, only loopback hosts are allowed.", host) - } - } - - if len(errMsg) > 0 { - if cfg.Logger != nil { - cfg.Logger.Log("Ignoring, HTTP credential provider", errMsg, err) - } - return credentials.ErrorProvider{ - Err: awserr.New("CredentialsEndpointError", errMsg, err), - ProviderName: endpointcreds.ProviderName, - } - } - - return httpCredProvider(cfg, handlers, u) -} - -func httpCredProvider(cfg aws.Config, handlers request.Handlers, u string) credentials.Provider { - return endpointcreds.NewProviderClient(cfg, handlers, u, - func(p *endpointcreds.Provider) { - p.ExpiryWindow = 5 * time.Minute - }, - ) -} - -func ec2RoleProvider(cfg aws.Config, handlers request.Handlers) credentials.Provider { - resolver := cfg.EndpointResolver - if resolver == nil { - resolver = endpoints.DefaultResolver() - } - - e, _ := resolver.EndpointFor(endpoints.Ec2metadataServiceID, "") - return &ec2rolecreds.EC2RoleProvider{ - Client: ec2metadata.NewClient(cfg, handlers, e.URL, e.SigningRegion), - ExpiryWindow: 5 * time.Minute, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go deleted file mode 100644 index ca0ee1dcc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/defaults/shared_config.go +++ /dev/null @@ -1,27 +0,0 @@ -package defaults - -import ( - "github.com/aws/aws-sdk-go/internal/shareddefaults" -) - -// 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 shareddefaults.SharedCredentialsFilename() -} - -// 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 shareddefaults.SharedConfigFilename() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/doc.go deleted file mode 100644 index 4fcb61618..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/doc.go +++ /dev/null @@ -1,56 +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.StringValue(strPtr) -// -// In addition to scalars the aws package also includes conversion utilities for -// map and slice for commonly types used in API parameters. The map and slice -// conversion functions use similar naming pattern as the scalar conversion -// functions. -// -// var strPtrs []*string -// var strs []string = []string{"Go", "Gophers", "Go"} -// -// // Convert []string to []*string -// strPtrs = aws.StringSlice(strs) -// -// // Convert []*string to []string -// strs = aws.StringValueSlice(strPtrs) -// -// SDK Default HTTP Client -// -// The SDK will use the http.DefaultClient if a HTTP client is not provided to -// the SDK's Session, or service client constructor. This means that if the -// http.DefaultClient is modified by other components of your application the -// modifications will be picked up by the SDK as well. -// -// In some cases this might be intended, but it is a better practice to create -// a custom HTTP Client to share explicitly through your application. You can -// configure the SDK to use the custom HTTP Client by setting the HTTPClient -// value of the SDK's Config type when creating a Session or service client. -package aws diff --git a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go deleted file mode 100644 index 984407a58..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/api.go +++ /dev/null @@ -1,162 +0,0 @@ -package ec2metadata - -import ( - "encoding/json" - "fmt" - "net/http" - "path" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -// GetMetadata uses the path provided to request information from the EC2 -// instance metdata service. The content will be returned as a string, or -// error if the request failed. -func (c *EC2Metadata) GetMetadata(p string) (string, error) { - op := &request.Operation{ - Name: "GetMetadata", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "meta-data", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetUserData returns the userdata that was configured for the service. If -// there is no user-data setup for the EC2 instance a "NotFoundError" error -// code will be returned. -func (c *EC2Metadata) GetUserData() (string, error) { - op := &request.Operation{ - Name: "GetUserData", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "user-data"), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - req.Handlers.UnmarshalError.PushBack(func(r *request.Request) { - if r.HTTPResponse.StatusCode == http.StatusNotFound { - r.Error = awserr.New("NotFoundError", "user-data not found", r.Error) - } - }) - - return output.Content, req.Send() -} - -// 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 *EC2Metadata) GetDynamicData(p string) (string, error) { - op := &request.Operation{ - Name: "GetDynamicData", - HTTPMethod: "GET", - HTTPPath: path.Join("/", "dynamic", p), - } - - output := &metadataOutput{} - req := c.NewRequest(op, nil, output) - - return output.Content, req.Send() -} - -// GetInstanceIdentityDocument retrieves an identity document describing an -// instance. Error is returned if the request fails or is unable to parse -// the response. -func (c *EC2Metadata) GetInstanceIdentityDocument() (EC2InstanceIdentityDocument, error) { - resp, err := c.GetDynamicData("instance-identity/document") - if err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 instance identity document", err) - } - - doc := EC2InstanceIdentityDocument{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&doc); err != nil { - return EC2InstanceIdentityDocument{}, - awserr.New("SerializationError", - "failed to decode EC2 instance identity document", err) - } - - return doc, nil -} - -// IAMInfo retrieves IAM info from the metadata API -func (c *EC2Metadata) IAMInfo() (EC2IAMInfo, error) { - resp, err := c.GetMetadata("iam/info") - if err != nil { - return EC2IAMInfo{}, - awserr.New("EC2MetadataRequestError", - "failed to get EC2 IAM info", err) - } - - info := EC2IAMInfo{} - if err := json.NewDecoder(strings.NewReader(resp)).Decode(&info); err != nil { - return EC2IAMInfo{}, - awserr.New("SerializationError", - "failed to decode EC2 IAM info", err) - } - - if info.Code != "Success" { - errMsg := fmt.Sprintf("failed to get EC2 IAM Info (%s)", info.Code) - return EC2IAMInfo{}, - awserr.New("EC2MetadataError", errMsg, nil) - } - - return info, nil -} - -// Region returns the region the instance is running in. -func (c *EC2Metadata) Region() (string, error) { - resp, err := c.GetMetadata("placement/availability-zone") - if err != nil { - return "", err - } - - // returns region without the suffix. Eg: us-west-2a becomes us-west-2 - return resp[:len(resp)-1], nil -} - -// Available returns if the application has access to the EC2 Metadata service. -// Can be used to determine if application is running within an EC2 Instance and -// the metadata service is available. -func (c *EC2Metadata) Available() bool { - if _, err := c.GetMetadata("instance-id"); err != nil { - return false - } - - return true -} - -// An EC2IAMInfo provides the shape for unmarshaling -// an IAM info from the metadata API -type EC2IAMInfo struct { - Code string - LastUpdated time.Time - InstanceProfileArn string - InstanceProfileID string -} - -// An EC2InstanceIdentityDocument provides the shape for unmarshaling -// an instance identity document -type EC2InstanceIdentityDocument struct { - DevpayProductCodes []string `json:"devpayProductCodes"` - 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/aws/ec2metadata/service.go b/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go deleted file mode 100644 index ef5f73292..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/ec2metadata/service.go +++ /dev/null @@ -1,148 +0,0 @@ -// Package ec2metadata provides the client for making API calls to the -// EC2 Metadata service. -// -// This package's client can be disabled completely by setting the environment -// variable "AWS_EC2_METADATA_DISABLED=true". This environment variable set to -// true instructs the SDK to disable the EC2 Metadata client. The client cannot -// be used while the environemnt variable is set to true, (case insensitive). -package ec2metadata - -import ( - "bytes" - "errors" - "io" - "net/http" - "os" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/request" -) - -// ServiceName is the name of the service. -const ServiceName = "ec2metadata" -const disableServiceEnvVar = "AWS_EC2_METADATA_DISABLED" - -// A EC2Metadata is an EC2 Metadata service Client. -type EC2Metadata struct { - *client.Client -} - -// New creates a new instance of the EC2Metadata client with a session. -// This client is safe to use across multiple goroutines. -// -// -// Example: -// // Create a EC2Metadata client from just a session. -// svc := ec2metadata.New(mySession) -// -// // Create a EC2Metadata client with additional configuration -// svc := ec2metadata.New(mySession, aws.NewConfig().WithLogLevel(aws.LogDebugHTTPBody)) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *EC2Metadata { - c := p.ClientConfig(ServiceName, cfgs...) - return NewClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion) -} - -// NewClient returns a new EC2Metadata client. Should be used to create -// a client when not using a session. Generally using just New with a session -// is preferred. -// -// If an unmodified HTTP client is provided from the stdlib default, or no client -// the EC2RoleProvider's EC2Metadata HTTP client's timeout will be shortened. -// To disable this set Config.EC2MetadataDisableTimeoutOverride to false. Enabled by default. -func NewClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion string, opts ...func(*client.Client)) *EC2Metadata { - if !aws.BoolValue(cfg.EC2MetadataDisableTimeoutOverride) && httpClientZero(cfg.HTTPClient) { - // If the http client is unmodified and this feature is not disabled - // set custom timeouts for EC2Metadata requests. - cfg.HTTPClient = &http.Client{ - // use a shorter timeout than default because the metadata - // service is local if it is running, and to fail faster - // if not running on an ec2 instance. - Timeout: 5 * time.Second, - } - } - - svc := &EC2Metadata{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - Endpoint: endpoint, - APIVersion: "latest", - }, - handlers, - ), - } - - svc.Handlers.Unmarshal.PushBack(unmarshalHandler) - svc.Handlers.UnmarshalError.PushBack(unmarshalError) - svc.Handlers.Validate.Clear() - svc.Handlers.Validate.PushBack(validateEndpointHandler) - - // Disable the EC2 Metadata service if the environment variable is set. - // This shortcirctes the service's functionality to always fail to send - // requests. - if strings.ToLower(os.Getenv(disableServiceEnvVar)) == "true" { - svc.Handlers.Send.SwapNamed(request.NamedHandler{ - Name: corehandlers.SendHandler.Name, - Fn: func(r *request.Request) { - r.Error = awserr.New( - request.CanceledErrorCode, - "EC2 IMDS access disabled via "+disableServiceEnvVar+" env var", - nil) - }, - }) - } - - // Add additional options to the service config - for _, option := range opts { - option(svc.Client) - } - - return svc -} - -func httpClientZero(c *http.Client) bool { - return c == nil || (c.Transport == nil && c.CheckRedirect == nil && c.Jar == nil && c.Timeout == 0) -} - -type metadataOutput struct { - Content string -} - -func unmarshalHandler(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata respose", err) - return - } - - if data, ok := r.Data.(*metadataOutput); ok { - data.Content = b.String() - } -} - -func unmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - b := &bytes.Buffer{} - if _, err := io.Copy(b, r.HTTPResponse.Body); err != nil { - r.Error = awserr.New("SerializationError", "unable to unmarshal EC2 metadata error respose", err) - return - } - - // Response body format is not consistent between metadata endpoints. - // Grab the error message as a string and include that as the source error - r.Error = awserr.New("EC2MetadataError", "failed to make EC2Metadata request", errors.New(b.String())) -} - -func validateEndpointHandler(r *request.Request) { - if r.ClientInfo.Endpoint == "" { - r.Error = aws.ErrMissingEndpoint - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go deleted file mode 100644 index 74f72de07..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/decode.go +++ /dev/null @@ -1,133 +0,0 @@ -package endpoints - -import ( - "encoding/json" - "fmt" - "io" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -type modelDefinition map[string]json.RawMessage - -// A DecodeModelOptions are the options for how the endpoints model definition -// are decoded. -type DecodeModelOptions struct { - SkipCustomizations bool -} - -// Set combines all of the option functions together. -func (d *DecodeModelOptions) Set(optFns ...func(*DecodeModelOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// DecodeModel unmarshals a Regions and Endpoint model definition file into -// a endpoint Resolver. If the file format is not supported, or an error occurs -// when unmarshaling the model an error will be returned. -// -// Casting the return value of this func to a EnumPartitions will -// allow you to get a list of the partitions in the order the endpoints -// will be resolved in. -// -// resolver, err := endpoints.DecodeModel(reader) -// -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// for _, p := range partitions { -// // ... inspect partitions -// } -func DecodeModel(r io.Reader, optFns ...func(*DecodeModelOptions)) (Resolver, error) { - var opts DecodeModelOptions - opts.Set(optFns...) - - // Get the version of the partition file to determine what - // unmarshaling model to use. - modelDef := modelDefinition{} - if err := json.NewDecoder(r).Decode(&modelDef); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - var version string - if b, ok := modelDef["version"]; ok { - version = string(b) - } else { - return nil, newDecodeModelError("endpoints version not found in model", nil) - } - - if version == "3" { - return decodeV3Endpoints(modelDef, opts) - } - - return nil, newDecodeModelError( - fmt.Sprintf("endpoints version %s, not supported", version), nil) -} - -func decodeV3Endpoints(modelDef modelDefinition, opts DecodeModelOptions) (Resolver, error) { - b, ok := modelDef["partitions"] - if !ok { - return nil, newDecodeModelError("endpoints model missing partitions", nil) - } - - ps := partitions{} - if err := json.Unmarshal(b, &ps); err != nil { - return nil, newDecodeModelError("failed to decode endpoints model", err) - } - - if opts.SkipCustomizations { - return ps, nil - } - - // Customization - for i := 0; i < len(ps); i++ { - p := &ps[i] - custAddEC2Metadata(p) - custAddS3DualStack(p) - custRmIotDataService(p) - } - - return ps, nil -} - -func custAddS3DualStack(p *partition) { - if p.ID != "aws" { - return - } - - s, ok := p.Services["s3"] - if !ok { - return - } - - s.Defaults.HasDualStack = boxedTrue - s.Defaults.DualStackHostname = "{service}.dualstack.{region}.{dnsSuffix}" - - p.Services["s3"] = s -} - -func custAddEC2Metadata(p *partition) { - p.Services["ec2metadata"] = service{ - IsRegionalized: boxedFalse, - PartitionEndpoint: "aws-global", - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - } -} - -func custRmIotDataService(p *partition) { - delete(p.Services, "data.iot") -} - -type decodeModelError struct { - awsError -} - -func newDecodeModelError(msg string, err error) decodeModelError { - return decodeModelError{ - awsError: awserr.New("DecodeEndpointsModelError", msg, err), - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go deleted file mode 100644 index 857f677dd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/defaults.go +++ /dev/null @@ -1,3087 +0,0 @@ -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - -// Partition identifiers -const ( - AwsPartitionID = "aws" // AWS Standard partition. - AwsCnPartitionID = "aws-cn" // AWS China partition. - AwsUsGovPartitionID = "aws-us-gov" // AWS GovCloud (US) partition. -) - -// AWS Standard partition's regions. -const ( - ApNortheast1RegionID = "ap-northeast-1" // Asia Pacific (Tokyo). - ApNortheast2RegionID = "ap-northeast-2" // Asia Pacific (Seoul). - ApSouth1RegionID = "ap-south-1" // Asia Pacific (Mumbai). - ApSoutheast1RegionID = "ap-southeast-1" // Asia Pacific (Singapore). - ApSoutheast2RegionID = "ap-southeast-2" // Asia Pacific (Sydney). - CaCentral1RegionID = "ca-central-1" // Canada (Central). - EuCentral1RegionID = "eu-central-1" // EU (Frankfurt). - EuWest1RegionID = "eu-west-1" // EU (Ireland). - EuWest2RegionID = "eu-west-2" // EU (London). - EuWest3RegionID = "eu-west-3" // EU (Paris). - SaEast1RegionID = "sa-east-1" // South America (Sao Paulo). - UsEast1RegionID = "us-east-1" // US East (N. Virginia). - UsEast2RegionID = "us-east-2" // US East (Ohio). - UsWest1RegionID = "us-west-1" // US West (N. California). - UsWest2RegionID = "us-west-2" // US West (Oregon). -) - -// AWS China partition's regions. -const ( - CnNorth1RegionID = "cn-north-1" // China (Beijing). - CnNorthwest1RegionID = "cn-northwest-1" // China (Ningxia). -) - -// AWS GovCloud (US) partition's regions. -const ( - UsGovWest1RegionID = "us-gov-west-1" // AWS GovCloud (US). -) - -// Service identifiers -const ( - A4bServiceID = "a4b" // A4b. - AcmServiceID = "acm" // Acm. - AcmPcaServiceID = "acm-pca" // AcmPca. - ApiPricingServiceID = "api.pricing" // ApiPricing. - ApigatewayServiceID = "apigateway" // Apigateway. - ApplicationAutoscalingServiceID = "application-autoscaling" // ApplicationAutoscaling. - Appstream2ServiceID = "appstream2" // Appstream2. - AthenaServiceID = "athena" // Athena. - AutoscalingServiceID = "autoscaling" // Autoscaling. - AutoscalingPlansServiceID = "autoscaling-plans" // AutoscalingPlans. - BatchServiceID = "batch" // Batch. - BudgetsServiceID = "budgets" // Budgets. - CeServiceID = "ce" // Ce. - Cloud9ServiceID = "cloud9" // Cloud9. - ClouddirectoryServiceID = "clouddirectory" // Clouddirectory. - CloudformationServiceID = "cloudformation" // Cloudformation. - CloudfrontServiceID = "cloudfront" // Cloudfront. - CloudhsmServiceID = "cloudhsm" // Cloudhsm. - Cloudhsmv2ServiceID = "cloudhsmv2" // Cloudhsmv2. - CloudsearchServiceID = "cloudsearch" // Cloudsearch. - CloudtrailServiceID = "cloudtrail" // Cloudtrail. - CodebuildServiceID = "codebuild" // Codebuild. - CodecommitServiceID = "codecommit" // Codecommit. - CodedeployServiceID = "codedeploy" // Codedeploy. - CodepipelineServiceID = "codepipeline" // Codepipeline. - CodestarServiceID = "codestar" // Codestar. - CognitoIdentityServiceID = "cognito-identity" // CognitoIdentity. - CognitoIdpServiceID = "cognito-idp" // CognitoIdp. - CognitoSyncServiceID = "cognito-sync" // CognitoSync. - ComprehendServiceID = "comprehend" // Comprehend. - ConfigServiceID = "config" // Config. - CurServiceID = "cur" // Cur. - DatapipelineServiceID = "datapipeline" // Datapipeline. - DaxServiceID = "dax" // Dax. - DevicefarmServiceID = "devicefarm" // Devicefarm. - DirectconnectServiceID = "directconnect" // Directconnect. - DiscoveryServiceID = "discovery" // Discovery. - DmsServiceID = "dms" // Dms. - DsServiceID = "ds" // Ds. - DynamodbServiceID = "dynamodb" // Dynamodb. - Ec2ServiceID = "ec2" // Ec2. - Ec2metadataServiceID = "ec2metadata" // Ec2metadata. - EcrServiceID = "ecr" // Ecr. - EcsServiceID = "ecs" // Ecs. - ElasticacheServiceID = "elasticache" // Elasticache. - ElasticbeanstalkServiceID = "elasticbeanstalk" // Elasticbeanstalk. - ElasticfilesystemServiceID = "elasticfilesystem" // Elasticfilesystem. - ElasticloadbalancingServiceID = "elasticloadbalancing" // Elasticloadbalancing. - ElasticmapreduceServiceID = "elasticmapreduce" // Elasticmapreduce. - ElastictranscoderServiceID = "elastictranscoder" // Elastictranscoder. - EmailServiceID = "email" // Email. - EntitlementMarketplaceServiceID = "entitlement.marketplace" // EntitlementMarketplace. - EsServiceID = "es" // Es. - EventsServiceID = "events" // Events. - FirehoseServiceID = "firehose" // Firehose. - FmsServiceID = "fms" // Fms. - GameliftServiceID = "gamelift" // Gamelift. - GlacierServiceID = "glacier" // Glacier. - GlueServiceID = "glue" // Glue. - GreengrassServiceID = "greengrass" // Greengrass. - GuarddutyServiceID = "guardduty" // Guardduty. - HealthServiceID = "health" // Health. - IamServiceID = "iam" // Iam. - ImportexportServiceID = "importexport" // Importexport. - InspectorServiceID = "inspector" // Inspector. - IotServiceID = "iot" // Iot. - KinesisServiceID = "kinesis" // Kinesis. - KinesisanalyticsServiceID = "kinesisanalytics" // Kinesisanalytics. - KinesisvideoServiceID = "kinesisvideo" // Kinesisvideo. - KmsServiceID = "kms" // Kms. - LambdaServiceID = "lambda" // Lambda. - LightsailServiceID = "lightsail" // Lightsail. - LogsServiceID = "logs" // Logs. - MachinelearningServiceID = "machinelearning" // Machinelearning. - MarketplacecommerceanalyticsServiceID = "marketplacecommerceanalytics" // Marketplacecommerceanalytics. - MediaconvertServiceID = "mediaconvert" // Mediaconvert. - MedialiveServiceID = "medialive" // Medialive. - MediapackageServiceID = "mediapackage" // Mediapackage. - MediastoreServiceID = "mediastore" // Mediastore. - MeteringMarketplaceServiceID = "metering.marketplace" // MeteringMarketplace. - MghServiceID = "mgh" // Mgh. - MobileanalyticsServiceID = "mobileanalytics" // Mobileanalytics. - ModelsLexServiceID = "models.lex" // ModelsLex. - MonitoringServiceID = "monitoring" // Monitoring. - MturkRequesterServiceID = "mturk-requester" // MturkRequester. - OpsworksServiceID = "opsworks" // Opsworks. - OpsworksCmServiceID = "opsworks-cm" // OpsworksCm. - OrganizationsServiceID = "organizations" // Organizations. - PinpointServiceID = "pinpoint" // Pinpoint. - PollyServiceID = "polly" // Polly. - RdsServiceID = "rds" // Rds. - RedshiftServiceID = "redshift" // Redshift. - RekognitionServiceID = "rekognition" // Rekognition. - ResourceGroupsServiceID = "resource-groups" // ResourceGroups. - Route53ServiceID = "route53" // Route53. - Route53domainsServiceID = "route53domains" // Route53domains. - RuntimeLexServiceID = "runtime.lex" // RuntimeLex. - RuntimeSagemakerServiceID = "runtime.sagemaker" // RuntimeSagemaker. - S3ServiceID = "s3" // S3. - SagemakerServiceID = "sagemaker" // Sagemaker. - SdbServiceID = "sdb" // Sdb. - SecretsmanagerServiceID = "secretsmanager" // Secretsmanager. - ServerlessrepoServiceID = "serverlessrepo" // Serverlessrepo. - ServicecatalogServiceID = "servicecatalog" // Servicecatalog. - ServicediscoveryServiceID = "servicediscovery" // Servicediscovery. - ShieldServiceID = "shield" // Shield. - SmsServiceID = "sms" // Sms. - SnowballServiceID = "snowball" // Snowball. - SnsServiceID = "sns" // Sns. - SqsServiceID = "sqs" // Sqs. - SsmServiceID = "ssm" // Ssm. - StatesServiceID = "states" // States. - StoragegatewayServiceID = "storagegateway" // Storagegateway. - StreamsDynamodbServiceID = "streams.dynamodb" // StreamsDynamodb. - StsServiceID = "sts" // Sts. - SupportServiceID = "support" // Support. - SwfServiceID = "swf" // Swf. - TaggingServiceID = "tagging" // Tagging. - TranslateServiceID = "translate" // Translate. - WafServiceID = "waf" // Waf. - WafRegionalServiceID = "waf-regional" // WafRegional. - WorkdocsServiceID = "workdocs" // Workdocs. - WorkmailServiceID = "workmail" // Workmail. - WorkspacesServiceID = "workspaces" // Workspaces. - XrayServiceID = "xray" // Xray. -) - -// DefaultResolver returns an Endpoint resolver that will be able -// to resolve endpoints for: AWS Standard, AWS China, and AWS GovCloud (US). -// -// Use DefaultPartitions() to get the list of the default partitions. -func DefaultResolver() Resolver { - return defaultPartitions -} - -// DefaultPartitions returns a list of the partitions the SDK is bundled -// with. The available partitions are: AWS Standard, AWS China, and AWS GovCloud (US). -// -// partitions := endpoints.DefaultPartitions -// for _, p := range partitions { -// // ... inspect partitions -// } -func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() -} - -var defaultPartitions = partitions{ - awsPartition, - awscnPartition, - awsusgovPartition, -} - -// AwsPartition returns the Resolver for AWS Standard. -func AwsPartition() Partition { - return awsPartition.Partition() -} - -var awsPartition = partition{ - ID: "aws", - Name: "AWS Standard", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^(us|eu|ap|sa|ca)\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "ap-northeast-1": region{ - Description: "Asia Pacific (Tokyo)", - }, - "ap-northeast-2": region{ - Description: "Asia Pacific (Seoul)", - }, - "ap-south-1": region{ - Description: "Asia Pacific (Mumbai)", - }, - "ap-southeast-1": region{ - Description: "Asia Pacific (Singapore)", - }, - "ap-southeast-2": region{ - Description: "Asia Pacific (Sydney)", - }, - "ca-central-1": region{ - Description: "Canada (Central)", - }, - "eu-central-1": region{ - Description: "EU (Frankfurt)", - }, - "eu-west-1": region{ - Description: "EU (Ireland)", - }, - "eu-west-2": region{ - Description: "EU (London)", - }, - "eu-west-3": region{ - Description: "EU (Paris)", - }, - "sa-east-1": region{ - Description: "South America (Sao Paulo)", - }, - "us-east-1": region{ - Description: "US East (N. Virginia)", - }, - "us-east-2": region{ - Description: "US East (Ohio)", - }, - "us-west-1": region{ - Description: "US West (N. California)", - }, - "us-west-2": region{ - Description: "US West (Oregon)", - }, - }, - Services: services{ - "a4b": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "acm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "acm-pca": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "api.pricing": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "pricing", - }, - }, - Endpoints: endpoints{ - "ap-south-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "apigateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "appstream2": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - CredentialScope: credentialScope{ - Service: "appstream", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "athena": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "autoscaling-plans": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "autoscaling-plans", - }, - }, - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "batch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "budgets": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "budgets.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "ce": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "ce.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloud9": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "clouddirectory": service{ - - Endpoints: endpoints{ - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudfront": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "cloudfront.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudsearch": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codebuild": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "codebuild-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "codebuild-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "codebuild-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "codebuild-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "codecommit": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codepipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "codestar": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-identity": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-idp": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cognito-sync": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "comprehend": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "cur": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "datapipeline": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "dax": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "devicefarm": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "discovery": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "dms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticfilesystem": service{ - - Endpoints: endpoints{ - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.{service}.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{region}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "elastictranscoder": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "email": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "entitlement.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "firehose": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "fms": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "gamelift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "glue": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "greengrass": service{ - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "guardduty": service{ - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "health": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "iam.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "importexport": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "importexport.amazonaws.com", - SignatureVersions: []string{"v2", "v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - Service: "IngestionService", - }, - }, - }, - }, - "inspector": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesisanalytics": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kinesisvideo": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "lightsail": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "machinelearning": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - }, - }, - "marketplacecommerceanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "mediaconvert": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "medialive": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mediapackage": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mediastore": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mgh": service{ - - Endpoints: endpoints{ - "us-west-2": endpoint{}, - }, - }, - "mobileanalytics": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "models.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "mturk-requester": service{ - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "sandbox": endpoint{ - Hostname: "mturk-requester-sandbox.us-east-1.amazonaws.com", - }, - "us-east-1": endpoint{}, - }, - }, - "opsworks": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "opsworks-cm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "organizations": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "organizations.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "pinpoint": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "mobiletargeting", - }, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "polly": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "{service}.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "resource-groups": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "route53": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "route53.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "route53domains": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "runtime.lex": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "lex", - }, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "runtime.sagemaker": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "s3": service{ - PartitionEndpoint: "us-east-1", - IsRegionalized: boxedTrue, - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - - HasDualStack: boxedTrue, - DualStackHostname: "{service}.dualstack.{region}.{dnsSuffix}", - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Hostname: "s3.ap-northeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{ - Hostname: "s3.ap-southeast-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ap-southeast-2": endpoint{ - Hostname: "s3.ap-southeast-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{ - Hostname: "s3.eu-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "s3-external-1": endpoint{ - Hostname: "s3-external-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{ - Hostname: "s3.sa-east-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-1": endpoint{ - Hostname: "s3.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{ - Hostname: "s3.us-west-1.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - "us-west-2": endpoint{ - Hostname: "s3.us-west-2.amazonaws.com", - SignatureVersions: []string{"s3", "s3v4"}, - }, - }, - }, - "sagemaker": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sdb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"v2"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - Hostname: "sdb.amazonaws.com", - }, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "secretsmanager": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "serverlessrepo": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-northeast-2": endpoint{ - Protocols: []string{"https"}, - }, - "ap-south-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-southeast-1": endpoint{ - Protocols: []string{"https"}, - }, - "ap-southeast-2": endpoint{ - Protocols: []string{"https"}, - }, - "ca-central-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-central-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-west-1": endpoint{ - Protocols: []string{"https"}, - }, - "eu-west-2": endpoint{ - Protocols: []string{"https"}, - }, - "sa-east-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-east-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-east-2": endpoint{ - Protocols: []string{"https"}, - }, - "us-west-1": endpoint{ - Protocols: []string{"https"}, - }, - "us-west-2": endpoint{ - Protocols: []string{"https"}, - }, - }, - }, - "servicecatalog": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "servicediscovery": service{ - - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "shield": service{ - IsRegionalized: boxedFalse, - Defaults: endpoint{ - SSLCommonName: "Shield.us-east-1.amazonaws.com", - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{ - SSLCommonName: "queue.{dnsSuffix}", - }, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "states": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "local": endpoint{ - Hostname: "localhost:8000", - Protocols: []string{"http"}, - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "sts": service{ - PartitionEndpoint: "aws-global", - Defaults: endpoint{ - Hostname: "sts.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{ - Hostname: "sts.ap-northeast-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "ap-northeast-2", - }, - }, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "aws-global": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-1-fips": endpoint{ - Hostname: "sts-fips.us-east-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - "us-east-2": endpoint{}, - "us-east-2-fips": endpoint{ - Hostname: "sts-fips.us-east-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-2", - }, - }, - "us-west-1": endpoint{}, - "us-west-1-fips": endpoint{ - Hostname: "sts-fips.us-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-1", - }, - }, - "us-west-2": endpoint{}, - "us-west-2-fips": endpoint{ - Hostname: "sts-fips.us-west-2.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-west-2", - }, - }, - }, - }, - "support": service{ - - Endpoints: endpoints{ - "us-east-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "eu-west-3": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "translate": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "waf": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "waf.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-east-1", - }, - }, - }, - }, - "waf-regional": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workdocs": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workmail": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "eu-west-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "workspaces": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - "xray": service{ - - Endpoints: endpoints{ - "ap-northeast-1": endpoint{}, - "ap-northeast-2": endpoint{}, - "ap-south-1": endpoint{}, - "ap-southeast-1": endpoint{}, - "ap-southeast-2": endpoint{}, - "ca-central-1": endpoint{}, - "eu-central-1": endpoint{}, - "eu-west-1": endpoint{}, - "eu-west-2": endpoint{}, - "sa-east-1": endpoint{}, - "us-east-1": endpoint{}, - "us-east-2": endpoint{}, - "us-west-1": endpoint{}, - "us-west-2": endpoint{}, - }, - }, - }, -} - -// AwsCnPartition returns the Resolver for AWS China. -func AwsCnPartition() Partition { - return awscnPartition.Partition() -} - -var awscnPartition = partition{ - ID: "aws-cn", - Name: "AWS China", - DNSSuffix: "amazonaws.com.cn", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^cn\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "cn-north-1": region{ - Description: "China (Beijing)", - }, - "cn-northwest-1": region{ - Description: "China (Ningxia)", - }, - }, - Services: services{ - "apigateway": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "application-autoscaling": service{ - Defaults: endpoint{ - Hostname: "autoscaling.{region}.amazonaws.com", - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "application-autoscaling", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "autoscaling": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "cognito-identity": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ec2": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - Defaults: endpoint{ - Protocols: []string{"https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "elasticmapreduce": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "cn-northwest-1": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "glacier": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-cn-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-cn-global": endpoint{ - Hostname: "iam.cn-north-1.amazonaws.com.cn", - CredentialScope: credentialScope{ - Region: "cn-north-1", - }, - }, - }, - }, - "iot": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "execute-api", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "monitoring": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - SignatureVersions: []string{"s3v4"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "sns": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sqs": service{ - Defaults: endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - Protocols: []string{"http", "https"}, - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "cn-north-1": endpoint{}, - "cn-northwest-1": endpoint{}, - }, - }, - }, -} - -// AwsUsGovPartition returns the Resolver for AWS GovCloud (US). -func AwsUsGovPartition() Partition { - return awsusgovPartition.Partition() -} - -var awsusgovPartition = partition{ - ID: "aws-us-gov", - Name: "AWS GovCloud (US)", - DNSSuffix: "amazonaws.com", - RegionRegex: regionRegex{ - Regexp: func() *regexp.Regexp { - reg, _ := regexp.Compile("^us\\-gov\\-\\w+\\-\\d+$") - return reg - }(), - }, - Defaults: endpoint{ - Hostname: "{service}.{region}.{dnsSuffix}", - Protocols: []string{"https"}, - SignatureVersions: []string{"v4"}, - }, - Regions: regions{ - "us-gov-west-1": region{ - Description: "AWS GovCloud (US)", - }, - }, - Services: services{ - "acm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "apigateway": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "autoscaling": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "cloudformation": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudhsm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudhsmv2": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "cloudhsm", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "cloudtrail": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "codedeploy": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "config": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "directconnect": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "dms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "dynamodb": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - "us-gov-west-1-fips": endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "ec2": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ec2metadata": service{ - PartitionEndpoint: "aws-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-global": endpoint{ - Hostname: "169.254.169.254/latest", - Protocols: []string{"http"}, - }, - }, - }, - "ecr": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "ecs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticache": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticbeanstalk": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "elasticloadbalancing": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "elasticmapreduce": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "es": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "events": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "glacier": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "iam": service{ - PartitionEndpoint: "aws-us-gov-global", - IsRegionalized: boxedFalse, - - Endpoints: endpoints{ - "aws-us-gov-global": endpoint{ - Hostname: "iam.us-gov.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "kinesis": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "kms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "lambda": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "logs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "metering.marketplace": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "aws-marketplace", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "monitoring": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "polly": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rds": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "redshift": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "rekognition": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "s3": service{ - Defaults: endpoint{ - SignatureVersions: []string{"s3", "s3v4"}, - }, - Endpoints: endpoints{ - "fips-us-gov-west-1": endpoint{ - Hostname: "s3-fips-us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - "us-gov-west-1": endpoint{ - Hostname: "s3.us-gov-west-1.amazonaws.com", - Protocols: []string{"http", "https"}, - }, - }, - }, - "sms": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "snowball": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "sns": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - Protocols: []string{"http", "https"}, - }, - }, - }, - "sqs": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{ - SSLCommonName: "{region}.queue.{dnsSuffix}", - Protocols: []string{"http", "https"}, - }, - }, - }, - "ssm": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "storagegateway": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "streams.dynamodb": service{ - Defaults: endpoint{ - CredentialScope: credentialScope{ - Service: "dynamodb", - }, - }, - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - "us-gov-west-1-fips": endpoint{ - Hostname: "dynamodb.us-gov-west-1.amazonaws.com", - CredentialScope: credentialScope{ - Region: "us-gov-west-1", - }, - }, - }, - }, - "sts": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "swf": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - "tagging": service{ - - Endpoints: endpoints{ - "us-gov-west-1": endpoint{}, - }, - }, - }, -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go deleted file mode 100644 index 84316b92c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/doc.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package endpoints provides the types and functionality for defining regions -// and endpoints, as well as querying those definitions. -// -// The SDK's Regions and Endpoints metadata is code generated into the endpoints -// package, and is accessible via the DefaultResolver function. This function -// returns a endpoint Resolver will search the metadata and build an associated -// endpoint if one is found. The default resolver will search all partitions -// known by the SDK. e.g AWS Standard (aws), AWS China (aws-cn), and -// AWS GovCloud (US) (aws-us-gov). -// . -// -// Enumerating Regions and Endpoint Metadata -// -// Casting the Resolver returned by DefaultResolver to a EnumPartitions interface -// will allow you to get access to the list of underlying Partitions with the -// Partitions method. This is helpful if you want to limit the SDK's endpoint -// resolving to a single partition, or enumerate regions, services, and endpoints -// in the partition. -// -// resolver := endpoints.DefaultResolver() -// partitions := resolver.(endpoints.EnumPartitions).Partitions() -// -// for _, p := range partitions { -// fmt.Println("Regions for", p.ID()) -// for id, _ := range p.Regions() { -// fmt.Println("*", id) -// } -// -// fmt.Println("Services for", p.ID()) -// for id, _ := range p.Services() { -// fmt.Println("*", id) -// } -// } -// -// Using Custom Endpoints -// -// The endpoints package also gives you the ability to use your own logic how -// endpoints are resolved. This is a great way to define a custom endpoint -// for select services, without passing that logic down through your code. -// -// If a type implements the Resolver interface it can be used to resolve -// endpoints. To use this with the SDK's Session and Config set the value -// of the type to the EndpointsResolver field of aws.Config when initializing -// the session, or service client. -// -// In addition the ResolverFunc is a wrapper for a func matching the signature -// of Resolver.EndpointFor, converting it to a type that satisfies the -// Resolver interface. -// -// -// myCustomResolver := func(service, region string, optFns ...func(*endpoints.Options)) (endpoints.ResolvedEndpoint, error) { -// if service == endpoints.S3ServiceID { -// return endpoints.ResolvedEndpoint{ -// URL: "s3.custom.endpoint.com", -// SigningRegion: "custom-signing-region", -// }, nil -// } -// -// return endpoints.DefaultResolver().EndpointFor(service, region, optFns...) -// } -// -// sess := session.Must(session.NewSession(&aws.Config{ -// Region: aws.String("us-west-2"), -// EndpointResolver: endpoints.ResolverFunc(myCustomResolver), -// })) -package endpoints diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go deleted file mode 100644 index e29c09512..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/endpoints.go +++ /dev/null @@ -1,449 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Options provide the configuration needed to direct how the -// endpoints will be resolved. -type Options struct { - // DisableSSL forces the endpoint to be resolved as HTTP. - // instead of HTTPS if the service supports it. - DisableSSL bool - - // Sets the resolver to resolve the endpoint as a dualstack endpoint - // for the service. If dualstack support for a service is not known and - // StrictMatching is not enabled a dualstack endpoint for the service will - // be returned. This endpoint may not be valid. If StrictMatching is - // enabled only services that are known to support dualstack will return - // dualstack endpoints. - UseDualStack bool - - // Enables strict matching of services and regions resolved endpoints. - // If the partition doesn't enumerate the exact service and region an - // error will be returned. This option will prevent returning endpoints - // that look valid, but may not resolve to any real endpoint. - StrictMatching bool - - // Enables resolving a service endpoint based on the region provided if the - // service does not exist. The service endpoint ID will be used as the service - // domain name prefix. By default the endpoint resolver requires the service - // to be known when resolving endpoints. - // - // If resolving an endpoint on the partition list the provided region will - // be used to determine which partition's domain name pattern to the service - // endpoint ID with. If both the service and region are unkonwn and resolving - // the endpoint on partition list an UnknownEndpointError error will be returned. - // - // If resolving and endpoint on a partition specific resolver that partition's - // domain name pattern will be used with the service endpoint ID. If both - // region and service do not exist when resolving an endpoint on a specific - // partition the partition's domain pattern will be used to combine the - // endpoint and region together. - // - // This option is ignored if StrictMatching is enabled. - ResolveUnknownService bool -} - -// Set combines all of the option functions together. -func (o *Options) Set(optFns ...func(*Options)) { - for _, fn := range optFns { - fn(o) - } -} - -// DisableSSLOption sets the DisableSSL options. Can be used as a functional -// option when resolving endpoints. -func DisableSSLOption(o *Options) { - o.DisableSSL = true -} - -// UseDualStackOption sets the UseDualStack option. Can be used as a functional -// option when resolving endpoints. -func UseDualStackOption(o *Options) { - o.UseDualStack = true -} - -// StrictMatchingOption sets the StrictMatching option. Can be used as a functional -// option when resolving endpoints. -func StrictMatchingOption(o *Options) { - o.StrictMatching = true -} - -// ResolveUnknownServiceOption sets the ResolveUnknownService option. Can be used -// as a functional option when resolving endpoints. -func ResolveUnknownServiceOption(o *Options) { - o.ResolveUnknownService = true -} - -// A Resolver provides the interface for functionality to resolve endpoints. -// The build in Partition and DefaultResolver return value satisfy this interface. -type Resolver interface { - EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) -} - -// ResolverFunc is a helper utility that wraps a function so it satisfies the -// Resolver interface. This is useful when you want to add additional endpoint -// resolving logic, or stub out specific endpoints with custom values. -type ResolverFunc func(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) - -// EndpointFor wraps the ResolverFunc function to satisfy the Resolver interface. -func (fn ResolverFunc) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return fn(service, region, opts...) -} - -var schemeRE = regexp.MustCompile("^([^:]+)://") - -// AddScheme adds the HTTP or HTTPS schemes to a endpoint URL if there is no -// scheme. If disableSSL is true HTTP will set HTTP instead of the default HTTPS. -// -// If disableSSL is set, it will only set the URL's scheme if the URL does not -// contain a scheme. -func AddScheme(endpoint string, disableSSL bool) string { - if !schemeRE.MatchString(endpoint) { - scheme := "https" - if disableSSL { - scheme = "http" - } - endpoint = fmt.Sprintf("%s://%s", scheme, endpoint) - } - - return endpoint -} - -// EnumPartitions a provides a way to retrieve the underlying partitions that -// make up the SDK's default Resolver, or any resolver decoded from a model -// file. -// -// Use this interface with DefaultResolver and DecodeModels to get the list of -// Partitions. -type EnumPartitions interface { - Partitions() []Partition -} - -// RegionsForService returns a map of regions for the partition and service. -// If either the partition or service does not exist false will be returned -// as the second parameter. -// -// This example shows how to get the regions for DynamoDB in the AWS partition. -// rs, exists := endpoints.RegionsForService(endpoints.DefaultPartitions(), endpoints.AwsPartitionID, endpoints.DynamodbServiceID) -// -// This is equivalent to using the partition directly. -// rs := endpoints.AwsPartition().Services()[endpoints.DynamodbServiceID].Regions() -func RegionsForService(ps []Partition, partitionID, serviceID string) (map[string]Region, bool) { - for _, p := range ps { - if p.ID() != partitionID { - continue - } - if _, ok := p.p.Services[serviceID]; !ok { - break - } - - s := Service{ - id: serviceID, - p: p.p, - } - return s.Regions(), true - } - - return map[string]Region{}, false -} - -// PartitionForRegion returns the first partition which includes the region -// passed in. This includes both known regions and regions which match -// a pattern supported by the partition which may include regions that are -// not explicitly known by the partition. Use the Regions method of the -// returned Partition if explicit support is needed. -func PartitionForRegion(ps []Partition, regionID string) (Partition, bool) { - for _, p := range ps { - if _, ok := p.p.Regions[regionID]; ok || p.p.RegionRegex.MatchString(regionID) { - return p, true - } - } - - return Partition{}, false -} - -// A Partition provides the ability to enumerate the partition's regions -// and services. -type Partition struct { - id string - p *partition -} - -// ID returns the identifier of the partition. -func (p Partition) ID() string { return p.id } - -// EndpointFor attempts to resolve the endpoint based on service and region. -// See Options for information on configuring how the endpoint is resolved. -// -// If the service cannot be found in the metadata the UnknownServiceError -// error will be returned. This validation will occur regardless if -// StrictMatching is enabled. To enable resolving unknown services set the -// "ResolveUnknownService" option to true. When StrictMatching is disabled -// this option allows the partition resolver to resolve a endpoint based on -// the service endpoint ID provided. -// -// When resolving endpoints you can choose to enable StrictMatching. This will -// require the provided service and region to be known by the partition. -// If the endpoint cannot be strictly resolved an error will be returned. This -// mode is useful to ensure the endpoint resolved is valid. Without -// StrictMatching enabled the endpoint returned my look valid but may not work. -// StrictMatching requires the SDK to be updated if you want to take advantage -// of new regions and services expansions. -// -// Errors that can be returned. -// * UnknownServiceError -// * UnknownEndpointError -func (p Partition) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return p.p.EndpointFor(service, region, opts...) -} - -// Regions returns a map of Regions indexed by their ID. This is useful for -// enumerating over the regions in a partition. -func (p Partition) Regions() map[string]Region { - rs := map[string]Region{} - for id, r := range p.p.Regions { - rs[id] = Region{ - id: id, - desc: r.Description, - p: p.p, - } - } - - return rs -} - -// Services returns a map of Service indexed by their ID. This is useful for -// enumerating over the services in a partition. -func (p Partition) Services() map[string]Service { - ss := map[string]Service{} - for id := range p.p.Services { - ss[id] = Service{ - id: id, - p: p.p, - } - } - - return ss -} - -// A Region provides information about a region, and ability to resolve an -// endpoint from the context of a region, given a service. -type Region struct { - id, desc string - p *partition -} - -// ID returns the region's identifier. -func (r Region) ID() string { return r.id } - -// Description returns the region's description. The region description -// is free text, it can be empty, and it may change between SDK releases. -func (r Region) Description() string { return r.desc } - -// ResolveEndpoint resolves an endpoint from the context of the region given -// a service. See Partition.EndpointFor for usage and errors that can be returned. -func (r Region) ResolveEndpoint(service string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return r.p.EndpointFor(service, r.id, opts...) -} - -// Services returns a list of all services that are known to be in this region. -func (r Region) Services() map[string]Service { - ss := map[string]Service{} - for id, s := range r.p.Services { - if _, ok := s.Endpoints[r.id]; ok { - ss[id] = Service{ - id: id, - p: r.p, - } - } - } - - return ss -} - -// A Service provides information about a service, and ability to resolve an -// endpoint from the context of a service, given a region. -type Service struct { - id string - p *partition -} - -// ID returns the identifier for the service. -func (s Service) ID() string { return s.id } - -// ResolveEndpoint resolves an endpoint from the context of a service given -// a region. See Partition.EndpointFor for usage and errors that can be returned. -func (s Service) ResolveEndpoint(region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - return s.p.EndpointFor(s.id, region, opts...) -} - -// Regions returns a map of Regions that the service is present in. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Regions() map[string]Region { - rs := map[string]Region{} - for id := range s.p.Services[s.id].Endpoints { - if r, ok := s.p.Regions[id]; ok { - rs[id] = Region{ - id: id, - desc: r.Description, - p: s.p, - } - } - } - - return rs -} - -// Endpoints returns a map of Endpoints indexed by their ID for all known -// endpoints for a service. -// -// A region is the AWS region the service exists in. Whereas a Endpoint is -// an URL that can be resolved to a instance of a service. -func (s Service) Endpoints() map[string]Endpoint { - es := map[string]Endpoint{} - for id := range s.p.Services[s.id].Endpoints { - es[id] = Endpoint{ - id: id, - serviceID: s.id, - p: s.p, - } - } - - return es -} - -// A Endpoint provides information about endpoints, and provides the ability -// to resolve that endpoint for the service, and the region the endpoint -// represents. -type Endpoint struct { - id string - serviceID string - p *partition -} - -// ID returns the identifier for an endpoint. -func (e Endpoint) ID() string { return e.id } - -// ServiceID returns the identifier the endpoint belongs to. -func (e Endpoint) ServiceID() string { return e.serviceID } - -// ResolveEndpoint resolves an endpoint from the context of a service and -// region the endpoint represents. See Partition.EndpointFor for usage and -// errors that can be returned. -func (e Endpoint) ResolveEndpoint(opts ...func(*Options)) (ResolvedEndpoint, error) { - return e.p.EndpointFor(e.serviceID, e.id, opts...) -} - -// A ResolvedEndpoint is an endpoint that has been resolved based on a partition -// service, and region. -type ResolvedEndpoint struct { - // The endpoint URL - URL string - - // The region that should be used for signing requests. - SigningRegion string - - // The service name that should be used for signing requests. - SigningName string - - // States that the signing name for this endpoint was derived from metadata - // passed in, but was not explicitly modeled. - SigningNameDerived bool - - // The signing method that should be used for signing requests. - SigningMethod string -} - -// So that the Error interface type can be included as an anonymous field -// in the requestError struct and not conflict with the error.Error() method. -type awsError awserr.Error - -// A EndpointNotFoundError is returned when in StrictMatching mode, and the -// endpoint for the service and region cannot be found in any of the partitions. -type EndpointNotFoundError struct { - awsError - Partition string - Service string - Region string -} - -// A UnknownServiceError is returned when the service does not resolve to an -// endpoint. Includes a list of all known services for the partition. Returned -// when a partition does not support the service. -type UnknownServiceError struct { - awsError - Partition string - Service string - Known []string -} - -// NewUnknownServiceError builds and returns UnknownServiceError. -func NewUnknownServiceError(p, s string, known []string) UnknownServiceError { - return UnknownServiceError{ - awsError: awserr.New("UnknownServiceError", - "could not resolve endpoint for unknown service", nil), - Partition: p, - Service: s, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownServiceError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q", - e.Partition, e.Service) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownServiceError) String() string { - return e.Error() -} - -// A UnknownEndpointError is returned when in StrictMatching mode and the -// service is valid, but the region does not resolve to an endpoint. Includes -// a list of all known endpoints for the service. -type UnknownEndpointError struct { - awsError - Partition string - Service string - Region string - Known []string -} - -// NewUnknownEndpointError builds and returns UnknownEndpointError. -func NewUnknownEndpointError(p, s, r string, known []string) UnknownEndpointError { - return UnknownEndpointError{ - awsError: awserr.New("UnknownEndpointError", - "could not resolve endpoint", nil), - Partition: p, - Service: s, - Region: r, - Known: known, - } -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) Error() string { - extra := fmt.Sprintf("partition: %q, service: %q, region: %q", - e.Partition, e.Service, e.Region) - if len(e.Known) > 0 { - extra += fmt.Sprintf(", known: %v", e.Known) - } - return awserr.SprintError(e.Code(), e.Message(), extra, e.OrigErr()) -} - -// String returns the string representation of the error. -func (e UnknownEndpointError) String() string { - return e.Error() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go deleted file mode 100644 index ff6f76db6..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model.go +++ /dev/null @@ -1,307 +0,0 @@ -package endpoints - -import ( - "fmt" - "regexp" - "strconv" - "strings" -) - -type partitions []partition - -func (ps partitions) EndpointFor(service, region string, opts ...func(*Options)) (ResolvedEndpoint, error) { - var opt Options - opt.Set(opts...) - - for i := 0; i < len(ps); i++ { - if !ps[i].canResolveEndpoint(service, region, opt.StrictMatching) { - continue - } - - return ps[i].EndpointFor(service, region, opts...) - } - - // If loose matching fallback to first partition format to use - // when resolving the endpoint. - if !opt.StrictMatching && len(ps) > 0 { - return ps[0].EndpointFor(service, region, opts...) - } - - return ResolvedEndpoint{}, NewUnknownEndpointError("all partitions", service, region, []string{}) -} - -// Partitions satisfies the EnumPartitions interface and returns a list -// of Partitions representing each partition represented in the SDK's -// endpoints model. -func (ps partitions) Partitions() []Partition { - parts := make([]Partition, 0, len(ps)) - for i := 0; i < len(ps); i++ { - parts = append(parts, ps[i].Partition()) - } - - return parts -} - -type partition struct { - ID string `json:"partition"` - Name string `json:"partitionName"` - DNSSuffix string `json:"dnsSuffix"` - RegionRegex regionRegex `json:"regionRegex"` - Defaults endpoint `json:"defaults"` - Regions regions `json:"regions"` - Services services `json:"services"` -} - -func (p partition) Partition() Partition { - return Partition{ - id: p.ID, - p: &p, - } -} - -func (p partition) canResolveEndpoint(service, region string, strictMatch bool) bool { - s, hasService := p.Services[service] - _, hasEndpoint := s.Endpoints[region] - - if hasEndpoint && hasService { - return true - } - - if strictMatch { - return false - } - - return p.RegionRegex.MatchString(region) -} - -func (p partition) EndpointFor(service, region string, opts ...func(*Options)) (resolved ResolvedEndpoint, err error) { - var opt Options - opt.Set(opts...) - - s, hasService := p.Services[service] - if !(hasService || opt.ResolveUnknownService) { - // Only return error if the resolver will not fallback to creating - // endpoint based on service endpoint ID passed in. - return resolved, NewUnknownServiceError(p.ID, service, serviceList(p.Services)) - } - - e, hasEndpoint := s.endpointForRegion(region) - if !hasEndpoint && opt.StrictMatching { - return resolved, NewUnknownEndpointError(p.ID, service, region, endpointList(s.Endpoints)) - } - - defs := []endpoint{p.Defaults, s.Defaults} - return e.resolve(service, region, p.DNSSuffix, defs, opt), nil -} - -func serviceList(ss services) []string { - list := make([]string, 0, len(ss)) - for k := range ss { - list = append(list, k) - } - return list -} -func endpointList(es endpoints) []string { - list := make([]string, 0, len(es)) - for k := range es { - list = append(list, k) - } - return list -} - -type regionRegex struct { - *regexp.Regexp -} - -func (rr *regionRegex) UnmarshalJSON(b []byte) (err error) { - // Strip leading and trailing quotes - regex, err := strconv.Unquote(string(b)) - if err != nil { - return fmt.Errorf("unable to strip quotes from regex, %v", err) - } - - rr.Regexp, err = regexp.Compile(regex) - if err != nil { - return fmt.Errorf("unable to unmarshal region regex, %v", err) - } - return nil -} - -type regions map[string]region - -type region struct { - Description string `json:"description"` -} - -type services map[string]service - -type service struct { - PartitionEndpoint string `json:"partitionEndpoint"` - IsRegionalized boxedBool `json:"isRegionalized,omitempty"` - Defaults endpoint `json:"defaults"` - Endpoints endpoints `json:"endpoints"` -} - -func (s *service) endpointForRegion(region string) (endpoint, bool) { - if s.IsRegionalized == boxedFalse { - return s.Endpoints[s.PartitionEndpoint], region == s.PartitionEndpoint - } - - if e, ok := s.Endpoints[region]; ok { - return e, true - } - - // Unable to find any matching endpoint, return - // blank that will be used for generic endpoint creation. - return endpoint{}, false -} - -type endpoints map[string]endpoint - -type endpoint struct { - Hostname string `json:"hostname"` - Protocols []string `json:"protocols"` - CredentialScope credentialScope `json:"credentialScope"` - - // Custom fields not modeled - HasDualStack boxedBool `json:"-"` - DualStackHostname string `json:"-"` - - // Signature Version not used - SignatureVersions []string `json:"signatureVersions"` - - // SSLCommonName not used. - SSLCommonName string `json:"sslCommonName"` -} - -const ( - defaultProtocol = "https" - defaultSigner = "v4" -) - -var ( - protocolPriority = []string{"https", "http"} - signerPriority = []string{"v4", "v2"} -) - -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] -} - -func (e endpoint) resolve(service, region, dnsSuffix string, defs []endpoint, opts Options) ResolvedEndpoint { - var merged endpoint - for _, def := range defs { - merged.mergeIn(def) - } - merged.mergeIn(e) - e = merged - - hostname := e.Hostname - - // Offset the hostname for dualstack if enabled - if opts.UseDualStack && e.HasDualStack == boxedTrue { - hostname = e.DualStackHostname - } - - u := strings.Replace(hostname, "{service}", service, 1) - u = strings.Replace(u, "{region}", region, 1) - u = strings.Replace(u, "{dnsSuffix}", dnsSuffix, 1) - - scheme := getEndpointScheme(e.Protocols, opts.DisableSSL) - u = fmt.Sprintf("%s://%s", scheme, u) - - signingRegion := e.CredentialScope.Region - if len(signingRegion) == 0 { - signingRegion = region - } - - signingName := e.CredentialScope.Service - var signingNameDerived bool - if len(signingName) == 0 { - signingName = service - signingNameDerived = true - } - - return ResolvedEndpoint{ - URL: u, - SigningRegion: signingRegion, - SigningName: signingName, - SigningNameDerived: signingNameDerived, - SigningMethod: getByPriority(e.SignatureVersions, signerPriority, defaultSigner), - } -} - -func getEndpointScheme(protocols []string, disableSSL bool) string { - if disableSSL { - return "http" - } - - return getByPriority(protocols, protocolPriority, defaultProtocol) -} - -func (e *endpoint) mergeIn(other endpoint) { - if len(other.Hostname) > 0 { - e.Hostname = other.Hostname - } - if len(other.Protocols) > 0 { - e.Protocols = other.Protocols - } - if len(other.SignatureVersions) > 0 { - e.SignatureVersions = other.SignatureVersions - } - 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.SSLCommonName) > 0 { - e.SSLCommonName = other.SSLCommonName - } - if other.HasDualStack != boxedBoolUnset { - e.HasDualStack = other.HasDualStack - } - if len(other.DualStackHostname) > 0 { - e.DualStackHostname = other.DualStackHostname - } -} - -type credentialScope struct { - Region string `json:"region"` - Service string `json:"service"` -} - -type boxedBool int - -func (b *boxedBool) UnmarshalJSON(buf []byte) error { - v, err := strconv.ParseBool(string(buf)) - if err != nil { - return err - } - - if v { - *b = boxedTrue - } else { - *b = boxedFalse - } - - return nil -} - -const ( - boxedBoolUnset boxedBool = iota - boxedFalse - boxedTrue -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go b/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go deleted file mode 100644 index 05e92df22..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/endpoints/v3model_codegen.go +++ /dev/null @@ -1,337 +0,0 @@ -// +build codegen - -package endpoints - -import ( - "fmt" - "io" - "reflect" - "strings" - "text/template" - "unicode" -) - -// A CodeGenOptions are the options for code generating the endpoints into -// Go code from the endpoints model definition. -type CodeGenOptions struct { - // Options for how the model will be decoded. - DecodeModelOptions DecodeModelOptions -} - -// Set combines all of the option functions together -func (d *CodeGenOptions) Set(optFns ...func(*CodeGenOptions)) { - for _, fn := range optFns { - fn(d) - } -} - -// CodeGenModel given a endpoints model file will decode it and attempt to -// generate Go code from the model definition. Error will be returned if -// the code is unable to be generated, or decoded. -func CodeGenModel(modelFile io.Reader, outFile io.Writer, optFns ...func(*CodeGenOptions)) error { - var opts CodeGenOptions - opts.Set(optFns...) - - resolver, err := DecodeModel(modelFile, func(d *DecodeModelOptions) { - *d = opts.DecodeModelOptions - }) - if err != nil { - return err - } - - tmpl := template.Must(template.New("tmpl").Funcs(funcMap).Parse(v3Tmpl)) - if err := tmpl.ExecuteTemplate(outFile, "defaults", resolver); err != nil { - return fmt.Errorf("failed to execute template, %v", err) - } - - return nil -} - -func toSymbol(v string) string { - out := []rune{} - for _, c := range strings.Title(v) { - if !(unicode.IsNumber(c) || unicode.IsLetter(c)) { - continue - } - - out = append(out, c) - } - - return string(out) -} - -func quoteString(v string) string { - return fmt.Sprintf("%q", v) -} - -func regionConstName(p, r string) string { - return toSymbol(p) + toSymbol(r) -} - -func partitionGetter(id string) string { - return fmt.Sprintf("%sPartition", toSymbol(id)) -} - -func partitionVarName(id string) string { - return fmt.Sprintf("%sPartition", strings.ToLower(toSymbol(id))) -} - -func listPartitionNames(ps partitions) string { - names := []string{} - switch len(ps) { - case 1: - return ps[0].Name - case 2: - return fmt.Sprintf("%s and %s", ps[0].Name, ps[1].Name) - default: - for i, p := range ps { - if i == len(ps)-1 { - names = append(names, "and "+p.Name) - } else { - names = append(names, p.Name) - } - } - return strings.Join(names, ", ") - } -} - -func boxedBoolIfSet(msg string, v boxedBool) string { - switch v { - case boxedTrue: - return fmt.Sprintf(msg, "boxedTrue") - case boxedFalse: - return fmt.Sprintf(msg, "boxedFalse") - default: - return "" - } -} - -func stringIfSet(msg, v string) string { - if len(v) == 0 { - return "" - } - - return fmt.Sprintf(msg, v) -} - -func stringSliceIfSet(msg string, vs []string) string { - if len(vs) == 0 { - return "" - } - - names := []string{} - for _, v := range vs { - names = append(names, `"`+v+`"`) - } - - return fmt.Sprintf(msg, strings.Join(names, ",")) -} - -func endpointIsSet(v endpoint) bool { - return !reflect.DeepEqual(v, endpoint{}) -} - -func serviceSet(ps partitions) map[string]struct{} { - set := map[string]struct{}{} - for _, p := range ps { - for id := range p.Services { - set[id] = struct{}{} - } - } - - return set -} - -var funcMap = template.FuncMap{ - "ToSymbol": toSymbol, - "QuoteString": quoteString, - "RegionConst": regionConstName, - "PartitionGetter": partitionGetter, - "PartitionVarName": partitionVarName, - "ListPartitionNames": listPartitionNames, - "BoxedBoolIfSet": boxedBoolIfSet, - "StringIfSet": stringIfSet, - "StringSliceIfSet": stringSliceIfSet, - "EndpointIsSet": endpointIsSet, - "ServicesSet": serviceSet, -} - -const v3Tmpl = ` -{{ define "defaults" -}} -// Code generated by aws/endpoints/v3model_codegen.go. DO NOT EDIT. - -package endpoints - -import ( - "regexp" -) - - {{ template "partition consts" . }} - - {{ range $_, $partition := . }} - {{ template "partition region consts" $partition }} - {{ end }} - - {{ template "service consts" . }} - - {{ template "endpoint resolvers" . }} -{{- end }} - -{{ define "partition consts" }} - // Partition identifiers - const ( - {{ range $_, $p := . -}} - {{ ToSymbol $p.ID }}PartitionID = {{ QuoteString $p.ID }} // {{ $p.Name }} partition. - {{ end -}} - ) -{{- end }} - -{{ define "partition region consts" }} - // {{ .Name }} partition's regions. - const ( - {{ range $id, $region := .Regions -}} - {{ ToSymbol $id }}RegionID = {{ QuoteString $id }} // {{ $region.Description }}. - {{ end -}} - ) -{{- end }} - -{{ define "service consts" }} - // Service identifiers - const ( - {{ $serviceSet := ServicesSet . -}} - {{ range $id, $_ := $serviceSet -}} - {{ ToSymbol $id }}ServiceID = {{ QuoteString $id }} // {{ ToSymbol $id }}. - {{ end -}} - ) -{{- end }} - -{{ define "endpoint resolvers" }} - // DefaultResolver returns an Endpoint resolver that will be able - // to resolve endpoints for: {{ ListPartitionNames . }}. - // - // Use DefaultPartitions() to get the list of the default partitions. - func DefaultResolver() Resolver { - return defaultPartitions - } - - // DefaultPartitions returns a list of the partitions the SDK is bundled - // with. The available partitions are: {{ ListPartitionNames . }}. - // - // partitions := endpoints.DefaultPartitions - // for _, p := range partitions { - // // ... inspect partitions - // } - func DefaultPartitions() []Partition { - return defaultPartitions.Partitions() - } - - var defaultPartitions = partitions{ - {{ range $_, $partition := . -}} - {{ PartitionVarName $partition.ID }}, - {{ end }} - } - - {{ range $_, $partition := . -}} - {{ $name := PartitionGetter $partition.ID -}} - // {{ $name }} returns the Resolver for {{ $partition.Name }}. - func {{ $name }}() Partition { - return {{ PartitionVarName $partition.ID }}.Partition() - } - var {{ PartitionVarName $partition.ID }} = {{ template "gocode Partition" $partition }} - {{ end }} -{{ end }} - -{{ define "default partitions" }} - func DefaultPartitions() []Partition { - return []partition{ - {{ range $_, $partition := . -}} - // {{ ToSymbol $partition.ID}}Partition(), - {{ end }} - } - } -{{ end }} - -{{ define "gocode Partition" -}} -partition{ - {{ StringIfSet "ID: %q,\n" .ID -}} - {{ StringIfSet "Name: %q,\n" .Name -}} - {{ StringIfSet "DNSSuffix: %q,\n" .DNSSuffix -}} - RegionRegex: {{ template "gocode RegionRegex" .RegionRegex }}, - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults }}, - {{- end }} - Regions: {{ template "gocode Regions" .Regions }}, - Services: {{ template "gocode Services" .Services }}, -} -{{- end }} - -{{ define "gocode RegionRegex" -}} -regionRegex{ - Regexp: func() *regexp.Regexp{ - reg, _ := regexp.Compile({{ QuoteString .Regexp.String }}) - return reg - }(), -} -{{- end }} - -{{ define "gocode Regions" -}} -regions{ - {{ range $id, $region := . -}} - "{{ $id }}": {{ template "gocode Region" $region }}, - {{ end -}} -} -{{- end }} - -{{ define "gocode Region" -}} -region{ - {{ StringIfSet "Description: %q,\n" .Description -}} -} -{{- end }} - -{{ define "gocode Services" -}} -services{ - {{ range $id, $service := . -}} - "{{ $id }}": {{ template "gocode Service" $service }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Service" -}} -service{ - {{ StringIfSet "PartitionEndpoint: %q,\n" .PartitionEndpoint -}} - {{ BoxedBoolIfSet "IsRegionalized: %s,\n" .IsRegionalized -}} - {{ if EndpointIsSet .Defaults -}} - Defaults: {{ template "gocode Endpoint" .Defaults -}}, - {{- end }} - {{ if .Endpoints -}} - Endpoints: {{ template "gocode Endpoints" .Endpoints }}, - {{- end }} -} -{{- end }} - -{{ define "gocode Endpoints" -}} -endpoints{ - {{ range $id, $endpoint := . -}} - "{{ $id }}": {{ template "gocode Endpoint" $endpoint }}, - {{ end }} -} -{{- end }} - -{{ define "gocode Endpoint" -}} -endpoint{ - {{ StringIfSet "Hostname: %q,\n" .Hostname -}} - {{ StringIfSet "SSLCommonName: %q,\n" .SSLCommonName -}} - {{ StringSliceIfSet "Protocols: []string{%s},\n" .Protocols -}} - {{ StringSliceIfSet "SignatureVersions: []string{%s},\n" .SignatureVersions -}} - {{ if or .CredentialScope.Region .CredentialScope.Service -}} - CredentialScope: credentialScope{ - {{ StringIfSet "Region: %q,\n" .CredentialScope.Region -}} - {{ StringIfSet "Service: %q,\n" .CredentialScope.Service -}} - }, - {{- end }} - {{ BoxedBoolIfSet "HasDualStack: %s,\n" .HasDualStack -}} - {{ StringIfSet "DualStackHostname: %q,\n" .DualStackHostname -}} - -} -{{- end }} -` diff --git a/vendor/github.com/aws/aws-sdk-go/aws/errors.go b/vendor/github.com/aws/aws-sdk-go/aws/errors.go deleted file mode 100644 index 576636168..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/errors.go +++ /dev/null @@ -1,17 +0,0 @@ -package aws - -import "github.com/aws/aws-sdk-go/aws/awserr" - -var ( - // ErrMissingRegion is an error that is returned if region configuration is - // not found. - // - // @readonly - ErrMissingRegion = awserr.New("MissingRegion", "could not find region configuration", nil) - - // ErrMissingEndpoint is an error that is returned if an endpoint cannot be - // resolved for a service. - // - // @readonly - ErrMissingEndpoint = awserr.New("MissingEndpoint", "'Endpoint' configuration is required for this service", nil) -) diff --git a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go deleted file mode 100644 index 91a6f277a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/jsonvalue.go +++ /dev/null @@ -1,12 +0,0 @@ -package aws - -// JSONValue is a representation of a grab bag type that will be marshaled -// into a json string. This type can be used just like any other map. -// -// Example: -// -// values := aws.JSONValue{ -// "Foo": "Bar", -// } -// values["Baz"] = "Qux" -type JSONValue map[string]interface{} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/logger.go b/vendor/github.com/aws/aws-sdk-go/aws/logger.go deleted file mode 100644 index 3babb5abd..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/logger.go +++ /dev/null @@ -1,112 +0,0 @@ -package aws - -import ( - "log" - "os" -) - -// A LogLevelType defines the level logging should be performed at. Used to instruct -// the SDK which statements should be logged. -type LogLevelType uint - -// LogLevel returns the pointer to a LogLevel. Should be used to workaround -// not being able to take the address of a non-composite literal. -func LogLevel(l LogLevelType) *LogLevelType { - return &l -} - -// Value returns the LogLevel value or the default value LogOff if the LogLevel -// is nil. Safe to use on nil value LogLevelTypes. -func (l *LogLevelType) Value() LogLevelType { - if l != nil { - return *l - } - return LogOff -} - -// Matches returns true if the v LogLevel is enabled by this LogLevel. Should be -// used with logging sub levels. Is safe to use on nil value LogLevelTypes. If -// LogLevel is nil, will default to LogOff comparison. -func (l *LogLevelType) Matches(v LogLevelType) bool { - c := l.Value() - return c&v == v -} - -// AtLeast returns true if this LogLevel is at least high enough to satisfies v. -// Is safe to use on nil value LogLevelTypes. If LogLevel is nil, will default -// to LogOff comparison. -func (l *LogLevelType) AtLeast(v LogLevelType) bool { - c := l.Value() - return c >= v -} - -const ( - // LogOff states that no logging should be performed by the SDK. This is the - // default state of the SDK, and should be use to disable all logging. - LogOff LogLevelType = iota * 0x1000 - - // LogDebug state that debug output should be logged by the SDK. This should - // be used to inspect request made and responses received. - LogDebug -) - -// Debug Logging Sub Levels -const ( - // LogDebugWithSigning states that the SDK should log request signing and - // presigning events. This should be used to log the signing details of - // requests for debugging. Will also enable LogDebug. - LogDebugWithSigning LogLevelType = LogDebug | (1 << iota) - - // LogDebugWithHTTPBody states the SDK should log HTTP request and response - // HTTP bodys in addition to the headers and path. This should be used to - // see the body content of requests and responses made while using the SDK - // Will also enable LogDebug. - LogDebugWithHTTPBody - - // LogDebugWithRequestRetries states the SDK should log when service requests will - // be retried. This should be used to log when you want to log when service - // requests are being retried. Will also enable LogDebug. - LogDebugWithRequestRetries - - // LogDebugWithRequestErrors states the SDK should log when service requests fail - // to build, send, validate, or unmarshal. - LogDebugWithRequestErrors -) - -// A Logger is a minimalistic interface for the SDK to log messages to. Should -// be used to provide custom logging writers for the SDK to use. -type Logger interface { - Log(...interface{}) -} - -// A LoggerFunc is a convenience type to convert a function taking a variadic -// list of arguments and wrap it so the Logger interface can be used. -// -// Example: -// s3.New(sess, &aws.Config{Logger: aws.LoggerFunc(func(args ...interface{}) { -// fmt.Fprintln(os.Stdout, args...) -// })}) -type LoggerFunc func(...interface{}) - -// Log calls the wrapped function with the arguments provided -func (f LoggerFunc) Log(args ...interface{}) { - f(args...) -} - -// NewDefaultLogger returns a Logger which will write log messages to stdout, and -// use same formatting runes as the stdlib log.Logger -func NewDefaultLogger() Logger { - return &defaultLogger{ - logger: log.New(os.Stdout, "", log.LstdFlags), - } -} - -// A defaultLogger provides a minimalistic logger satisfying the Logger interface. -type defaultLogger struct { - logger *log.Logger -} - -// Log logs the parameters to the stdlib logger. See log.Println. -func (l defaultLogger) Log(args ...interface{}) { - l.logger.Println(args...) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go deleted file mode 100644 index 271da432c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error.go +++ /dev/null @@ -1,19 +0,0 @@ -// +build !appengine,!plan9 - -package request - -import ( - "net" - "os" - "syscall" -) - -func isErrConnectionReset(err error) bool { - if opErr, ok := err.(*net.OpError); ok { - if sysErr, ok := opErr.Err.(*os.SyscallError); ok { - return sysErr.Err == syscall.ECONNRESET - } - } - - return false -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go b/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go deleted file mode 100644 index daf9eca43..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/connection_reset_error_other.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build appengine plan9 - -package request - -import ( - "strings" -) - -func isErrConnectionReset(err error) bool { - return strings.Contains(err.Error(), "connection reset") -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go b/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go deleted file mode 100644 index 802ac88ad..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/handlers.go +++ /dev/null @@ -1,256 +0,0 @@ -package request - -import ( - "fmt" - "strings" -) - -// A Handlers provides a collection of request handlers for various -// stages of handling requests. -type Handlers struct { - Validate HandlerList - Build HandlerList - Sign HandlerList - Send HandlerList - ValidateResponse HandlerList - Unmarshal HandlerList - UnmarshalMeta HandlerList - UnmarshalError HandlerList - Retry HandlerList - AfterRetry HandlerList - Complete HandlerList -} - -// Copy returns of this handler's lists. -func (h *Handlers) Copy() Handlers { - return Handlers{ - Validate: h.Validate.copy(), - Build: h.Build.copy(), - Sign: h.Sign.copy(), - Send: h.Send.copy(), - ValidateResponse: h.ValidateResponse.copy(), - Unmarshal: h.Unmarshal.copy(), - UnmarshalError: h.UnmarshalError.copy(), - UnmarshalMeta: h.UnmarshalMeta.copy(), - Retry: h.Retry.copy(), - AfterRetry: h.AfterRetry.copy(), - Complete: h.Complete.copy(), - } -} - -// Clear removes callback functions for all handlers -func (h *Handlers) Clear() { - h.Validate.Clear() - h.Build.Clear() - h.Send.Clear() - h.Sign.Clear() - h.Unmarshal.Clear() - h.UnmarshalMeta.Clear() - h.UnmarshalError.Clear() - h.ValidateResponse.Clear() - h.Retry.Clear() - h.AfterRetry.Clear() - h.Complete.Clear() -} - -// A HandlerListRunItem represents an entry in the HandlerList which -// is being run. -type HandlerListRunItem struct { - Index int - Handler NamedHandler - Request *Request -} - -// A HandlerList manages zero or more handlers in a list. -type HandlerList struct { - list []NamedHandler - - // Called after each request handler in the list is called. If set - // and the func returns true the HandlerList will continue to iterate - // over the request handlers. If false is returned the HandlerList - // will stop iterating. - // - // Should be used if extra logic to be performed between each handler - // in the list. This can be used to terminate a list's iteration - // based on a condition such as error like, HandlerListStopOnError. - // Or for logging like HandlerListLogItem. - AfterEachFn func(item HandlerListRunItem) bool -} - -// A NamedHandler is a struct that contains a name and function callback. -type NamedHandler struct { - Name string - Fn func(*Request) -} - -// copy creates a copy of the handler list. -func (l *HandlerList) copy() HandlerList { - n := HandlerList{ - AfterEachFn: l.AfterEachFn, - } - if len(l.list) == 0 { - return n - } - - n.list = append(make([]NamedHandler, 0, len(l.list)), l.list...) - return n -} - -// Clear clears the handler list. -func (l *HandlerList) Clear() { - l.list = l.list[0:0] -} - -// Len returns the number of handlers in the list. -func (l *HandlerList) Len() int { - return len(l.list) -} - -// PushBack pushes handler f to the back of the handler list. -func (l *HandlerList) PushBack(f func(*Request)) { - l.PushBackNamed(NamedHandler{"__anonymous", f}) -} - -// PushBackNamed pushes named handler f to the back of the handler list. -func (l *HandlerList) PushBackNamed(n NamedHandler) { - if cap(l.list) == 0 { - l.list = make([]NamedHandler, 0, 5) - } - l.list = append(l.list, n) -} - -// PushFront pushes handler f to the front of the handler list. -func (l *HandlerList) PushFront(f func(*Request)) { - l.PushFrontNamed(NamedHandler{"__anonymous", f}) -} - -// PushFrontNamed pushes named handler f to the front of the handler list. -func (l *HandlerList) PushFrontNamed(n NamedHandler) { - if cap(l.list) == len(l.list) { - // Allocating new list required - l.list = append([]NamedHandler{n}, l.list...) - } else { - // Enough room to prepend into list. - l.list = append(l.list, NamedHandler{}) - copy(l.list[1:], l.list) - l.list[0] = n - } -} - -// Remove removes a NamedHandler n -func (l *HandlerList) Remove(n NamedHandler) { - l.RemoveByName(n.Name) -} - -// RemoveByName removes a NamedHandler by name. -func (l *HandlerList) RemoveByName(name string) { - for i := 0; i < len(l.list); i++ { - m := l.list[i] - if m.Name == name { - // Shift array preventing creating new arrays - copy(l.list[i:], l.list[i+1:]) - l.list[len(l.list)-1] = NamedHandler{} - l.list = l.list[:len(l.list)-1] - - // decrement list so next check to length is correct - i-- - } - } -} - -// SwapNamed will swap out any existing handlers with the same name as the -// passed in NamedHandler returning true if handlers were swapped. False is -// returned otherwise. -func (l *HandlerList) SwapNamed(n NamedHandler) (swapped bool) { - for i := 0; i < len(l.list); i++ { - if l.list[i].Name == n.Name { - l.list[i].Fn = n.Fn - swapped = true - } - } - - return swapped -} - -// SetBackNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the end of the list. -func (l *HandlerList) SetBackNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushBackNamed(n) - } -} - -// SetFrontNamed will replace the named handler if it exists in the handler list. -// If the handler does not exist the handler will be added to the beginning of -// the list. -func (l *HandlerList) SetFrontNamed(n NamedHandler) { - if !l.SwapNamed(n) { - l.PushFrontNamed(n) - } -} - -// Run executes all handlers in the list with a given request object. -func (l *HandlerList) Run(r *Request) { - for i, h := range l.list { - h.Fn(r) - item := HandlerListRunItem{ - Index: i, Handler: h, Request: r, - } - if l.AfterEachFn != nil && !l.AfterEachFn(item) { - return - } - } -} - -// HandlerListLogItem logs the request handler and the state of the -// request's Error value. Always returns true to continue iterating -// request handlers in a HandlerList. -func HandlerListLogItem(item HandlerListRunItem) bool { - if item.Request.Config.Logger == nil { - return true - } - item.Request.Config.Logger.Log("DEBUG: RequestHandler", - item.Index, item.Handler.Name, item.Request.Error) - - return true -} - -// HandlerListStopOnError returns false to stop the HandlerList iterating -// over request handlers if Request.Error is not nil. True otherwise -// to continue iterating. -func HandlerListStopOnError(item HandlerListRunItem) bool { - return item.Request.Error == nil -} - -// WithAppendUserAgent will add a string to the user agent prefixed with a -// single white space. -func WithAppendUserAgent(s string) Option { - return func(r *Request) { - r.Handlers.Build.PushBack(func(r2 *Request) { - AddToUserAgent(r, s) - }) - } -} - -// MakeAddToUserAgentHandler will add the name/version pair to the User-Agent request -// header. If the extra parameters are provided they will be added as metadata to the -// name/version pair resulting in the following format. -// "name/version (extra0; extra1; ...)" -// The user agent part will be concatenated with this current request's user agent string. -func MakeAddToUserAgentHandler(name, version string, extra ...string) func(*Request) { - ua := fmt.Sprintf("%s/%s", name, version) - if len(extra) > 0 { - ua += fmt.Sprintf(" (%s)", strings.Join(extra, "; ")) - } - return func(r *Request) { - AddToUserAgent(r, ua) - } -} - -// MakeAddToUserAgentFreeFormHandler adds the input to the User-Agent request header. -// The input string will be concatenated with the current request's user agent string. -func MakeAddToUserAgentFreeFormHandler(s string) func(*Request) { - return func(r *Request) { - AddToUserAgent(r, s) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go deleted file mode 100644 index 79f79602b..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/http_request.go +++ /dev/null @@ -1,24 +0,0 @@ -package request - -import ( - "io" - "net/http" - "net/url" -) - -func copyHTTPRequest(r *http.Request, body io.ReadCloser) *http.Request { - req := new(http.Request) - *req = *r - req.URL = &url.URL{} - *req.URL = *r.URL - req.Body = body - - req.Header = http.Header{} - for k, v := range r.Header { - for _, vv := range v { - req.Header.Add(k, vv) - } - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go b/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go deleted file mode 100644 index b0c2ef4fe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/offset_reader.go +++ /dev/null @@ -1,60 +0,0 @@ -package request - -import ( - "io" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// offsetReader is a thread-safe io.ReadCloser to prevent racing -// with retrying requests -type offsetReader struct { - buf io.ReadSeeker - lock sync.Mutex - closed bool -} - -func newOffsetReader(buf io.ReadSeeker, offset int64) *offsetReader { - reader := &offsetReader{} - buf.Seek(offset, sdkio.SeekStart) - - reader.buf = buf - return reader -} - -// Close will close the instance of the offset reader's access to -// the underlying io.ReadSeeker. -func (o *offsetReader) Close() error { - o.lock.Lock() - defer o.lock.Unlock() - o.closed = true - return nil -} - -// Read is a thread-safe read of the underlying io.ReadSeeker -func (o *offsetReader) Read(p []byte) (int, error) { - o.lock.Lock() - defer o.lock.Unlock() - - if o.closed { - return 0, io.EOF - } - - return o.buf.Read(p) -} - -// Seek is a thread-safe seeking operation. -func (o *offsetReader) Seek(offset int64, whence int) (int64, error) { - o.lock.Lock() - defer o.lock.Unlock() - - return o.buf.Seek(offset, whence) -} - -// CloseAndCopy will return a new offsetReader with a copy of the old buffer -// and close the old buffer. -func (o *offsetReader) CloseAndCopy(offset int64) *offsetReader { - o.Close() - return newOffsetReader(o.buf, offset) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request.go deleted file mode 100644 index 69b7a01ad..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request.go +++ /dev/null @@ -1,654 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - "io" - "net" - "net/http" - "net/url" - "reflect" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -const ( - // ErrCodeSerialization is the serialization error code that is received - // during protocol unmarshaling. - ErrCodeSerialization = "SerializationError" - - // ErrCodeRead is an error that is returned during HTTP reads. - ErrCodeRead = "ReadError" - - // ErrCodeResponseTimeout is the connection timeout error that is received - // during body reads. - ErrCodeResponseTimeout = "ResponseTimeout" - - // ErrCodeInvalidPresignExpire is returned when the expire time provided to - // presign is invalid - ErrCodeInvalidPresignExpire = "InvalidPresignExpireError" - - // CanceledErrorCode is the error code that will be returned by an - // API request that was canceled. Requests given a aws.Context may - // return this error when canceled. - CanceledErrorCode = "RequestCanceled" -) - -// A Request is the service request to be made. -type Request struct { - Config aws.Config - ClientInfo metadata.ClientInfo - Handlers Handlers - - Retryer - Time time.Time - Operation *Operation - HTTPRequest *http.Request - HTTPResponse *http.Response - Body io.ReadSeeker - BodyStart int64 // offset from beginning of Body that the request body starts - Params interface{} - Error error - Data interface{} - RequestID string - RetryCount int - Retryable *bool - RetryDelay time.Duration - NotHoist bool - SignedHeaderVals http.Header - LastSignedAt time.Time - DisableFollowRedirects bool - - // A value greater than 0 instructs the request to be signed as Presigned URL - // You should not set this field directly. Instead use Request's - // Presign or PresignRequest methods. - ExpireTime time.Duration - - context aws.Context - - built bool - - // Need to persist an intermediate body between the input Body and HTTP - // request body because the HTTP Client's transport can maintain a reference - // to the HTTP request's body after the client has returned. This value is - // safe to use concurrently and wrap the input Body for each HTTP request. - safeBody *offsetReader -} - -// An Operation is the service API operation to be made. -type Operation struct { - Name string - HTTPMethod string - HTTPPath string - *Paginator - - BeforePresignFn func(r *Request) error -} - -// New returns a new Request pointer for the service API -// operation and parameters. -// -// Params is any value of input parameters to be the request payload. -// Data is pointer value to an object which the request's response -// payload will be deserialized to. -func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers, - retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { - - method := operation.HTTPMethod - if method == "" { - method = "POST" - } - - httpReq, _ := http.NewRequest(method, "", nil) - - var err error - httpReq.URL, err = url.Parse(clientInfo.Endpoint + operation.HTTPPath) - if err != nil { - httpReq.URL = &url.URL{} - err = awserr.New("InvalidEndpointURL", "invalid endpoint uri", err) - } - - SanitizeHostForHeader(httpReq) - - r := &Request{ - Config: cfg, - ClientInfo: clientInfo, - Handlers: handlers.Copy(), - - Retryer: retryer, - Time: time.Now(), - ExpireTime: 0, - Operation: operation, - HTTPRequest: httpReq, - Body: nil, - Params: params, - Error: err, - Data: data, - } - r.SetBufferBody([]byte{}) - - return r -} - -// A Option is a functional option that can augment or modify a request when -// using a WithContext API operation method. -type Option func(*Request) - -// WithGetResponseHeader builds a request Option which will retrieve a single -// header value from the HTTP Response. If there are multiple values for the -// header key use WithGetResponseHeaders instead to access the http.Header -// map directly. The passed in val pointer must be non-nil. -// -// This Option can be used multiple times with a single API operation. -// -// var id2, versionID string -// svc.PutObjectWithContext(ctx, params, -// request.WithGetResponseHeader("x-amz-id-2", &id2), -// request.WithGetResponseHeader("x-amz-version-id", &versionID), -// ) -func WithGetResponseHeader(key string, val *string) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *val = req.HTTPResponse.Header.Get(key) - }) - } -} - -// WithGetResponseHeaders builds a request Option which will retrieve the -// headers from the HTTP response and assign them to the passed in headers -// variable. The passed in headers pointer must be non-nil. -// -// var headers http.Header -// svc.PutObjectWithContext(ctx, params, request.WithGetResponseHeaders(&headers)) -func WithGetResponseHeaders(headers *http.Header) Option { - return func(r *Request) { - r.Handlers.Complete.PushBack(func(req *Request) { - *headers = req.HTTPResponse.Header - }) - } -} - -// WithLogLevel is a request option that will set the request to use a specific -// log level when the request is made. -// -// svc.PutObjectWithContext(ctx, params, request.WithLogLevel(aws.LogDebugWithHTTPBody) -func WithLogLevel(l aws.LogLevelType) Option { - return func(r *Request) { - r.Config.LogLevel = aws.LogLevel(l) - } -} - -// ApplyOptions will apply each option to the request calling them in the order -// the were provided. -func (r *Request) ApplyOptions(opts ...Option) { - for _, opt := range opts { - opt(r) - } -} - -// Context will always returns a non-nil context. If Request does not have a -// context aws.BackgroundContext will be returned. -func (r *Request) Context() aws.Context { - if r.context != nil { - return r.context - } - return aws.BackgroundContext() -} - -// SetContext adds a Context to the current request that can be used to cancel -// a in-flight request. The Context value must not be nil, or this method will -// panic. -// -// Unlike http.Request.WithContext, SetContext does not return a copy of the -// Request. It is not safe to use use a single Request value for multiple -// requests. A new Request should be created for each API operation request. -// -// Go 1.6 and below: -// The http.Request's Cancel field will be set to the Done() value of -// the context. This will overwrite the Cancel field's value. -// -// Go 1.7 and above: -// The http.Request.WithContext will be used to set the context on the underlying -// http.Request. This will create a shallow copy of the http.Request. The SDK -// may create sub contexts in the future for nested requests such as retries. -func (r *Request) SetContext(ctx aws.Context) { - if ctx == nil { - panic("context cannot be nil") - } - setRequestContext(r, ctx) -} - -// WillRetry returns if the request's can be retried. -func (r *Request) WillRetry() bool { - if !aws.IsReaderSeekable(r.Body) && r.HTTPRequest.Body != NoBody { - return false - } - return r.Error != nil && aws.BoolValue(r.Retryable) && r.RetryCount < r.MaxRetries() -} - -// ParamsFilled returns if the request's parameters have been populated -// and the parameters are valid. False is returned if no parameters are -// provided or invalid. -func (r *Request) ParamsFilled() bool { - return r.Params != nil && reflect.ValueOf(r.Params).Elem().IsValid() -} - -// DataFilled returns true if the request's data for response deserialization -// target has been set and is a valid. False is returned if data is not -// set, or is invalid. -func (r *Request) DataFilled() bool { - return r.Data != nil && reflect.ValueOf(r.Data).Elem().IsValid() -} - -// SetBufferBody will set the request's body bytes that will be sent to -// the service API. -func (r *Request) SetBufferBody(buf []byte) { - r.SetReaderBody(bytes.NewReader(buf)) -} - -// SetStringBody sets the body of the request to be backed by a string. -func (r *Request) SetStringBody(s string) { - r.SetReaderBody(strings.NewReader(s)) -} - -// SetReaderBody will set the request's body reader. -func (r *Request) SetReaderBody(reader io.ReadSeeker) { - r.Body = reader - r.BodyStart, _ = reader.Seek(0, sdkio.SeekCurrent) // Get the Bodies current offset. - r.ResetBody() -} - -// Presign returns the request's signed URL. Error will be returned -// if the signing fails. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -func (r *Request) Presign(expire time.Duration) (string, error) { - r = r.copy() - - // Presign requires all headers be hoisted. There is no way to retrieve - // the signed headers not hoisted without this. Making the presigned URL - // useless. - r.NotHoist = false - - u, _, err := getPresignedURL(r, expire) - return u, err -} - -// PresignRequest behaves just like presign, with the addition of returning a -// set of headers that were signed. -// -// It is invalid to create a presigned URL with a expire duration 0 or less. An -// error is returned if expire duration is 0 or less. -// -// Returns the URL string for the API operation with signature in the query string, -// and the HTTP headers that were included in the signature. These headers must -// be included in any HTTP request made with the presigned URL. -// -// To prevent hoisting any headers to the query string set NotHoist to true on -// this Request value prior to calling PresignRequest. -func (r *Request) PresignRequest(expire time.Duration) (string, http.Header, error) { - r = r.copy() - return getPresignedURL(r, expire) -} - -// IsPresigned returns true if the request represents a presigned API url. -func (r *Request) IsPresigned() bool { - return r.ExpireTime != 0 -} - -func getPresignedURL(r *Request, expire time.Duration) (string, http.Header, error) { - if expire <= 0 { - return "", nil, awserr.New( - ErrCodeInvalidPresignExpire, - "presigned URL requires an expire duration greater than 0", - nil, - ) - } - - r.ExpireTime = expire - - if r.Operation.BeforePresignFn != nil { - if err := r.Operation.BeforePresignFn(r); err != nil { - return "", nil, err - } - } - - if err := r.Sign(); err != nil { - return "", nil, err - } - - return r.HTTPRequest.URL.String(), r.SignedHeaderVals, nil -} - -func debugLogReqError(r *Request, stage string, retrying bool, err error) { - if !r.Config.LogLevel.Matches(aws.LogDebugWithRequestErrors) { - return - } - - retryStr := "not retrying" - if retrying { - retryStr = "will retry" - } - - r.Config.Logger.Log(fmt.Sprintf("DEBUG: %s %s/%s failed, %s, error %v", - stage, r.ClientInfo.ServiceName, r.Operation.Name, retryStr, err)) -} - -// Build will build the request's object so it can be signed and sent -// to the service. Build will also validate all the request's parameters. -// Any additional build Handlers set on this request will be run -// in the order they were set. -// -// The request will only be built once. Multiple calls to build will have -// no effect. -// -// If any Validate or Build errors occur the build will stop and the error -// which occurred will be returned. -func (r *Request) Build() error { - if !r.built { - r.Handlers.Validate.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Request", false, r.Error) - return r.Error - } - r.Handlers.Build.Run(r) - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - r.built = true - } - - return r.Error -} - -// Sign will sign the request returning error if errors are encountered. -// -// Send will build the request prior to signing. All Sign Handlers will -// be executed in the order they were set. -func (r *Request) Sign() error { - r.Build() - if r.Error != nil { - debugLogReqError(r, "Build Request", false, r.Error) - return r.Error - } - - r.Handlers.Sign.Run(r) - return r.Error -} - -func (r *Request) getNextRequestBody() (io.ReadCloser, error) { - if r.safeBody != nil { - r.safeBody.Close() - } - - r.safeBody = newOffsetReader(r.Body, r.BodyStart) - - // Go 1.8 tightened and clarified the rules code needs to use when building - // requests with the http package. Go 1.8 removed the automatic detection - // of if the Request.Body was empty, or actually had bytes in it. The SDK - // always sets the Request.Body even if it is empty and should not actually - // be sent. This is incorrect. - // - // Go 1.8 did add a http.NoBody value that the SDK can use to tell the http - // client that the request really should be sent without a body. The - // Request.Body cannot be set to nil, which is preferable, because the - // field is exported and could introduce nil pointer dereferences for users - // of the SDK if they used that field. - // - // Related golang/go#18257 - l, err := aws.SeekerLen(r.Body) - if err != nil { - return nil, awserr.New(ErrCodeSerialization, "failed to compute request body size", err) - } - - var body io.ReadCloser - if l == 0 { - body = NoBody - } else if l > 0 { - body = r.safeBody - } else { - // Hack to prevent sending bodies for methods where the body - // should be ignored by the server. Sending bodies on these - // methods without an associated ContentLength will cause the - // request to socket timeout because the server does not handle - // Transfer-Encoding: chunked bodies for these methods. - // - // This would only happen if a aws.ReaderSeekerCloser was used with - // a io.Reader that was not also an io.Seeker, or did not implement - // Len() method. - switch r.Operation.HTTPMethod { - case "GET", "HEAD", "DELETE": - body = NoBody - default: - body = r.safeBody - } - } - - return body, nil -} - -// GetBody will return an io.ReadSeeker of the Request's underlying -// input body with a concurrency safe wrapper. -func (r *Request) GetBody() io.ReadSeeker { - return r.safeBody -} - -// Send will send the request returning error if errors are encountered. -// -// Send will sign the request prior to sending. All Send Handlers will -// be executed in the order they were set. -// -// Canceling a request is non-deterministic. If a request has been canceled, -// then the transport will choose, randomly, one of the state channels during -// reads or getting the connection. -// -// readLoop() and getConn(req *Request, cm connectMethod) -// https://github.com/golang/go/blob/master/src/net/http/transport.go -// -// Send will not close the request.Request's body. -func (r *Request) Send() error { - defer func() { - // Regardless of success or failure of the request trigger the Complete - // request handlers. - r.Handlers.Complete.Run(r) - }() - - for { - if aws.BoolValue(r.Retryable) { - if r.Config.LogLevel.Matches(aws.LogDebugWithRequestRetries) { - r.Config.Logger.Log(fmt.Sprintf("DEBUG: Retrying Request %s/%s, attempt %d", - r.ClientInfo.ServiceName, r.Operation.Name, r.RetryCount)) - } - - // The previous http.Request will have a reference to the r.Body - // and the HTTP Client's Transport may still be reading from - // the request's body even though the Client's Do returned. - r.HTTPRequest = copyHTTPRequest(r.HTTPRequest, nil) - r.ResetBody() - - // Closing response body to ensure that no response body is leaked - // between retry attempts. - if r.HTTPResponse != nil && r.HTTPResponse.Body != nil { - r.HTTPResponse.Body.Close() - } - } - - r.Sign() - if r.Error != nil { - return r.Error - } - - r.Retryable = nil - - r.Handlers.Send.Run(r) - if r.Error != nil { - if !shouldRetryCancel(r) { - return r.Error - } - - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Send Request", false, err) - return r.Error - } - debugLogReqError(r, "Send Request", true, err) - continue - } - r.Handlers.UnmarshalMeta.Run(r) - r.Handlers.ValidateResponse.Run(r) - if r.Error != nil { - r.Handlers.UnmarshalError.Run(r) - err := r.Error - - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Validate Response", false, err) - return r.Error - } - debugLogReqError(r, "Validate Response", true, err) - continue - } - - r.Handlers.Unmarshal.Run(r) - if r.Error != nil { - err := r.Error - r.Handlers.Retry.Run(r) - r.Handlers.AfterRetry.Run(r) - if r.Error != nil { - debugLogReqError(r, "Unmarshal Response", false, err) - return r.Error - } - debugLogReqError(r, "Unmarshal Response", true, err) - continue - } - - break - } - - return nil -} - -// copy will copy a request which will allow for local manipulation of the -// request. -func (r *Request) copy() *Request { - req := &Request{} - *req = *r - req.Handlers = r.Handlers.Copy() - op := *r.Operation - req.Operation = &op - return req -} - -// AddToUserAgent adds the string to the end of the request's current user agent. -func AddToUserAgent(r *Request, s string) { - curUA := r.HTTPRequest.Header.Get("User-Agent") - if len(curUA) > 0 { - s = curUA + " " + s - } - r.HTTPRequest.Header.Set("User-Agent", s) -} - -func shouldRetryCancel(r *Request) bool { - awsErr, ok := r.Error.(awserr.Error) - timeoutErr := false - errStr := r.Error.Error() - if ok { - if awsErr.Code() == CanceledErrorCode { - return false - } - err := awsErr.OrigErr() - netErr, netOK := err.(net.Error) - timeoutErr = netOK && netErr.Temporary() - if urlErr, ok := err.(*url.Error); !timeoutErr && ok { - errStr = urlErr.Err.Error() - } - } - - // There can be two types of canceled errors here. - // The first being a net.Error and the other being an error. - // If the request was timed out, we want to continue the retry - // process. Otherwise, return the canceled error. - return timeoutErr || - (errStr != "net/http: request canceled" && - errStr != "net/http: request canceled while waiting for connection") - -} - -// 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/aws/request/request_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go deleted file mode 100644 index 869b97a1a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_7.go +++ /dev/null @@ -1,39 +0,0 @@ -// +build !go1.8 - -package request - -import "io" - -// NoBody is an io.ReadCloser with no bytes. Read always returns EOF -// and Close always returns nil. It can be used in an outgoing client -// request to explicitly signal that a request has zero bytes. -// An alternative, however, is to simply set Request.Body to nil. -// -// Copy of Go 1.8 NoBody type from net/http/http.go -type noBody struct{} - -func (noBody) Read([]byte) (int, error) { return 0, io.EOF } -func (noBody) Close() error { return nil } -func (noBody) WriteTo(io.Writer) (int64, error) { return 0, nil } - -// NoBody is an empty reader that will trigger the Go HTTP client to not include -// and body in the HTTP request. -var NoBody = noBody{} - -// ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go deleted file mode 100644 index c32fc69bc..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_1_8.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build go1.8 - -package request - -import ( - "net/http" -) - -// NoBody is a http.NoBody reader instructing Go HTTP client to not include -// and body in the HTTP request. -var NoBody = http.NoBody - -// ResetBody rewinds the request body back to its starting position, and -// set's the HTTP Request body reference. When the body is read prior -// to being sent in the HTTP request it will need to be rewound. -// -// ResetBody will automatically be called by the SDK's build handler, but if -// the request is being used directly ResetBody must be called before the request -// is Sent. SetStringBody, SetBufferBody, and SetReaderBody will automatically -// call ResetBody. -// -// Will also set the Go 1.8's http.Request.GetBody member to allow retrying -// PUT/POST redirects. -func (r *Request) ResetBody() { - body, err := r.getNextRequestBody() - if err != nil { - r.Error = err - return - } - - r.HTTPRequest.Body = body - r.HTTPRequest.GetBody = r.getNextRequestBody -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go deleted file mode 100644 index a7365cd1e..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest = r.HTTPRequest.WithContext(ctx) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go deleted file mode 100644 index 307fa0705..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_context_1_6.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !go1.7 - -package request - -import "github.com/aws/aws-sdk-go/aws" - -// setContext updates the Request to use the passed in context for cancellation. -// Context will also be used for request retry delay. -// -// Creates shallow copy of the http.Request with the WithContext method. -func setRequestContext(r *Request, ctx aws.Context) { - r.context = ctx - r.HTTPRequest.Cancel = ctx.Done() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go b/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go deleted file mode 100644 index 159518a75..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/request_pagination.go +++ /dev/null @@ -1,251 +0,0 @@ -package request - -import ( - "reflect" - "sync/atomic" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// A Pagination provides paginating of SDK API operations which are paginatable. -// Generally you should not use this type directly, but use the "Pages" API -// operations method to automatically perform pagination for you. Such as, -// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods. -// -// Pagination differs from a Paginator type in that pagination is the type that -// does the pagination between API operations, and Paginator defines the -// configuration that will be used per page request. -// -// cont := true -// for p.Next() && cont { -// data := p.Page().(*s3.ListObjectsOutput) -// // process the page's data -// } -// return p.Err() -// -// See service client API operation Pages methods for examples how the SDK will -// use the Pagination type. -type Pagination struct { - // Function to return a Request value for each pagination request. - // Any configuration or handlers that need to be applied to the request - // prior to getting the next page should be done here before the request - // returned. - // - // NewRequest should always be built from the same API operations. It is - // undefined if different API operations are returned on subsequent calls. - NewRequest func() (*Request, error) - - started bool - nextTokens []interface{} - - err error - curPage interface{} -} - -// HasNextPage will return true if Pagination is able to determine that the API -// operation has additional pages. False will be returned if there are no more -// pages remaining. -// -// Will always return true if Next has not been called yet. -func (p *Pagination) HasNextPage() bool { - return !(p.started && len(p.nextTokens) == 0) -} - -// Err returns the error Pagination encountered when retrieving the next page. -func (p *Pagination) Err() error { - return p.err -} - -// Page returns the current page. Page should only be called after a successful -// call to Next. It is undefined what Page will return if Page is called after -// Next returns false. -func (p *Pagination) Page() interface{} { - return p.curPage -} - -// Next will attempt to retrieve the next page for the API operation. When a page -// is retrieved true will be returned. If the page cannot be retrieved, or there -// are no more pages false will be returned. -// -// Use the Page method to retrieve the current page data. The data will need -// to be cast to the API operation's output type. -// -// Use the Err method to determine if an error occurred if Page returns false. -func (p *Pagination) Next() bool { - if !p.HasNextPage() { - return false - } - - req, err := p.NewRequest() - if err != nil { - p.err = err - return false - } - - if p.started { - for i, intok := range req.Operation.InputTokens { - awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i]) - } - } - p.started = true - - err = req.Send() - if err != nil { - p.err = err - return false - } - - p.nextTokens = req.nextPageTokens() - p.curPage = req.Data - - return true -} - -// A Paginator is the configuration data that defines how an API operation -// should be paginated. This type is used by the API service models to define -// the generated pagination config for service APIs. -// -// The Pagination type is what provides iterating between pages of an API. It -// is only used to store the token metadata the SDK should use for performing -// pagination. -type Paginator struct { - InputTokens []string - OutputTokens []string - LimitToken string - TruncationToken string -} - -// nextPageTokens returns the tokens to use when asking for the next page of data. -func (r *Request) nextPageTokens() []interface{} { - if r.Operation.Paginator == nil { - return nil - } - if r.Operation.TruncationToken != "" { - tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken) - if len(tr) == 0 { - return nil - } - - switch v := tr[0].(type) { - case *bool: - if !aws.BoolValue(v) { - return nil - } - case bool: - if v == false { - return nil - } - } - } - - tokens := []interface{}{} - tokenAdded := false - for _, outToken := range r.Operation.OutputTokens { - vs, _ := awsutil.ValuesAtPath(r.Data, outToken) - if len(vs) == 0 { - tokens = append(tokens, nil) - continue - } - v := vs[0] - - switch tv := v.(type) { - case *string: - if len(aws.StringValue(tv)) == 0 { - tokens = append(tokens, nil) - continue - } - case string: - if len(tv) == 0 { - tokens = append(tokens, nil) - continue - } - } - - tokenAdded = true - tokens = append(tokens, v) - } - if !tokenAdded { - return nil - } - - return tokens -} - -// Ensure a deprecated item is only logged once instead of each time its used. -func logDeprecatedf(logger aws.Logger, flag *int32, msg string) { - if logger == nil { - return - } - if atomic.CompareAndSwapInt32(flag, 0, 1) { - logger.Log(msg) - } -} - -var ( - logDeprecatedHasNextPage int32 - logDeprecatedNextPage int32 - logDeprecatedEachPage int32 -) - -// HasNextPage returns true if this request has more pages of data available. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) HasNextPage() bool { - logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage, - "Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations") - - return len(r.nextPageTokens()) > 0 -} - -// NextPage returns a new Request that can be executed to return the next -// page of result data. Call .Send() on this request to execute it. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) NextPage() *Request { - logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage, - "Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations") - - tokens := r.nextPageTokens() - if len(tokens) == 0 { - return nil - } - - data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface() - nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data) - for i, intok := range nr.Operation.InputTokens { - awsutil.SetValueAtPath(nr.Params, intok, tokens[i]) - } - return nr -} - -// EachPage iterates over each page of a paginated request object. The fn -// parameter should be a function with the following sample signature: -// -// func(page *T, lastPage bool) bool { -// return true // return false to stop iterating -// } -// -// Where "T" is the structure type matching the output structure of the given -// operation. For example, a request object generated by -// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput -// as the structure "T". The lastPage value represents whether the page is -// the last page of data or not. The return value of this function should -// return true to keep iterating or false to stop. -// -// Deprecated Use Pagination type for configurable pagination of API operations -func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error { - logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage, - "Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations") - - for page := r; page != nil; page = page.NextPage() { - if err := page.Send(); err != nil { - return err - } - if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage { - return page.Error - } - } - - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go deleted file mode 100644 index f35fef213..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/retryer.go +++ /dev/null @@ -1,161 +0,0 @@ -package request - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" -) - -// Retryer is an interface to control retry logic for a given service. -// The default implementation used by most services is the client.DefaultRetryer -// structure, which contains basic retry logic using exponential backoff. -type Retryer interface { - RetryRules(*Request) time.Duration - ShouldRetry(*Request) bool - MaxRetries() int -} - -// WithRetryer sets a config Retryer value to the given Config returning it -// for chaining. -func WithRetryer(cfg *aws.Config, retryer Retryer) *aws.Config { - cfg.Retryer = retryer - return cfg -} - -// retryableCodes is a collection of service response codes which are retry-able -// without any further action. -var retryableCodes = map[string]struct{}{ - "RequestError": {}, - "RequestTimeout": {}, - ErrCodeResponseTimeout: {}, - "RequestTimeoutException": {}, // Glacier's flavor of RequestTimeout -} - -var throttleCodes = map[string]struct{}{ - "ProvisionedThroughputExceededException": {}, - "Throttling": {}, - "ThrottlingException": {}, - "RequestLimitExceeded": {}, - "RequestThrottled": {}, - "TooManyRequestsException": {}, // Lambda functions - "PriorRequestNotComplete": {}, // Route53 -} - -// credsExpiredCodes is a collection of error codes which signify the credentials -// need to be refreshed. Expired tokens require refreshing of credentials, and -// resigning before the request can be retried. -var credsExpiredCodes = map[string]struct{}{ - "ExpiredToken": {}, - "ExpiredTokenException": {}, - "RequestExpired": {}, // EC2 Only -} - -func isCodeThrottle(code string) bool { - _, ok := throttleCodes[code] - return ok -} - -func isCodeRetryable(code string) bool { - if _, ok := retryableCodes[code]; ok { - return true - } - - return isCodeExpiredCreds(code) -} - -func isCodeExpiredCreds(code string) bool { - _, ok := credsExpiredCodes[code] - return ok -} - -var validParentCodes = map[string]struct{}{ - ErrCodeSerialization: {}, - ErrCodeRead: {}, -} - -type temporaryError interface { - Temporary() bool -} - -func isNestedErrorRetryable(parentErr awserr.Error) bool { - if parentErr == nil { - return false - } - - if _, ok := validParentCodes[parentErr.Code()]; !ok { - return false - } - - err := parentErr.OrigErr() - if err == nil { - return false - } - - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) - } - - if t, ok := err.(temporaryError); ok { - return t.Temporary() - } - - return isErrConnectionReset(err) -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if error is nil. -func IsErrorRetryable(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeRetryable(aerr.Code()) || isNestedErrorRetryable(aerr) - } - } - return false -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if error is nil. -func IsErrorThrottle(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeThrottle(aerr.Code()) - } - } - return false -} - -// IsErrorExpiredCreds returns whether the error code is a credential expiry error. -// Returns false if error is nil. -func IsErrorExpiredCreds(err error) bool { - if err != nil { - if aerr, ok := err.(awserr.Error); ok { - return isCodeExpiredCreds(aerr.Code()) - } - } - return false -} - -// IsErrorRetryable returns whether the error is retryable, based on its Code. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorRetryable -func (r *Request) IsErrorRetryable() bool { - return IsErrorRetryable(r.Error) -} - -// IsErrorThrottle returns whether the error is to be throttled based on its code. -// Returns false if the request has no Error set -// -// Alias for the utility function IsErrorThrottle -func (r *Request) IsErrorThrottle() bool { - return IsErrorThrottle(r.Error) -} - -// IsErrorExpired returns whether the error code is a credential expiry error. -// Returns false if the request has no Error set. -// -// Alias for the utility function IsErrorExpiredCreds -func (r *Request) IsErrorExpired() bool { - return IsErrorExpiredCreds(r.Error) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go b/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go deleted file mode 100644 index 09a44eb98..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/timeout_read_closer.go +++ /dev/null @@ -1,94 +0,0 @@ -package request - -import ( - "io" - "time" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -var timeoutErr = awserr.New( - ErrCodeResponseTimeout, - "read on body has reached the timeout limit", - nil, -) - -type readResult struct { - n int - err error -} - -// timeoutReadCloser will handle body reads that take too long. -// We will return a ErrReadTimeout error if a timeout occurs. -type timeoutReadCloser struct { - reader io.ReadCloser - duration time.Duration -} - -// Read will spin off a goroutine to call the reader's Read method. We will -// select on the timer's channel or the read's channel. Whoever completes first -// will be returned. -func (r *timeoutReadCloser) Read(b []byte) (int, error) { - timer := time.NewTimer(r.duration) - c := make(chan readResult, 1) - - go func() { - n, err := r.reader.Read(b) - timer.Stop() - c <- readResult{n: n, err: err} - }() - - select { - case data := <-c: - return data.n, data.err - case <-timer.C: - return 0, timeoutErr - } -} - -func (r *timeoutReadCloser) Close() error { - return r.reader.Close() -} - -const ( - // HandlerResponseTimeout is what we use to signify the name of the - // response timeout handler. - HandlerResponseTimeout = "ResponseTimeoutHandler" -) - -// adaptToResponseTimeoutError is a handler that will replace any top level error -// to a ErrCodeResponseTimeout, if its child is that. -func adaptToResponseTimeoutError(req *Request) { - if err, ok := req.Error.(awserr.Error); ok { - aerr, ok := err.OrigErr().(awserr.Error) - if ok && aerr.Code() == ErrCodeResponseTimeout { - req.Error = aerr - } - } -} - -// WithResponseReadTimeout is a request option that will wrap the body in a timeout read closer. -// This will allow for per read timeouts. If a timeout occurred, we will return the -// ErrCodeResponseTimeout. -// -// svc.PutObjectWithContext(ctx, params, request.WithTimeoutReadCloser(30 * time.Second) -func WithResponseReadTimeout(duration time.Duration) Option { - return func(r *Request) { - - var timeoutHandler = NamedHandler{ - HandlerResponseTimeout, - func(req *Request) { - req.HTTPResponse.Body = &timeoutReadCloser{ - reader: req.HTTPResponse.Body, - duration: duration, - } - }} - - // remove the handler so we are not stomping over any new durations. - r.Handlers.Send.RemoveByName(HandlerResponseTimeout) - r.Handlers.Send.PushBackNamed(timeoutHandler) - - r.Handlers.Unmarshal.PushBack(adaptToResponseTimeoutError) - r.Handlers.UnmarshalError.PushBack(adaptToResponseTimeoutError) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go b/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go deleted file mode 100644 index 401246228..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/validation.go +++ /dev/null @@ -1,234 +0,0 @@ -package request - -import ( - "bytes" - "fmt" - - "github.com/aws/aws-sdk-go/aws/awserr" -) - -const ( - // InvalidParameterErrCode is the error code for invalid parameters errors - InvalidParameterErrCode = "InvalidParameter" - // ParamRequiredErrCode is the error code for required parameter errors - ParamRequiredErrCode = "ParamRequiredError" - // ParamMinValueErrCode is the error code for fields with too low of a - // number value. - ParamMinValueErrCode = "ParamMinValueError" - // ParamMinLenErrCode is the error code for fields without enough elements. - ParamMinLenErrCode = "ParamMinLenError" -) - -// Validator provides a way for types to perform validation logic on their -// input values that external code can use to determine if a type's values -// are valid. -type Validator interface { - Validate() error -} - -// An ErrInvalidParams provides wrapping of invalid parameter errors found when -// validating API operation input parameters. -type ErrInvalidParams struct { - // Context is the base context of the invalid parameter group. - Context string - errs []ErrInvalidParam -} - -// 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 *ErrInvalidParams) Add(err ErrInvalidParam) { - err.SetContext(e.Context) - e.errs = append(e.errs, err) -} - -// AddNested adds the invalid parameter errors from another ErrInvalidParams -// 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 *ErrInvalidParams) AddNested(nestedCtx string, nested ErrInvalidParams) { - 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 ErrInvalidParams) Len() int { - return len(e.errs) -} - -// Code returns the code of the error -func (e ErrInvalidParams) Code() string { - return InvalidParameterErrCode -} - -// Message returns the message of the error -func (e ErrInvalidParams) Message() string { - return fmt.Sprintf("%d validation error(s) found.", len(e.errs)) -} - -// Error returns the string formatted form of the invalid parameters. -func (e ErrInvalidParams) Error() string { - w := &bytes.Buffer{} - fmt.Fprintf(w, "%s: %s\n", e.Code(), e.Message()) - - for _, err := range e.errs { - fmt.Fprintf(w, "- %s\n", err.Message()) - } - - return w.String() -} - -// OrigErr returns the invalid parameters as a awserr.BatchedErrors value -func (e ErrInvalidParams) OrigErr() error { - return awserr.NewBatchError( - InvalidParameterErrCode, e.Message(), e.OrigErrs()) -} - -// OrigErrs returns a slice of the invalid parameters -func (e ErrInvalidParams) OrigErrs() []error { - errs := make([]error, len(e.errs)) - for i := 0; i < len(errs); i++ { - errs[i] = e.errs[i] - } - - return errs -} - -// An ErrInvalidParam represents an invalid parameter error type. -type ErrInvalidParam interface { - awserr.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 errInvalidParam struct { - context string - nestedContext string - field string - code string - msg string -} - -// Code returns the error code for the type of invalid parameter. -func (e *errInvalidParam) Code() string { - return e.code -} - -// Message returns the reason the parameter was invalid, and its context. -func (e *errInvalidParam) Message() string { - return fmt.Sprintf("%s, %s.", e.msg, e.Field()) -} - -// Error returns the string version of the invalid parameter error. -func (e *errInvalidParam) Error() string { - return fmt.Sprintf("%s: %s", e.code, e.Message()) -} - -// OrigErr returns nil, Implemented for awserr.Error interface. -func (e *errInvalidParam) OrigErr() error { - return nil -} - -// Field Returns the field and context the error occurred. -func (e *errInvalidParam) Field() string { - field := e.context - if len(field) > 0 { - field += "." - } - if len(e.nestedContext) > 0 { - field += fmt.Sprintf("%s.", e.nestedContext) - } - field += e.field - - return field -} - -// SetContext updates the base context of the error. -func (e *errInvalidParam) SetContext(ctx string) { - e.context = ctx -} - -// AddNestedContext prepends a context to the field's path. -func (e *errInvalidParam) AddNestedContext(ctx string) { - if len(e.nestedContext) == 0 { - e.nestedContext = ctx - } else { - e.nestedContext = fmt.Sprintf("%s.%s", ctx, e.nestedContext) - } - -} - -// An ErrParamRequired represents an required parameter error. -type ErrParamRequired struct { - errInvalidParam -} - -// NewErrParamRequired creates a new required parameter error. -func NewErrParamRequired(field string) *ErrParamRequired { - return &ErrParamRequired{ - errInvalidParam{ - code: ParamRequiredErrCode, - field: field, - msg: fmt.Sprintf("missing required field"), - }, - } -} - -// An ErrParamMinValue represents a minimum value parameter error. -type ErrParamMinValue struct { - errInvalidParam - min float64 -} - -// NewErrParamMinValue creates a new minimum value parameter error. -func NewErrParamMinValue(field string, min float64) *ErrParamMinValue { - return &ErrParamMinValue{ - errInvalidParam: errInvalidParam{ - code: ParamMinValueErrCode, - field: field, - msg: fmt.Sprintf("minimum field value of %v", min), - }, - min: min, - } -} - -// MinValue returns the field's require minimum value. -// -// float64 is returned for both int and float min values. -func (e *ErrParamMinValue) MinValue() float64 { - return e.min -} - -// An ErrParamMinLen represents a minimum length parameter error. -type ErrParamMinLen struct { - errInvalidParam - min int -} - -// NewErrParamMinLen creates a new minimum length parameter error. -func NewErrParamMinLen(field string, min int) *ErrParamMinLen { - return &ErrParamMinLen{ - errInvalidParam: errInvalidParam{ - code: ParamMinLenErrCode, - field: field, - msg: fmt.Sprintf("minimum field size of %v", min), - }, - min: min, - } -} - -// MinLen returns the field's required minimum length. -func (e *ErrParamMinLen) MinLen() int { - return e.min -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go b/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go deleted file mode 100644 index 4601f883c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/request/waiter.go +++ /dev/null @@ -1,295 +0,0 @@ -package request - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/awsutil" -) - -// WaiterResourceNotReadyErrorCode is the error code returned by a waiter when -// the waiter's max attempts have been exhausted. -const WaiterResourceNotReadyErrorCode = "ResourceNotReady" - -// A WaiterOption is a function that will update the Waiter value's fields to -// configure the waiter. -type WaiterOption func(*Waiter) - -// WithWaiterMaxAttempts returns the maximum number of times the waiter should -// attempt to check the resource for the target state. -func WithWaiterMaxAttempts(max int) WaiterOption { - return func(w *Waiter) { - w.MaxAttempts = max - } -} - -// WaiterDelay will return a delay the waiter should pause between attempts to -// check the resource state. The passed in attempt is the number of times the -// Waiter has checked the resource state. -// -// Attempt is the number of attempts the Waiter has made checking the resource -// state. -type WaiterDelay func(attempt int) time.Duration - -// ConstantWaiterDelay returns a WaiterDelay that will always return a constant -// delay the waiter should use between attempts. It ignores the number of -// attempts made. -func ConstantWaiterDelay(delay time.Duration) WaiterDelay { - return func(attempt int) time.Duration { - return delay - } -} - -// WithWaiterDelay will set the Waiter to use the WaiterDelay passed in. -func WithWaiterDelay(delayer WaiterDelay) WaiterOption { - return func(w *Waiter) { - w.Delay = delayer - } -} - -// WithWaiterLogger returns a waiter option to set the logger a waiter -// should use to log warnings and errors to. -func WithWaiterLogger(logger aws.Logger) WaiterOption { - return func(w *Waiter) { - w.Logger = logger - } -} - -// WithWaiterRequestOptions returns a waiter option setting the request -// options for each request the waiter makes. Appends to waiter's request -// options already set. -func WithWaiterRequestOptions(opts ...Option) WaiterOption { - return func(w *Waiter) { - w.RequestOptions = append(w.RequestOptions, opts...) - } -} - -// A Waiter provides the functionality to perform a blocking call which will -// wait for a resource state to be satisfied by a service. -// -// This type should not be used directly. The API operations provided in the -// service packages prefixed with "WaitUntil" should be used instead. -type Waiter struct { - Name string - Acceptors []WaiterAcceptor - Logger aws.Logger - - MaxAttempts int - Delay WaiterDelay - - RequestOptions []Option - NewRequest func([]Option) (*Request, error) - SleepWithContext func(aws.Context, time.Duration) error -} - -// ApplyOptions updates the waiter with the list of waiter options provided. -func (w *Waiter) ApplyOptions(opts ...WaiterOption) { - for _, fn := range opts { - fn(w) - } -} - -// WaiterState are states the waiter uses based on WaiterAcceptor definitions -// to identify if the resource state the waiter is waiting on has occurred. -type WaiterState int - -// String returns the string representation of the waiter state. -func (s WaiterState) String() string { - switch s { - case SuccessWaiterState: - return "success" - case FailureWaiterState: - return "failure" - case RetryWaiterState: - return "retry" - default: - return "unknown waiter state" - } -} - -// States the waiter acceptors will use to identify target resource states. -const ( - SuccessWaiterState WaiterState = iota // waiter successful - FailureWaiterState // waiter failed - RetryWaiterState // waiter needs to be retried -) - -// WaiterMatchMode is the mode that the waiter will use to match the WaiterAcceptor -// definition's Expected attribute. -type WaiterMatchMode int - -// Modes the waiter will use when inspecting API response to identify target -// resource states. -const ( - PathAllWaiterMatch WaiterMatchMode = iota // match on all paths - PathWaiterMatch // match on specific path - PathAnyWaiterMatch // match on any path - PathListWaiterMatch // match on list of paths - StatusWaiterMatch // match on status code - ErrorWaiterMatch // match on error -) - -// String returns the string representation of the waiter match mode. -func (m WaiterMatchMode) String() string { - switch m { - case PathAllWaiterMatch: - return "pathAll" - case PathWaiterMatch: - return "path" - case PathAnyWaiterMatch: - return "pathAny" - case PathListWaiterMatch: - return "pathList" - case StatusWaiterMatch: - return "status" - case ErrorWaiterMatch: - return "error" - default: - return "unknown waiter match mode" - } -} - -// WaitWithContext will make requests for the API operation using NewRequest to -// build API requests. The request's response will be compared against the -// Waiter's Acceptors to determine the successful state of the resource the -// waiter is inspecting. -// -// The passed in context must not be nil. If it is nil a panic will occur. The -// Context will be used to cancel the waiter's pending requests and retry delays. -// Use aws.BackgroundContext if no context is available. -// -// The waiter will continue until the target state defined by the Acceptors, -// or the max attempts expires. -// -// Will return the WaiterResourceNotReadyErrorCode error code if the waiter's -// retryer ShouldRetry returns false. This normally will happen when the max -// wait attempts expires. -func (w Waiter) WaitWithContext(ctx aws.Context) error { - - for attempt := 1; ; attempt++ { - req, err := w.NewRequest(w.RequestOptions) - if err != nil { - waiterLogf(w.Logger, "unable to create request %v", err) - return err - } - req.Handlers.Build.PushBack(MakeAddToUserAgentFreeFormHandler("Waiter")) - err = req.Send() - - // See if any of the acceptors match the request's response, or error - for _, a := range w.Acceptors { - if matched, matchErr := a.match(w.Name, w.Logger, req, err); matched { - return matchErr - } - } - - // The Waiter should only check the resource state MaxAttempts times - // This is here instead of in the for loop above to prevent delaying - // unnecessary when the waiter will not retry. - if attempt == w.MaxAttempts { - break - } - - // Delay to wait before inspecting the resource again - delay := w.Delay(attempt) - if sleepFn := req.Config.SleepDelay; sleepFn != nil { - // Support SleepDelay for backwards compatibility and testing - sleepFn(delay) - } else { - sleepCtxFn := w.SleepWithContext - if sleepCtxFn == nil { - sleepCtxFn = aws.SleepWithContext - } - - if err := sleepCtxFn(ctx, delay); err != nil { - return awserr.New(CanceledErrorCode, "waiter context canceled", err) - } - } - } - - return awserr.New(WaiterResourceNotReadyErrorCode, "exceeded wait attempts", nil) -} - -// A WaiterAcceptor provides the information needed to wait for an API operation -// to complete. -type WaiterAcceptor struct { - State WaiterState - Matcher WaiterMatchMode - Argument string - Expected interface{} -} - -// match returns if the acceptor found a match with the passed in request -// or error. True is returned if the acceptor made a match, error is returned -// if there was an error attempting to perform the match. -func (a *WaiterAcceptor) match(name string, l aws.Logger, req *Request, err error) (bool, error) { - result := false - var vals []interface{} - - switch a.Matcher { - case PathAllWaiterMatch, PathWaiterMatch: - // Require all matches to be equal for result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - if len(vals) == 0 { - break - } - result = true - for _, val := range vals { - if !awsutil.DeepEqual(val, a.Expected) { - result = false - break - } - } - case PathAnyWaiterMatch: - // Only a single match needs to equal for the result to match - vals, _ = awsutil.ValuesAtPath(req.Data, a.Argument) - for _, val := range vals { - if awsutil.DeepEqual(val, a.Expected) { - result = true - break - } - } - case PathListWaiterMatch: - // ignored matcher - case StatusWaiterMatch: - s := a.Expected.(int) - result = s == req.HTTPResponse.StatusCode - case ErrorWaiterMatch: - if aerr, ok := err.(awserr.Error); ok { - result = aerr.Code() == a.Expected.(string) - } - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected matcher: %s", - name, a.Matcher) - } - - if !result { - // If there was no matching result found there is nothing more to do - // for this response, retry the request. - return false, nil - } - - switch a.State { - case SuccessWaiterState: - // waiter completed - return true, nil - case FailureWaiterState: - // Waiter failure state triggered - return true, awserr.New(WaiterResourceNotReadyErrorCode, - "failed waiting for successful resource state", err) - case RetryWaiterState: - // clear the error and retry the operation - return false, nil - default: - waiterLogf(l, "WARNING: Waiter %s encountered unexpected state: %s", - name, a.State) - return false, nil - } -} - -func waiterLogf(logger aws.Logger, msg string, args ...interface{}) { - if logger != nil { - logger.Log(fmt.Sprintf(msg, args...)) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go b/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go deleted file mode 100644 index ea7b886f8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/doc.go +++ /dev/null @@ -1,273 +0,0 @@ -/* -Package session provides configuration for the SDK's service clients. - -Sessions can be shared across all service clients that share the same base -configuration. The Session is built from the SDK's default configuration and -request handlers. - -Sessions should be cached when possible, because creating a new Session will -load all configuration values from the environment, and config files each time -the Session is created. Sharing the Session value across all of your service -clients will ensure the configuration is loaded the fewest number of times possible. - -Concurrency - -Sessions are safe to use concurrently as long as the Session is not being -modified. The SDK will not modify the Session once the Session has been created. -Creating service clients concurrently from a shared Session is safe. - -Sessions from Shared Config - -Sessions can be created using the method above that will only load the -additional config if the AWS_SDK_LOAD_CONFIG environment variable is set. -Alternatively you can explicitly create a Session with shared config enabled. -To do this you can use NewSessionWithOptions to configure how the Session will -be created. Using the NewSessionWithOptions with SharedConfigState set to -SharedConfigEnable will create the session as if the AWS_SDK_LOAD_CONFIG -environment variable was set. - -Creating Sessions - -When creating Sessions optional aws.Config values can be passed in that will -override the default, or loaded config values the Session is being created -with. This allows you to provide additional, or case based, configuration -as needed. - -By default NewSession will only load credentials from the shared credentials -file (~/.aws/credentials). If the AWS_SDK_LOAD_CONFIG environment variable is -set to a truthy value the Session will be created from the configuration -values from the shared config (~/.aws/config) and shared credentials -(~/.aws/credentials) files. See the section Sessions from Shared Config for -more information. - -Create a Session with the default config and request handlers. With credentials -region, and profile loaded from the environment and shared config automatically. -Requires the AWS_PROFILE to be set, or "default" is used. - - // Create Session - sess := session.Must(session.NewSession()) - - // Create a Session with a custom region - sess := session.Must(session.NewSession(&aws.Config{ - Region: aws.String("us-east-1"), - })) - - // Create a S3 client instance from a session - sess := session.Must(session.NewSession()) - - svc := s3.New(sess) - -Create Session With Option Overrides - -In addition to NewSession, Sessions can be created using NewSessionWithOptions. -This func allows you to control and override how the Session will be created -through code instead of being driven by environment variables only. - -Use NewSessionWithOptions when you want to provide the config profile, or -override the shared config state (AWS_SDK_LOAD_CONFIG). - - // Equivalent to session.NewSession() - sess := session.Must(session.NewSessionWithOptions(session.Options{ - // Options - })) - - // Specify profile to load for the session's config - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Profile: "profile_name", - })) - - // Specify profile for config and region for requests - sess := session.Must(session.NewSessionWithOptions(session.Options{ - Config: aws.Config{Region: aws.String("us-east-1")}, - Profile: "profile_name", - })) - - // Force enable Shared Config support - sess := session.Must(session.NewSessionWithOptions(session.Options{ - SharedConfigState: session.SharedConfigEnable, - })) - -Adding Handlers - -You can add handlers to a session for processing HTTP requests. All service -clients that use the session inherit the handlers. For example, the following -handler logs every request and its payload made by a service client: - - // Create a session, and add additional handlers for all service - // clients created with the Session to inherit. Adds logging handler. - sess := session.Must(session.NewSession()) - - sess.Handlers.Send.PushFront(func(r *request.Request) { - // Log every request made and its payload - logger.Println("Request: %s/%s, Payload: %s", - r.ClientInfo.ServiceName, r.Operation, r.Params) - }) - -Deprecated "New" function - -The New session function has been deprecated because it does not provide good -way to return errors that occur when loading the configuration files and values. -Because of this, NewSession was created so errors can be retrieved when -creating a session fails. - -Shared Config Fields - -By default the SDK will only load the shared credentials file's (~/.aws/credentials) -credentials values, and all other config is provided by the environment variables, -SDK defaults, and user provided aws.Config values. - -If the AWS_SDK_LOAD_CONFIG environment variable is set, or SharedConfigEnable -option is used to create the Session the full shared config values will be -loaded. This includes credentials, region, and support for assume role. In -addition the Session will load its configuration from both the shared config -file (~/.aws/config) and shared credentials file (~/.aws/credentials). Both -files have the same format. - -If both config files are present the configuration from both files will be -read. The Session will be created from configuration values from the shared -credentials file (~/.aws/credentials) over those in the shared config file (~/.aws/config). - -Credentials are the values the SDK should use for authenticating requests with -AWS Services. They arfrom a configuration file will need to include both -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 = AKID - aws_secret_access_key = SECRET - aws_session_token = TOKEN - -Assume Role values allow you to configure the SDK to assume an IAM role using -a set of credentials provided in a config file via the source_profile field. -Both "role_arn" and "source_profile" are required. The SDK supports assuming -a role with MFA token if the session option AssumeRoleTokenProvider -is set. - - role_arn = arn:aws:iam:::role/ - source_profile = profile_with_creds - external_id = 1234 - mfa_serial = - role_session_name = session_name - -Region is the region the SDK should use for looking up AWS service endpoints -and signing requests. - - region = us-east-1 - -Assume Role with MFA token - -To create a session with support for assuming an IAM role with MFA set the -session option AssumeRoleTokenProvider to a function that will prompt for the -MFA token code when the SDK assumes the role and refreshes the role's credentials. -This allows you to configure the SDK via the shared config to assumea role -with MFA tokens. - -In order for the SDK to assume a role with MFA the SharedConfigState -session option must be set to SharedConfigEnable, or AWS_SDK_LOAD_CONFIG -environment variable set. - -The shared configuration instructs the SDK to assume an IAM role with MFA -when the mfa_serial configuration field is set in the shared config -(~/.aws/config) or shared credentials (~/.aws/credentials) file. - -If mfa_serial is set in the configuration, the SDK will assume the role, and -the AssumeRoleTokenProvider session option is not set an an error will -be returned when creating the session. - - sess := session.Must(session.NewSessionWithOptions(session.Options{ - AssumeRoleTokenProvider: stscreds.StdinTokenProvider, - })) - - // Create service client value configured for credentials - // from assumed role. - svc := s3.New(sess) - -To setup assume role outside of a session see the stscrds.AssumeRoleProvider -documentation. - -Environment Variables - -When a Session is created several environment variables can be set to adjust -how the SDK functions, and what configuration data it loads when creating -Sessions. All environment values are optional, but some values like credentials -require multiple of the values to set or the partial values will be ignored. -All environment variable values are strings unless otherwise noted. - -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=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - - # Session Token - AWS_SESSION_TOKEN=TOKEN - -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-east-1 - - # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_REGION is not also set. - AWS_DEFAULT_REGION=us-east-1 - -Profile name the SDK should load use when loading shared config from the -configuration files. If not provided "default" will be used as the profile name. - - AWS_PROFILE=my_profile - - # AWS_DEFAULT_PROFILE is only read if AWS_SDK_LOAD_CONFIG is also set, - # and AWS_PROFILE is not also set. - AWS_DEFAULT_PROFILE=my_profile - -SDK load config instructs the SDK to load the shared config in addition to -shared credentials. This also expands the configuration loaded so the shared -credentials will have parity with the shared config file. This also enables -Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE -env values as well. - - AWS_SDK_LOAD_CONFIG=1 - -Shared credentials file path can be set to instruct the SDK to use an alternative -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 - -Shared config file path can be set to instruct the SDK to use an alternative -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 - -Path to a custom Credentials Authority (CA) bundle PEM file that the SDK -will use instead of the default system's root CA bundle. Use this only -if you want to replace the CA bundle the SDK uses for TLS requests. - - AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - -Enabling this option will attempt to merge the Transport into the SDK's HTTP -client. If the client's Transport is not a http.Transport an error will be -returned. If the Transport's TLS config is set this option will cause the SDK -to overwrite the Transport's TLS config's RootCAs value. If the CA bundle file -contains multiple certificates all of them will be loaded. - -The Session option CustomCABundle is also available when creating sessions -to also enable this feature. CustomCABundle session option field has priority -over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - -Setting a custom HTTPClient in the aws.Config options will override this setting. -To use this option and custom HTTP client, the HTTP client needs to be provided -when creating the session. Not the service client. -*/ -package session diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go deleted file mode 100644 index 12b452177..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/env_config.go +++ /dev/null @@ -1,199 +0,0 @@ -package session - -import ( - "os" - "strconv" - - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/defaults" -) - -// EnvProviderName provides a name of the provider when config is loaded from environment. -const EnvProviderName = "EnvConfigCredentials" - -// 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=SECRET # only read if AWS_SECRET_ACCESS_KEY is not set. - // - // # Session Token - // AWS_SESSION_TOKEN=TOKEN - Creds credentials.Value - - // 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-east-1 - // - // # AWS_DEFAULT_REGION is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_REGION is not also set. - // AWS_DEFAULT_REGION=us-east-1 - 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 is only read if AWS_SDK_LOAD_CONFIG is also set, - // # and AWS_PROFILE is not also set. - // AWS_DEFAULT_PROFILE=my_profile - Profile string - - // SDK load config instructs the SDK to load the shared config in addition to - // shared credentials. This also expands the configuration loaded from the shared - // credentials to have parity with the shared config file. This also enables - // Region and Profile support for the AWS_DEFAULT_REGION and AWS_DEFAULT_PROFILE - // env values as well. - // - // AWS_SDK_LOAD_CONFIG=1 - EnableSharedConfig bool - - // 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 Authroity (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 session. Not the service client. - // - // AWS_CA_BUNDLE=$HOME/my_custom_ca_bundle - CustomCABundle string -} - -var ( - credAccessEnvKey = []string{ - "AWS_ACCESS_KEY_ID", - "AWS_ACCESS_KEY", - } - credSecretEnvKey = []string{ - "AWS_SECRET_ACCESS_KEY", - "AWS_SECRET_KEY", - } - credSessionEnvKey = []string{ - "AWS_SESSION_TOKEN", - } - - regionEnvKeys = []string{ - "AWS_REGION", - "AWS_DEFAULT_REGION", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - profileEnvKeys = []string{ - "AWS_PROFILE", - "AWS_DEFAULT_PROFILE", // Only read if AWS_SDK_LOAD_CONFIG is also set - } - sharedCredsFileEnvKey = []string{ - "AWS_SHARED_CREDENTIALS_FILE", - } - sharedConfigFileEnvKey = []string{ - "AWS_CONFIG_FILE", - } -) - -// loadEnvConfig retrieves the SDK's environment configuration. -// See `envConfig` for the values that will be retrieved. -// -// If the environment variable `AWS_SDK_LOAD_CONFIG` is set to a truthy value -// the shared SDK config will be loaded in addition to the SDK's specific -// configuration values. -func loadEnvConfig() envConfig { - enableSharedConfig, _ := strconv.ParseBool(os.Getenv("AWS_SDK_LOAD_CONFIG")) - return envConfigLoad(enableSharedConfig) -} - -// loadEnvSharedConfig retrieves the SDK's environment configuration, and the -// SDK shared config. See `envConfig` for the values that will be retrieved. -// -// Loads the shared configuration in addition to the SDK's specific configuration. -// This will load the same values as `loadEnvConfig` if the `AWS_SDK_LOAD_CONFIG` -// environment variable is set. -func loadSharedEnvConfig() envConfig { - return envConfigLoad(true) -} - -func envConfigLoad(enableSharedConfig bool) envConfig { - cfg := envConfig{} - - cfg.EnableSharedConfig = enableSharedConfig - - setFromEnvVal(&cfg.Creds.AccessKeyID, credAccessEnvKey) - setFromEnvVal(&cfg.Creds.SecretAccessKey, credSecretEnvKey) - setFromEnvVal(&cfg.Creds.SessionToken, credSessionEnvKey) - - // Require logical grouping of credentials - if len(cfg.Creds.AccessKeyID) == 0 || len(cfg.Creds.SecretAccessKey) == 0 { - cfg.Creds = credentials.Value{} - } else { - cfg.Creds.ProviderName = EnvProviderName - } - - regionKeys := regionEnvKeys - profileKeys := profileEnvKeys - if !cfg.EnableSharedConfig { - regionKeys = regionKeys[:1] - profileKeys = profileKeys[:1] - } - - setFromEnvVal(&cfg.Region, regionKeys) - setFromEnvVal(&cfg.Profile, profileKeys) - - setFromEnvVal(&cfg.SharedCredentialsFile, sharedCredsFileEnvKey) - setFromEnvVal(&cfg.SharedConfigFile, sharedConfigFileEnvKey) - - if len(cfg.SharedCredentialsFile) == 0 { - cfg.SharedCredentialsFile = defaults.SharedCredentialsFilename() - } - if len(cfg.SharedConfigFile) == 0 { - cfg.SharedConfigFile = defaults.SharedConfigFilename() - } - - cfg.CustomCABundle = os.Getenv("AWS_CA_BUNDLE") - - return cfg -} - -func setFromEnvVal(dst *string, keys []string) { - for _, k := range keys { - if v := os.Getenv(k); len(v) > 0 { - *dst = v - break - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go b/vendor/github.com/aws/aws-sdk-go/aws/session/session.go deleted file mode 100644 index 259b5c0fe..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/session.go +++ /dev/null @@ -1,606 +0,0 @@ -package session - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/corehandlers" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/credentials/stscreds" - "github.com/aws/aws-sdk-go/aws/defaults" - "github.com/aws/aws-sdk-go/aws/endpoints" - "github.com/aws/aws-sdk-go/aws/request" -) - -// A Session provides a central location to create service clients from and -// store configurations and request handlers for those services. -// -// Sessions are safe to create service clients concurrently, but it is not safe -// to mutate the Session concurrently. -// -// The Session satisfies the service client's client.ConfigProvider. -type Session struct { - Config *aws.Config - Handlers request.Handlers -} - -// New creates a new instance of the handlers merging in the provided configs -// on top of the SDK's default configurations. Once the Session is created it -// can be mutated to modify the Config or Handlers. The Session is safe to be -// read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment is set to a truthy value, the New -// method could now encounter an error when loading the configuration. When -// The environment variable is set, and an error occurs, New will return a -// session that will fail all requests reporting the error that occurred while -// loading the session. Use NewSession to get the error when creating the -// session. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded, in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. -// -// Deprecated: Use NewSession functions to create sessions instead. NewSession -// has the same functionality as New except an error can be returned when the -// func is called instead of waiting to receive an error until a request is made. -func New(cfgs ...*aws.Config) *Session { - // load initial config from environment - envCfg := loadEnvConfig() - - if envCfg.EnableSharedConfig { - var cfg aws.Config - cfg.MergeIn(cfgs...) - s, err := NewSessionWithOptions(Options{ - Config: cfg, - SharedConfigState: SharedConfigEnable, - }) - if err != nil { - // Old session.New expected all errors to be discovered when - // a request is made, and would report the errors then. This - // needs to be replicated if an error occurs while creating - // the session. - msg := "failed to create session with AWS_SDK_LOAD_CONFIG enabled. " + - "Use session.NewSession to handle errors occurring during session creation." - - // Session creation failed, need to report the error and prevent - // any requests from succeeding. - s = &Session{Config: defaults.Config()} - s.Config.MergeIn(cfgs...) - s.Config.Logger.Log("ERROR:", msg, "Error:", err) - s.Handlers.Validate.PushBack(func(r *request.Request) { - r.Error = err - }) - } - return s - } - - return deprecatedNewSession(cfgs...) -} - -// NewSession returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. Once the Session is created -// it can be mutated to modify the Config or Handlers. The Session is safe to -// be read concurrently, but it should not be written to concurrently. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// See the NewSessionWithOptions func for information on how to override or -// control through code how the Session will be created. Such as specifying the -// config profile, and controlling if shared config is enabled or not. -func NewSession(cfgs ...*aws.Config) (*Session, error) { - opts := Options{} - opts.Config.MergeIn(cfgs...) - - return NewSessionWithOptions(opts) -} - -// SharedConfigState provides the ability to optionally override the state -// of the session's creation based on the shared config being enabled or -// disabled. -type SharedConfigState int - -const ( - // SharedConfigStateFromEnv does not override any state of the - // AWS_SDK_LOAD_CONFIG env var. It is the default value of the - // SharedConfigState type. - SharedConfigStateFromEnv SharedConfigState = iota - - // SharedConfigDisable overrides the AWS_SDK_LOAD_CONFIG env var value - // and disables the shared config functionality. - SharedConfigDisable - - // SharedConfigEnable overrides the AWS_SDK_LOAD_CONFIG env var value - // and enables the shared config functionality. - SharedConfigEnable -) - -// Options provides the means to control how a Session is created and what -// configuration values will be loaded. -// -type Options struct { - // Provides config values for the SDK to use when creating service clients - // and making API requests to services. Any value set in with this field - // will override the associated value provided by the SDK defaults, - // environment or config files where relevant. - // - // If not set, configuration values from from SDK defaults, environment, - // config will be used. - Config aws.Config - - // Overrides the config profile the Session should be created from. If not - // set the value of the environment variable will be loaded (AWS_PROFILE, - // or AWS_DEFAULT_PROFILE if the Shared Config is enabled). - // - // If not set and environment variables are not set the "default" - // (DefaultSharedConfigProfile) will be used as the profile to load the - // session config from. - Profile string - - // Instructs how the Session will be created based on the AWS_SDK_LOAD_CONFIG - // environment variable. By default a Session will be created using the - // value provided by the AWS_SDK_LOAD_CONFIG environment variable. - // - // Setting this value to SharedConfigEnable or SharedConfigDisable - // will allow you to override the AWS_SDK_LOAD_CONFIG environment variable - // and enable or disable the shared config functionality. - SharedConfigState SharedConfigState - - // Ordered list of files the session will load configuration from. - // It will override environment variable AWS_SHARED_CREDENTIALS_FILE, AWS_CONFIG_FILE. - SharedConfigFiles []string - - // When the SDK's shared config is configured to assume a role with MFA - // this option is required in order to provide the mechanism that will - // retrieve the MFA token. There is no default value for this field. If - // it is not set an error will be returned when creating the session. - // - // This token provider will be called when ever the assumed role's - // credentials need to be refreshed. Within the context of service clients - // all sharing the same session the SDK will ensure calls to the token - // provider are atomic. When sharing a token provider across multiple - // sessions additional synchronization logic is needed to ensure the - // token providers do not introduce race conditions. It is recommend to - // share the session where possible. - // - // stscreds.StdinTokenProvider is a basic implementation that will prompt - // from stdin for the MFA token code. - // - // This field is only used if the shared configuration is enabled, and - // the config enables assume role wit MFA via the mfa_serial field. - AssumeRoleTokenProvider func() (string, error) - - // Reader for a custom Credentials Authority (CA) bundle in PEM format that - // the SDK will use instead of the default system's root CA bundle. Use this - // only if you want to replace the CA bundle the SDK uses for TLS requests. - // - // Enabling this option will attempt to merge the Transport into the SDK's HTTP - // client. If the client's Transport is not a http.Transport an error will be - // returned. If the Transport's TLS config is set this option will cause the SDK - // to overwrite the Transport's TLS config's RootCAs value. If the CA - // bundle reader contains multiple certificates all of them will be loaded. - // - // The Session option CustomCABundle is also available when creating sessions - // to also enable this feature. CustomCABundle session option field has priority - // over the AWS_CA_BUNDLE environment variable, and will be used if both are set. - CustomCABundle io.Reader -} - -// NewSessionWithOptions returns a new Session created from SDK defaults, config files, -// environment, and user provided config files. This func uses the Options -// values to configure how the Session is created. -// -// If the AWS_SDK_LOAD_CONFIG environment variable is set to a truthy value -// the shared config file (~/.aws/config) will also be loaded in addition to -// the shared credentials file (~/.aws/credentials). Values set in both the -// shared config, and shared credentials will be taken from the shared -// credentials file. Enabling the Shared Config will also allow the Session -// to be built with retrieving credentials with AssumeRole set in the config. -// -// // Equivalent to session.New -// sess := session.Must(session.NewSessionWithOptions(session.Options{})) -// -// // Specify profile to load for the session's config -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Profile: "profile_name", -// })) -// -// // Specify profile for config and region for requests -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// Config: aws.Config{Region: aws.String("us-east-1")}, -// Profile: "profile_name", -// })) -// -// // Force enable Shared Config support -// sess := session.Must(session.NewSessionWithOptions(session.Options{ -// SharedConfigState: session.SharedConfigEnable, -// })) -func NewSessionWithOptions(opts Options) (*Session, error) { - var envCfg envConfig - if opts.SharedConfigState == SharedConfigEnable { - envCfg = loadSharedEnvConfig() - } else { - envCfg = loadEnvConfig() - } - - if len(opts.Profile) > 0 { - envCfg.Profile = opts.Profile - } - - switch opts.SharedConfigState { - case SharedConfigDisable: - envCfg.EnableSharedConfig = false - case SharedConfigEnable: - envCfg.EnableSharedConfig = true - } - - // Only use AWS_CA_BUNDLE if session option is not provided. - if len(envCfg.CustomCABundle) != 0 && opts.CustomCABundle == nil { - f, err := os.Open(envCfg.CustomCABundle) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to open custom CA bundle PEM file", err) - } - defer f.Close() - opts.CustomCABundle = f - } - - return newSession(opts, envCfg, &opts.Config) -} - -// Must is a helper function to ensure the Session is valid and there was no -// error when calling a NewSession function. -// -// This helper is intended to be used in variable initialization to load the -// Session and configuration at startup. Such as: -// -// var sess = session.Must(session.NewSession()) -func Must(sess *Session, err error) *Session { - if err != nil { - panic(err) - } - - return sess -} - -func deprecatedNewSession(cfgs ...*aws.Config) *Session { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Apply the passed in configs so the configuration can be applied to the - // default credential chain - cfg.MergeIn(cfgs...) - if cfg.EndpointResolver == nil { - // An endpoint resolver is required for a session to be able to provide - // endpoints for service client configurations. - cfg.EndpointResolver = endpoints.DefaultResolver() - } - cfg.Credentials = defaults.CredChain(cfg, handlers) - - // Reapply any passed in configs to override credentials if set - cfg.MergeIn(cfgs...) - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - - return s -} - -func newSession(opts Options, envCfg envConfig, cfgs ...*aws.Config) (*Session, error) { - cfg := defaults.Config() - handlers := defaults.Handlers() - - // Get a merged version of the user provided config to determine if - // credentials were. - userCfg := &aws.Config{} - userCfg.MergeIn(cfgs...) - - // Ordered config files will be loaded in with later files overwriting - // previous config file values. - var cfgFiles []string - if opts.SharedConfigFiles != nil { - cfgFiles = opts.SharedConfigFiles - } else { - cfgFiles = []string{envCfg.SharedConfigFile, envCfg.SharedCredentialsFile} - if !envCfg.EnableSharedConfig { - // The shared config file (~/.aws/config) is only loaded if instructed - // to load via the envConfig.EnableSharedConfig (AWS_SDK_LOAD_CONFIG). - cfgFiles = cfgFiles[1:] - } - } - - // Load additional config from file(s) - sharedCfg, err := loadSharedConfig(envCfg.Profile, cfgFiles) - if err != nil { - return nil, err - } - - if err := mergeConfigSrcs(cfg, userCfg, envCfg, sharedCfg, handlers, opts); err != nil { - return nil, err - } - - s := &Session{ - Config: cfg, - Handlers: handlers, - } - - initHandlers(s) - - // Setup HTTP client with custom cert bundle if enabled - if opts.CustomCABundle != nil { - if err := loadCustomCABundle(s, opts.CustomCABundle); err != nil { - return nil, err - } - } - - return s, nil -} - -func loadCustomCABundle(s *Session, bundle io.Reader) error { - var t *http.Transport - switch v := s.Config.HTTPClient.Transport.(type) { - case *http.Transport: - t = v - default: - if s.Config.HTTPClient.Transport != nil { - return awserr.New("LoadCustomCABundleError", - "unable to load custom CA bundle, HTTPClient's transport unsupported type", nil) - } - } - if t == nil { - t = &http.Transport{} - } - - p, err := loadCertPool(bundle) - if err != nil { - return err - } - if t.TLSClientConfig == nil { - t.TLSClientConfig = &tls.Config{} - } - t.TLSClientConfig.RootCAs = p - - s.Config.HTTPClient.Transport = t - - return nil -} - -func loadCertPool(r io.Reader) (*x509.CertPool, error) { - b, err := ioutil.ReadAll(r) - if err != nil { - return nil, awserr.New("LoadCustomCABundleError", - "failed to read custom CA bundle PEM file", err) - } - - p := x509.NewCertPool() - if !p.AppendCertsFromPEM(b) { - return nil, awserr.New("LoadCustomCABundleError", - "failed to load custom CA bundle PEM file", err) - } - - return p, nil -} - -func mergeConfigSrcs(cfg, userCfg *aws.Config, envCfg envConfig, sharedCfg sharedConfig, handlers request.Handlers, sessOpts Options) error { - // Merge in user provided configuration - cfg.MergeIn(userCfg) - - // Region if not already set by user - if len(aws.StringValue(cfg.Region)) == 0 { - if len(envCfg.Region) > 0 { - cfg.WithRegion(envCfg.Region) - } else if envCfg.EnableSharedConfig && len(sharedCfg.Region) > 0 { - cfg.WithRegion(sharedCfg.Region) - } - } - - // Configure credentials if not already set - if cfg.Credentials == credentials.AnonymousCredentials && userCfg.Credentials == nil { - if len(envCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - envCfg.Creds, - ) - } else if envCfg.EnableSharedConfig && len(sharedCfg.AssumeRole.RoleARN) > 0 && sharedCfg.AssumeRoleSource != nil { - cfgCp := *cfg - cfgCp.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.AssumeRoleSource.Creds, - ) - if len(sharedCfg.AssumeRole.MFASerial) > 0 && sessOpts.AssumeRoleTokenProvider == nil { - // AssumeRole Token provider is required if doing Assume Role - // with MFA. - return AssumeRoleTokenProviderNotSetError{} - } - cfg.Credentials = stscreds.NewCredentials( - &Session{ - Config: &cfgCp, - Handlers: handlers.Copy(), - }, - sharedCfg.AssumeRole.RoleARN, - func(opt *stscreds.AssumeRoleProvider) { - opt.RoleSessionName = sharedCfg.AssumeRole.RoleSessionName - - // Assume role with external ID - if len(sharedCfg.AssumeRole.ExternalID) > 0 { - opt.ExternalID = aws.String(sharedCfg.AssumeRole.ExternalID) - } - - // Assume role with MFA - if len(sharedCfg.AssumeRole.MFASerial) > 0 { - opt.SerialNumber = aws.String(sharedCfg.AssumeRole.MFASerial) - opt.TokenProvider = sessOpts.AssumeRoleTokenProvider - } - }, - ) - } else if len(sharedCfg.Creds.AccessKeyID) > 0 { - cfg.Credentials = credentials.NewStaticCredentialsFromCreds( - sharedCfg.Creds, - ) - } else { - // Fallback to default credentials provider, include mock errors - // for the credential chain so user can identify why credentials - // failed to be retrieved. - cfg.Credentials = credentials.NewCredentials(&credentials.ChainProvider{ - VerboseErrors: aws.BoolValue(cfg.CredentialsChainVerboseErrors), - Providers: []credentials.Provider{ - &credProviderError{Err: awserr.New("EnvAccessKeyNotFound", "failed to find credentials in the environment.", nil)}, - &credProviderError{Err: awserr.New("SharedCredsLoad", fmt.Sprintf("failed to load profile, %s.", envCfg.Profile), nil)}, - defaults.RemoteCredProvider(*cfg, handlers), - }, - }) - } - } - - return nil -} - -// AssumeRoleTokenProviderNotSetError is an error returned when creating a session when the -// MFAToken option is not set when shared config is configured load assume a -// role with an MFA token. -type AssumeRoleTokenProviderNotSetError struct{} - -// Code is the short id of the error. -func (e AssumeRoleTokenProviderNotSetError) Code() string { - return "AssumeRoleTokenProviderNotSetError" -} - -// Message is the description of the error -func (e AssumeRoleTokenProviderNotSetError) Message() string { - return fmt.Sprintf("assume role with MFA enabled, but AssumeRoleTokenProvider session option not set.") -} - -// OrigErr is the underlying error that caused the failure. -func (e AssumeRoleTokenProviderNotSetError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e AssumeRoleTokenProviderNotSetError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} - -type credProviderError struct { - Err error -} - -var emptyCreds = credentials.Value{} - -func (c credProviderError) Retrieve() (credentials.Value, error) { - return credentials.Value{}, c.Err -} -func (c credProviderError) IsExpired() bool { - return true -} - -func initHandlers(s *Session) { - // Add the Validate parameter handler if it is not disabled. - s.Handlers.Validate.Remove(corehandlers.ValidateParametersHandler) - if !aws.BoolValue(s.Config.DisableParamValidation) { - s.Handlers.Validate.PushBackNamed(corehandlers.ValidateParametersHandler) - } -} - -// Copy creates and returns a copy of the current Session, coping the config -// and handlers. If any additional configs are provided they will be merged -// on top of the Session's copied config. -// -// // Create a copy of the current Session, configured for the us-west-2 region. -// sess.Copy(&aws.Config{Region: aws.String("us-west-2")}) -func (s *Session) Copy(cfgs ...*aws.Config) *Session { - newSession := &Session{ - Config: s.Config.Copy(cfgs...), - Handlers: s.Handlers.Copy(), - } - - initHandlers(newSession) - - return newSession -} - -// ClientConfig satisfies the client.ConfigProvider interface and is used to -// configure the service client instances. Passing the Session to the service -// client's constructor (New) will use this method to configure the client. -func (s *Session) ClientConfig(serviceName string, cfgs ...*aws.Config) client.Config { - // Backwards compatibility, the error will be eaten if user calls ClientConfig - // directly. All SDK services will use ClientconfigWithError. - cfg, _ := s.clientConfigWithErr(serviceName, cfgs...) - - return cfg -} - -func (s *Session) clientConfigWithErr(serviceName string, cfgs ...*aws.Config) (client.Config, error) { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - var err error - - region := aws.StringValue(s.Config.Region) - - if endpoint := aws.StringValue(s.Config.Endpoint); len(endpoint) != 0 { - resolved.URL = endpoints.AddScheme(endpoint, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } else { - resolved, err = s.Config.EndpointResolver.EndpointFor( - serviceName, region, - func(opt *endpoints.Options) { - opt.DisableSSL = aws.BoolValue(s.Config.DisableSSL) - opt.UseDualStack = aws.BoolValue(s.Config.UseDualStack) - - // Support the condition where the service is modeled but its - // endpoint metadata is not available. - opt.ResolveUnknownService = true - }, - ) - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - }, err -} - -// ClientConfigNoResolveEndpoint is the same as ClientConfig with the exception -// that the EndpointResolver will not be used to resolve the endpoint. The only -// endpoint set must come from the aws.Config.Endpoint field. -func (s *Session) ClientConfigNoResolveEndpoint(cfgs ...*aws.Config) client.Config { - s = s.Copy(cfgs...) - - var resolved endpoints.ResolvedEndpoint - - region := aws.StringValue(s.Config.Region) - - if ep := aws.StringValue(s.Config.Endpoint); len(ep) > 0 { - resolved.URL = endpoints.AddScheme(ep, aws.BoolValue(s.Config.DisableSSL)) - resolved.SigningRegion = region - } - - return client.Config{ - Config: s.Config, - Handlers: s.Handlers, - Endpoint: resolved.URL, - SigningRegion: resolved.SigningRegion, - SigningNameDerived: resolved.SigningNameDerived, - SigningName: resolved.SigningName, - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go b/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go deleted file mode 100644 index 09c8e5bc7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/session/shared_config.go +++ /dev/null @@ -1,295 +0,0 @@ -package session - -import ( - "fmt" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/go-ini/ini" -) - -const ( - // 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 - externalIDKey = `external_id` // optional - mfaSerialKey = `mfa_serial` // optional - roleSessionNameKey = `role_session_name` // optional - - // Additional Config fields - regionKey = `region` - - // DefaultSharedConfigProfile is the default profile to be used when - // loading configuration from the config files if another profile name - // is not provided. - DefaultSharedConfigProfile = `default` -) - -type assumeRoleConfig struct { - RoleARN string - SourceProfile string - ExternalID string - MFASerial string - RoleSessionName string -} - -// sharedConfig represents the configuration fields of the SDK config files. -type sharedConfig struct { - // 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 - Creds credentials.Value - - AssumeRole assumeRoleConfig - AssumeRoleSource *sharedConfig - - // Region is the region the SDK should use for looking up AWS service endpoints - // and signing requests. - // - // region - Region string -} - -type sharedConfigFile struct { - Filename string - IniData *ini.File -} - -// loadSharedConfig 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. -// -// See sharedConfig.setFromFile for information how the config files -// will be loaded. -func loadSharedConfig(profile string, filenames []string) (sharedConfig, error) { - if len(profile) == 0 { - profile = DefaultSharedConfigProfile - } - - files, err := loadSharedConfigIniFiles(filenames) - if err != nil { - return sharedConfig{}, err - } - - cfg := sharedConfig{} - if err = cfg.setFromIniFiles(profile, files); err != nil { - return sharedConfig{}, err - } - - if len(cfg.AssumeRole.SourceProfile) > 0 { - if err := cfg.setAssumeRoleSource(profile, files); err != nil { - return sharedConfig{}, err - } - } - - return cfg, nil -} - -func loadSharedConfigIniFiles(filenames []string) ([]sharedConfigFile, error) { - files := make([]sharedConfigFile, 0, len(filenames)) - - for _, filename := range filenames { - b, err := ioutil.ReadFile(filename) - if err != nil { - // Skip files which can't be opened and read for whatever reason - continue - } - - f, err := ini.Load(b) - if err != nil { - return nil, SharedConfigLoadError{Filename: filename, Err: err} - } - - files = append(files, sharedConfigFile{ - Filename: filename, IniData: f, - }) - } - - return files, nil -} - -func (cfg *sharedConfig) setAssumeRoleSource(origProfile string, files []sharedConfigFile) error { - var assumeRoleSrc sharedConfig - - // Multiple level assume role chains are not support - if cfg.AssumeRole.SourceProfile == origProfile { - assumeRoleSrc = *cfg - assumeRoleSrc.AssumeRole = assumeRoleConfig{} - } else { - err := assumeRoleSrc.setFromIniFiles(cfg.AssumeRole.SourceProfile, files) - if err != nil { - return err - } - } - - if len(assumeRoleSrc.Creds.AccessKeyID) == 0 { - return SharedConfigAssumeRoleError{RoleARN: cfg.AssumeRole.RoleARN} - } - - cfg.AssumeRoleSource = &assumeRoleSrc - - return nil -} - -func (cfg *sharedConfig) setFromIniFiles(profile string, files []sharedConfigFile) error { - // Trim files from the list that don't exist. - for _, f := range files { - if err := cfg.setFromIniFile(profile, f); err != nil { - if _, ok := err.(SharedConfigProfileNotExistsError); ok { - // Ignore proviles missings - continue - } - return err - } - } - - return nil -} - -// setFromFile loads the configuration from the file using -// the profile provided. 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 (cfg *sharedConfig) setFromIniFile(profile string, file sharedConfigFile) error { - section, err := file.IniData.GetSection(profile) - if err != nil { - // Fallback to to alternate profile name: profile - section, err = file.IniData.GetSection(fmt.Sprintf("profile %s", profile)) - if err != nil { - return SharedConfigProfileNotExistsError{Profile: profile, Err: err} - } - } - - // Shared Credentials - akid := section.Key(accessKeyIDKey).String() - secret := section.Key(secretAccessKey).String() - if len(akid) > 0 && len(secret) > 0 { - cfg.Creds = credentials.Value{ - AccessKeyID: akid, - SecretAccessKey: secret, - SessionToken: section.Key(sessionTokenKey).String(), - ProviderName: fmt.Sprintf("SharedConfigCredentials: %s", file.Filename), - } - } - - // Assume Role - roleArn := section.Key(roleArnKey).String() - srcProfile := section.Key(sourceProfileKey).String() - if len(roleArn) > 0 && len(srcProfile) > 0 { - cfg.AssumeRole = assumeRoleConfig{ - RoleARN: roleArn, - SourceProfile: srcProfile, - ExternalID: section.Key(externalIDKey).String(), - MFASerial: section.Key(mfaSerialKey).String(), - RoleSessionName: section.Key(roleSessionNameKey).String(), - } - } - - // Region - if v := section.Key(regionKey).String(); len(v) > 0 { - cfg.Region = v - } - - return nil -} - -// SharedConfigLoadError is an error for the shared config file failed to load. -type SharedConfigLoadError struct { - Filename string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigLoadError) Code() string { - return "SharedConfigLoadError" -} - -// Message is the description of the error -func (e SharedConfigLoadError) Message() string { - return fmt.Sprintf("failed to load config file, %s", e.Filename) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigLoadError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigLoadError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// SharedConfigProfileNotExistsError is an error for the shared config when -// the profile was not find in the config file. -type SharedConfigProfileNotExistsError struct { - Profile string - Err error -} - -// Code is the short id of the error. -func (e SharedConfigProfileNotExistsError) Code() string { - return "SharedConfigProfileNotExistsError" -} - -// Message is the description of the error -func (e SharedConfigProfileNotExistsError) Message() string { - return fmt.Sprintf("failed to get profile, %s", e.Profile) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigProfileNotExistsError) OrigErr() error { - return e.Err -} - -// Error satisfies the error interface. -func (e SharedConfigProfileNotExistsError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", e.Err) -} - -// 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 { - RoleARN string -} - -// Code is the short id of the error. -func (e SharedConfigAssumeRoleError) Code() string { - return "SharedConfigAssumeRoleError" -} - -// Message is the description of the error -func (e SharedConfigAssumeRoleError) Message() string { - return fmt.Sprintf("failed to load assume role for %s, source profile has no shared credentials", - e.RoleARN) -} - -// OrigErr is the underlying error that caused the failure. -func (e SharedConfigAssumeRoleError) OrigErr() error { - return nil -} - -// Error satisfies the error interface. -func (e SharedConfigAssumeRoleError) Error() string { - return awserr.SprintError(e.Code(), e.Message(), "", nil) -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go deleted file mode 100644 index 244c86da0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/header_rules.go +++ /dev/null @@ -1,82 +0,0 @@ -package v4 - -import ( - "net/http" - "strings" -) - -// validator 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 -} - -// whitelist is a generic rule for whitelisting -type whitelist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (w whitelist) IsValid(value string) bool { - return w.rule.IsValid(value) -} - -// blacklist is a generic rule for blacklisting -type blacklist struct { - rule -} - -// IsValid for whitelist checks if the value is within the whitelist -func (b blacklist) IsValid(value string) bool { - return !b.rule.IsValid(value) -} - -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 strings.HasPrefix(http.CanonicalHeaderKey(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/aws/signer/v4/options.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go deleted file mode 100644 index 6aa2ed241..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/options.go +++ /dev/null @@ -1,7 +0,0 @@ -package v4 - -// WithUnsignedPayload will enable and set the UnsignedPayload field to -// true of the signer. -func WithUnsignedPayload(v4 *Signer) { - v4.UnsignedPayload = true -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go deleted file mode 100644 index bd082e9d1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/uri_path.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.5 - -package v4 - -import ( - "net/url" - "strings" -) - -func getURIPath(u *url.URL) string { - var uri string - - if len(u.Opaque) > 0 { - uri = "/" + strings.Join(strings.Split(u.Opaque, "/")[3:], "/") - } else { - uri = u.EscapedPath() - } - - if len(uri) == 0 { - uri = "/" - } - - return uri -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go b/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go deleted file mode 100644 index 6e4637612..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/signer/v4/v4.go +++ /dev/null @@ -1,779 +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 -// logic when using Go v1.5 or higher. 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. If you're using Go v1.4 you must set -// URL.Opaque if the URI path needs escaping. If URL.Opaque is not set with -// Go v1.5 the signer will fallback to URL.Path. -// -// 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. -// -// If signing a request intended for HTTP2 server, and you're using Go 1.6.2 -// through 1.7.4 you should use the URL.RawPath as the pre-escaped form of the -// request URL. https://github.com/golang/go/issues/16847 points to a bug in -// Go pre 1.8 that fails to make HTTP2 requests using absolute URL in the HTTP -// message. URL.Opaque generally will force Go to make requests with absolute URL. -// URL.RawPath does not do this, but RawPath must be a valid escaping of Path -// or url.EscapedPath will ignore the RawPath escaping. -// -// Test `TestStandaloneSign` provides a complete example of using the signer -// outside of the SDK and pre-escaping the URI path. -package v4 - -import ( - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/credentials" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/internal/sdkio" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -const ( - authHeaderPrefix = "AWS4-HMAC-SHA256" - timeFormat = "20060102T150405Z" - shortTimeFormat = "20060102" - - // emptyStringSHA256 is a SHA256 of an empty string - emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855` -) - -var ignoredHeaders = rules{ - blacklist{ - mapRule{ - "Authorization": struct{}{}, - "User-Agent": struct{}{}, - "X-Amzn-Trace-Id": struct{}{}, - }, - }, -} - -// requiredSignedHeaders is a whitelist for build canonical headers. -var requiredSignedHeaders = rules{ - whitelist{ - 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-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{}{}, - }, - }, - patterns{"X-Amz-Meta-"}, -} - -// allowedHoisting is a whitelist for build query headers. The boolean value -// represents whether or not it is a pattern. -var allowedQueryHoisting = inclusiveRules{ - blacklist{requiredSignedHeaders}, - patterns{"X-Amz-"}, -} - -// 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 { - // The authentication credentials the request will be signed against. - // This value must be set to sign requests. - Credentials *credentials.Credentials - - // Sets the log level the signer should use when reporting information to - // the logger. If the logger is nil nothing will be logged. See - // aws.LogLevelType for more information on available logging levels - // - // By default nothing will be logged. - Debug aws.LogLevelType - - // The logger loging information will be written to. If there the logger - // is nil, nothing will be logged. - Logger aws.Logger - - // 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 - - // Disales the automatical setting of the HTTP request's Body field with the - // io.ReadSeeker passed in to the signer. This is useful if you're using a - // custom wrapper around the body for the io.ReadSeeker and want to preserve - // the Body value on the Request.Body. - // - // This does run the risk of signing a request with a body that will not be - // sent in the request. Need to ensure that the underlying data of the Body - // values are the same. - DisableRequestBodyOverwrite bool - - // currentTimeFn returns the time value which represents the current time. - // This value should only be used for testing. If it is nil the default - // time.Now will be used. - currentTimeFn func() time.Time - - // UnsignedPayload will prevent signing of the payload. This will only - // work for services that have support for this. - UnsignedPayload bool -} - -// NewSigner returns a Signer pointer configured with the credentials and optional -// option values provided. If not options are provided the Signer will use its -// default configuration. -func NewSigner(credentials *credentials.Credentials, options ...func(*Signer)) *Signer { - v4 := &Signer{ - Credentials: credentials, - } - - for _, option := range options { - option(v4) - } - - return v4 -} - -type signingCtx struct { - ServiceName string - Region string - Request *http.Request - Body io.ReadSeeker - Query url.Values - Time time.Time - ExpireTime time.Duration - SignedHeaderVals http.Header - - DisableURIPathEscaping bool - - credValues credentials.Value - isPresign bool - formattedTime string - formattedShortTime string - unsignedPayload bool - - bodyDigest string - signedHeaders string - canonicalHeaders string - canonicalString string - credentialString string - stringToSign string - signature string - authorization string -} - -// Sign signs AWS v4 requests with the provided body, 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 a list of HTTP headers that were included in the signature or an -// error if signing the request failed. Generally for signed requests this value -// is not needed as the full request context will be captured by the http.Request -// value. It is included for reference though. -// -// Sign will set the request's Body to be the `body` parameter passed in. If -// the body is not already an io.ReadCloser, it will be wrapped within one. If -// a `nil` body parameter passed to Sign, the request's Body field will be -// also set to nil. Its important to note that this functionality will not -// change the request's ContentLength of the request. -// -// 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 requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -func (v4 Signer) Sign(r *http.Request, body io.ReadSeeker, service, region string, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, 0, false, signTime) -} - -// Presign signs AWS v4 requests with the provided body, 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 a list 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. -// -// Presign differs from Sign 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. -// -// Presign also takes an exp value which is the duration the -// signed request will be valid after the signing time. This is allows you to -// set when the request will expire. -// -// The requests body is an io.ReadSeeker so the SHA256 of the body can be -// generated. To bypass the signer computing the hash you can set the -// "X-Amz-Content-Sha256" header with a precomputed value. The signer will -// only compute the hash if the request header value is empty. -// -// Presigning a S3 request will not compute the body's SHA256 hash by default. -// This is done due to the general use case for S3 presigned URLs is to share -// PUT/GET capabilities. If you would like to include the body's SHA256 in the -// presigned request's signature you can set the "X-Amz-Content-Sha256" -// HTTP header and that will be included in the request's signature. -func (v4 Signer) Presign(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, signTime time.Time) (http.Header, error) { - return v4.signWithBody(r, body, service, region, exp, true, signTime) -} - -func (v4 Signer) signWithBody(r *http.Request, body io.ReadSeeker, service, region string, exp time.Duration, isPresign bool, signTime time.Time) (http.Header, error) { - currentTimeFn := v4.currentTimeFn - if currentTimeFn == nil { - currentTimeFn = time.Now - } - - ctx := &signingCtx{ - Request: r, - Body: body, - Query: r.URL.Query(), - Time: signTime, - ExpireTime: exp, - isPresign: isPresign, - ServiceName: service, - Region: region, - DisableURIPathEscaping: v4.DisableURIPathEscaping, - unsignedPayload: v4.UnsignedPayload, - } - - for key := range ctx.Query { - sort.Strings(ctx.Query[key]) - } - - if ctx.isRequestSigned() { - ctx.Time = currentTimeFn() - ctx.handlePresignRemoval() - } - - var err error - ctx.credValues, err = v4.Credentials.Get() - if err != nil { - return http.Header{}, err - } - - ctx.sanitizeHostForHeader() - ctx.assignAmzQueryValues() - if err := ctx.build(v4.DisableHeaderHoisting); err != nil { - return nil, err - } - - // If the request is not presigned the body should be attached to it. This - // prevents the confusion of wanting to send a signed request without - // the body the request was signed for attached. - if !(v4.DisableRequestBodyOverwrite || ctx.isPresign) { - var reader io.ReadCloser - if body != nil { - var ok bool - if reader, ok = body.(io.ReadCloser); !ok { - reader = ioutil.NopCloser(body) - } - } - r.Body = reader - } - - if v4.Debug.Matches(aws.LogDebugWithSigning) { - v4.logSigningInfo(ctx) - } - - return ctx.SignedHeaderVals, nil -} - -func (ctx *signingCtx) sanitizeHostForHeader() { - request.SanitizeHostForHeader(ctx.Request) -} - -func (ctx *signingCtx) handlePresignRemoval() { - if !ctx.isPresign { - return - } - - // The credentials have expired for this request. The current signing - // is invalid, and needs to be request because the request will fail. - ctx.removePresign() - - // Update the request's query string to ensure the values stays in - // sync in the case retrieving the new credentials fails. - ctx.Request.URL.RawQuery = ctx.Query.Encode() -} - -func (ctx *signingCtx) assignAmzQueryValues() { - if ctx.isPresign { - ctx.Query.Set("X-Amz-Algorithm", authHeaderPrefix) - if ctx.credValues.SessionToken != "" { - ctx.Query.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } else { - ctx.Query.Del("X-Amz-Security-Token") - } - - return - } - - if ctx.credValues.SessionToken != "" { - ctx.Request.Header.Set("X-Amz-Security-Token", ctx.credValues.SessionToken) - } -} - -// SignRequestHandler is a named request handler the SDK will use to sign -// service client request with using the V4 signature. -var SignRequestHandler = request.NamedHandler{ - Name: "v4.SignRequestHandler", Fn: SignSDKRequest, -} - -// SignSDKRequest signs an AWS request with the V4 signature. This -// request handler should only be used with the SDK's built in service client's -// API operation requests. -// -// This function should not be used on its on its own, but in conjunction with -// an AWS service client's API operation call. To sign a standalone request -// not created by a service client's API operation method use the "Sign" or -// "Presign" functions of the "Signer" type. -// -// If the credentials of the request's config are set to -// credentials.AnonymousCredentials the request will not be signed. -func SignSDKRequest(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now) -} - -// BuildNamedHandler will build a generic handler for signing. -func BuildNamedHandler(name string, opts ...func(*Signer)) request.NamedHandler { - return request.NamedHandler{ - Name: name, - Fn: func(req *request.Request) { - signSDKRequestWithCurrTime(req, time.Now, opts...) - }, - } -} - -func signSDKRequestWithCurrTime(req *request.Request, curTimeFn func() time.Time, opts ...func(*Signer)) { - // If the request does not need to be signed ignore the signing of the - // request if the AnonymousCredentials object is used. - if req.Config.Credentials == credentials.AnonymousCredentials { - return - } - - region := req.ClientInfo.SigningRegion - if region == "" { - region = aws.StringValue(req.Config.Region) - } - - name := req.ClientInfo.SigningName - if name == "" { - name = req.ClientInfo.ServiceName - } - - v4 := NewSigner(req.Config.Credentials, func(v4 *Signer) { - v4.Debug = req.Config.LogLevel.Value() - v4.Logger = req.Config.Logger - v4.DisableHeaderHoisting = req.NotHoist - v4.currentTimeFn = curTimeFn - if name == "s3" { - // S3 service should not have any escaping applied - v4.DisableURIPathEscaping = true - } - // Prevents setting the HTTPRequest's Body. Since the Body could be - // wrapped in a custom io.Closer that we do not want to be stompped - // on top of by the signer. - v4.DisableRequestBodyOverwrite = true - }) - - for _, opt := range opts { - opt(v4) - } - - signingTime := req.Time - if !req.LastSignedAt.IsZero() { - signingTime = req.LastSignedAt - } - - signedHeaders, err := v4.signWithBody(req.HTTPRequest, req.GetBody(), - name, region, req.ExpireTime, req.ExpireTime > 0, signingTime, - ) - if err != nil { - req.Error = err - req.SignedHeaderVals = nil - return - } - - req.SignedHeaderVals = signedHeaders - req.LastSignedAt = curTimeFn() -} - -const logSignInfoMsg = `DEBUG: Request Signature: ----[ CANONICAL STRING ]----------------------------- -%s ----[ STRING TO SIGN ]-------------------------------- -%s%s ------------------------------------------------------` -const logSignedURLMsg = ` ----[ SIGNED URL ]------------------------------------ -%s` - -func (v4 *Signer) logSigningInfo(ctx *signingCtx) { - signedURLMsg := "" - if ctx.isPresign { - signedURLMsg = fmt.Sprintf(logSignedURLMsg, ctx.Request.URL.String()) - } - msg := fmt.Sprintf(logSignInfoMsg, ctx.canonicalString, ctx.stringToSign, signedURLMsg) - v4.Logger.Log(msg) -} - -func (ctx *signingCtx) build(disableHeaderHoisting bool) error { - ctx.buildTime() // no depends - ctx.buildCredentialString() // no depends - - if err := ctx.buildBodyDigest(); err != nil { - return err - } - - unsignedHeaders := ctx.Request.Header - if ctx.isPresign { - if !disableHeaderHoisting { - urlValues := url.Values{} - urlValues, unsignedHeaders = buildQuery(allowedQueryHoisting, unsignedHeaders) // no depends - for k := range urlValues { - ctx.Query[k] = urlValues[k] - } - } - } - - ctx.buildCanonicalHeaders(ignoredHeaders, unsignedHeaders) - ctx.buildCanonicalString() // depends on canon headers / signed headers - ctx.buildStringToSign() // depends on canon string - ctx.buildSignature() // depends on string to sign - - if ctx.isPresign { - ctx.Request.URL.RawQuery += "&X-Amz-Signature=" + ctx.signature - } else { - parts := []string{ - authHeaderPrefix + " Credential=" + ctx.credValues.AccessKeyID + "/" + ctx.credentialString, - "SignedHeaders=" + ctx.signedHeaders, - "Signature=" + ctx.signature, - } - ctx.Request.Header.Set("Authorization", strings.Join(parts, ", ")) - } - - return nil -} - -func (ctx *signingCtx) buildTime() { - ctx.formattedTime = ctx.Time.UTC().Format(timeFormat) - ctx.formattedShortTime = ctx.Time.UTC().Format(shortTimeFormat) - - if ctx.isPresign { - duration := int64(ctx.ExpireTime / time.Second) - ctx.Query.Set("X-Amz-Date", ctx.formattedTime) - ctx.Query.Set("X-Amz-Expires", strconv.FormatInt(duration, 10)) - } else { - ctx.Request.Header.Set("X-Amz-Date", ctx.formattedTime) - } -} - -func (ctx *signingCtx) buildCredentialString() { - ctx.credentialString = strings.Join([]string{ - ctx.formattedShortTime, - ctx.Region, - ctx.ServiceName, - "aws4_request", - }, "/") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-Credential", ctx.credValues.AccessKeyID+"/"+ctx.credentialString) - } -} - -func buildQuery(r 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 (ctx *signingCtx) buildCanonicalHeaders(r rule, header http.Header) { - var headers []string - headers = append(headers, "host") - for k, v := range header { - canonicalKey := http.CanonicalHeaderKey(k) - if !r.IsValid(canonicalKey) { - continue // ignored header - } - if ctx.SignedHeaderVals == nil { - ctx.SignedHeaderVals = make(http.Header) - } - - lowerCaseKey := strings.ToLower(k) - if _, ok := ctx.SignedHeaderVals[lowerCaseKey]; ok { - // include additional values - ctx.SignedHeaderVals[lowerCaseKey] = append(ctx.SignedHeaderVals[lowerCaseKey], v...) - continue - } - - headers = append(headers, lowerCaseKey) - ctx.SignedHeaderVals[lowerCaseKey] = v - } - sort.Strings(headers) - - ctx.signedHeaders = strings.Join(headers, ";") - - if ctx.isPresign { - ctx.Query.Set("X-Amz-SignedHeaders", ctx.signedHeaders) - } - - headerValues := make([]string, len(headers)) - for i, k := range headers { - if k == "host" { - if ctx.Request.Host != "" { - headerValues[i] = "host:" + ctx.Request.Host - } else { - headerValues[i] = "host:" + ctx.Request.URL.Host - } - } else { - headerValues[i] = k + ":" + - strings.Join(ctx.SignedHeaderVals[k], ",") - } - } - stripExcessSpaces(headerValues) - ctx.canonicalHeaders = strings.Join(headerValues, "\n") -} - -func (ctx *signingCtx) buildCanonicalString() { - ctx.Request.URL.RawQuery = strings.Replace(ctx.Query.Encode(), "+", "%20", -1) - - uri := getURIPath(ctx.Request.URL) - - if !ctx.DisableURIPathEscaping { - uri = rest.EscapePath(uri, false) - } - - ctx.canonicalString = strings.Join([]string{ - ctx.Request.Method, - uri, - ctx.Request.URL.RawQuery, - ctx.canonicalHeaders + "\n", - ctx.signedHeaders, - ctx.bodyDigest, - }, "\n") -} - -func (ctx *signingCtx) buildStringToSign() { - ctx.stringToSign = strings.Join([]string{ - authHeaderPrefix, - ctx.formattedTime, - ctx.credentialString, - hex.EncodeToString(makeSha256([]byte(ctx.canonicalString))), - }, "\n") -} - -func (ctx *signingCtx) buildSignature() { - secret := ctx.credValues.SecretAccessKey - date := makeHmac([]byte("AWS4"+secret), []byte(ctx.formattedShortTime)) - region := makeHmac(date, []byte(ctx.Region)) - service := makeHmac(region, []byte(ctx.ServiceName)) - credentials := makeHmac(service, []byte("aws4_request")) - signature := makeHmac(credentials, []byte(ctx.stringToSign)) - ctx.signature = hex.EncodeToString(signature) -} - -func (ctx *signingCtx) buildBodyDigest() error { - hash := ctx.Request.Header.Get("X-Amz-Content-Sha256") - if hash == "" { - if ctx.unsignedPayload || (ctx.isPresign && ctx.ServiceName == "s3") { - hash = "UNSIGNED-PAYLOAD" - } else if ctx.Body == nil { - hash = emptyStringSHA256 - } else { - if !aws.IsReaderSeekable(ctx.Body) { - return fmt.Errorf("cannot use unseekable request body %T, for signed request with body", ctx.Body) - } - hash = hex.EncodeToString(makeSha256Reader(ctx.Body)) - } - if ctx.unsignedPayload || ctx.ServiceName == "s3" || ctx.ServiceName == "glacier" { - ctx.Request.Header.Set("X-Amz-Content-Sha256", hash) - } - } - ctx.bodyDigest = hash - - return nil -} - -// isRequestSigned returns if the request is currently signed or presigned -func (ctx *signingCtx) isRequestSigned() bool { - if ctx.isPresign && ctx.Query.Get("X-Amz-Signature") != "" { - return true - } - if ctx.Request.Header.Get("Authorization") != "" { - return true - } - - return false -} - -// unsign removes signing flags for both signed and presigned requests. -func (ctx *signingCtx) removePresign() { - ctx.Query.Del("X-Amz-Algorithm") - ctx.Query.Del("X-Amz-Signature") - ctx.Query.Del("X-Amz-Security-Token") - ctx.Query.Del("X-Amz-Date") - ctx.Query.Del("X-Amz-Expires") - ctx.Query.Del("X-Amz-Credential") - ctx.Query.Del("X-Amz-SignedHeaders") -} - -func makeHmac(key []byte, data []byte) []byte { - hash := hmac.New(sha256.New, key) - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256(data []byte) []byte { - hash := sha256.New() - hash.Write(data) - return hash.Sum(nil) -} - -func makeSha256Reader(reader io.ReadSeeker) []byte { - hash := sha256.New() - start, _ := reader.Seek(0, sdkio.SeekCurrent) - defer reader.Seek(start, sdkio.SeekStart) - - io.Copy(hash, reader) - return hash.Sum(nil) -} - -const doubleSpace = " " - -// stripExcessSpaces will rewrite the passed in slice's string values to not -// contain muliple side-by-side spaces. -func stripExcessSpaces(vals []string) { - var j, k, l, m, spaces int - for i, str := range vals { - // 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 { - vals[i] = str - continue - } - - 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++ - } - } - - vals[i] = string(buf[:m]) - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/types.go b/vendor/github.com/aws/aws-sdk-go/aws/types.go deleted file mode 100644 index 8b6f23425..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/types.go +++ /dev/null @@ -1,201 +0,0 @@ -package aws - -import ( - "io" - "sync" - - "github.com/aws/aws-sdk-go/internal/sdkio" -) - -// ReadSeekCloser wraps a io.Reader returning a ReaderSeekerCloser. Should -// only be used with an io.Reader that is also an io.Seeker. Doing so may -// cause request signature errors, or request body's not sent for GET, HEAD -// and DELETE HTTP methods. -// -// Deprecated: Should only be used with io.ReadSeeker. If using for -// S3 PutObject to stream content use s3manager.Uploader instead. -func ReadSeekCloser(r io.Reader) ReaderSeekerCloser { - return ReaderSeekerCloser{r} -} - -// ReaderSeekerCloser represents a reader that can also delegate io.Seeker and -// io.Closer interfaces to the underlying object if they are available. -type ReaderSeekerCloser struct { - r io.Reader -} - -// IsReaderSeekable returns if the underlying reader type can be seeked. A -// io.Reader might not actually be seekable if it is the ReaderSeekerCloser -// type. -func IsReaderSeekable(r io.Reader) bool { - switch v := r.(type) { - case ReaderSeekerCloser: - return v.IsSeeker() - case *ReaderSeekerCloser: - return v.IsSeeker() - case io.ReadSeeker: - return true - default: - return false - } -} - -// Read reads from the reader up to size of p. The number of bytes read, and -// error if it occurred will be returned. -// -// If the reader is not an io.Reader zero bytes read, and nil error will be returned. -// -// Performs the same functionality as io.Reader Read -func (r ReaderSeekerCloser) Read(p []byte) (int, error) { - switch t := r.r.(type) { - case io.Reader: - return t.Read(p) - } - return 0, nil -} - -// Seek sets the offset for the next Read to offset, interpreted according to -// whence: 0 means relative to the origin of the file, 1 means relative to the -// current offset, and 2 means relative to the end. Seek returns the new offset -// and an error, if any. -// -// If the ReaderSeekerCloser is not an io.Seeker nothing will be done. -func (r ReaderSeekerCloser) Seek(offset int64, whence int) (int64, error) { - switch t := r.r.(type) { - case io.Seeker: - return t.Seek(offset, whence) - } - return int64(0), nil -} - -// IsSeeker returns if the underlying reader is also a seeker. -func (r ReaderSeekerCloser) IsSeeker() bool { - _, ok := r.r.(io.Seeker) - return ok -} - -// HasLen returns the length of the underlying reader if the value implements -// the Len() int method. -func (r ReaderSeekerCloser) HasLen() (int, bool) { - type lenner interface { - Len() int - } - - if lr, ok := r.r.(lenner); ok { - return lr.Len(), true - } - - return 0, false -} - -// GetLen returns the length of the bytes remaining in the underlying reader. -// Checks first for Len(), then io.Seeker to determine the size of the -// underlying reader. -// -// Will return -1 if the length cannot be determined. -func (r ReaderSeekerCloser) GetLen() (int64, error) { - if l, ok := r.HasLen(); ok { - return int64(l), nil - } - - if s, ok := r.r.(io.Seeker); ok { - return seekerLen(s) - } - - return -1, nil -} - -// SeekerLen attempts to get the number of bytes remaining at the seeker's -// current position. Returns the number of bytes remaining or error. -func SeekerLen(s io.Seeker) (int64, error) { - // Determine if the seeker is actually seekable. ReaderSeekerCloser - // hides the fact that a io.Readers might not actually be seekable. - switch v := s.(type) { - case ReaderSeekerCloser: - return v.GetLen() - case *ReaderSeekerCloser: - return v.GetLen() - } - - return seekerLen(s) -} - -func seekerLen(s io.Seeker) (int64, error) { - curOffset, err := s.Seek(0, sdkio.SeekCurrent) - if err != nil { - return 0, err - } - - endOffset, err := s.Seek(0, sdkio.SeekEnd) - if err != nil { - return 0, err - } - - _, err = s.Seek(curOffset, sdkio.SeekStart) - if err != nil { - return 0, err - } - - return endOffset - curOffset, nil -} - -// Close closes the ReaderSeekerCloser. -// -// If the ReaderSeekerCloser is not an io.Closer nothing will be done. -func (r ReaderSeekerCloser) Close() error { - switch t := r.r.(type) { - case io.Closer: - return t.Close() - } - return nil -} - -// A WriteAtBuffer provides a in memory buffer supporting the io.WriterAt interface -// Can be used with the s3manager.Downloader to download content to a buffer -// in memory. Safe to use concurrently. -type WriteAtBuffer struct { - buf []byte - m sync.Mutex - - // GrowthCoeff defines the growth rate of the internal buffer. By - // default, the growth rate is 1, where expanding the internal - // buffer will allocate only enough capacity to fit the new expected - // length. - GrowthCoeff float64 -} - -// NewWriteAtBuffer creates a WriteAtBuffer with an internal buffer -// provided by buf. -func NewWriteAtBuffer(buf []byte) *WriteAtBuffer { - return &WriteAtBuffer{buf: buf} -} - -// WriteAt writes a slice of bytes to a buffer starting at the position provided -// The number of bytes written will be returned, or error. Can overwrite previous -// written slices if the write ats overlap. -func (b *WriteAtBuffer) WriteAt(p []byte, pos int64) (n int, err error) { - pLen := len(p) - expLen := pos + int64(pLen) - b.m.Lock() - defer b.m.Unlock() - if int64(len(b.buf)) < expLen { - if int64(cap(b.buf)) < expLen { - if b.GrowthCoeff < 1 { - b.GrowthCoeff = 1 - } - newBuf := make([]byte, expLen, int64(b.GrowthCoeff*float64(expLen))) - copy(newBuf, b.buf) - b.buf = newBuf - } - b.buf = b.buf[:expLen] - } - copy(b.buf[pos:], p) - return pLen, nil -} - -// Bytes returns a slice of bytes written to the buffer. -func (b *WriteAtBuffer) Bytes() []byte { - b.m.Lock() - defer b.m.Unlock() - return b.buf -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url.go b/vendor/github.com/aws/aws-sdk-go/aws/url.go deleted file mode 100644 index 6192b2455..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.8 - -package aws - -import "net/url" - -// URLHostname will extract the Hostname without port from the URL value. -// -// Wrapper of net/url#URL.Hostname for backwards Go version compatibility. -func URLHostname(url *url.URL) string { - return url.Hostname() -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go b/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go deleted file mode 100644 index 0210d2720..000000000 --- a/vendor/github.com/aws/aws-sdk-go/aws/url_1_7.go +++ /dev/null @@ -1,29 +0,0 @@ -// +build !go1.8 - -package aws - -import ( - "net/url" - "strings" -) - -// URLHostname will extract the Hostname without port from the URL value. -// -// Copy of Go 1.8's net/url#URL.Hostname functionality. -func URLHostname(url *url.URL) string { - return stripPort(url.Host) - -} - -// stripPort is copy of Go 1.8 url#URL.Hostname functionality. -// https://golang.org/src/net/url/url.go -func stripPort(hostport string) string { - colon := strings.IndexByte(hostport, ':') - if colon == -1 { - return hostport - } - if i := strings.IndexByte(hostport, ']'); i != -1 { - return strings.TrimPrefix(hostport[:i], "[") - } - return hostport[:colon] -} diff --git a/vendor/github.com/aws/aws-sdk-go/aws/version.go b/vendor/github.com/aws/aws-sdk-go/aws/version.go deleted file mode 100644 index 22ae23fa2..000000000 --- a/vendor/github.com/aws/aws-sdk-go/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" - -// SDKVersion is the version of this SDK -const SDKVersion = "1.13.54" diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go deleted file mode 100644 index 5aa9137e0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.6.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !go1.7 - -package sdkio - -// Copy of Go 1.7 io package's Seeker constants. -const ( - SeekStart = 0 // seek relative to the origin of the file - SeekCurrent = 1 // seek relative to the current offset - SeekEnd = 2 // seek relative to the end -) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go deleted file mode 100644 index e5f005613..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkio/io_go1.7.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build go1.7 - -package sdkio - -import "io" - -// Alias for Go 1.7 io package Seeker constants -const ( - SeekStart = io.SeekStart // seek relative to the origin of the file - SeekCurrent = io.SeekCurrent // seek relative to the current offset - SeekEnd = io.SeekEnd // seek relative to the end -) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go b/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go deleted file mode 100644 index 0c9802d87..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/sdkrand/locked_source.go +++ /dev/null @@ -1,29 +0,0 @@ -package sdkrand - -import ( - "math/rand" - "sync" - "time" -) - -// lockedSource is a thread-safe implementation of rand.Source -type lockedSource struct { - lk sync.Mutex - src rand.Source -} - -func (r *lockedSource) Int63() (n int64) { - r.lk.Lock() - n = r.src.Int63() - r.lk.Unlock() - return -} - -func (r *lockedSource) Seed(seed int64) { - r.lk.Lock() - r.src.Seed(seed) - r.lk.Unlock() -} - -// SeededRand is a new RNG using a thread safe implementation of rand.Source -var SeededRand = rand.New(&lockedSource{src: rand.NewSource(time.Now().UnixNano())}) diff --git a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go b/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go deleted file mode 100644 index ebcbc2b40..000000000 --- a/vendor/github.com/aws/aws-sdk-go/internal/shareddefaults/shared_config.go +++ /dev/null @@ -1,40 +0,0 @@ -package shareddefaults - -import ( - "os" - "path/filepath" - "runtime" -) - -// 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 { - if runtime.GOOS == "windows" { // Windows - return os.Getenv("USERPROFILE") - } - - // *nix - return os.Getenv("HOME") -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go deleted file mode 100644 index 53831dff9..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/idempotency.go +++ /dev/null @@ -1,75 +0,0 @@ -package protocol - -import ( - "crypto/rand" - "fmt" - "reflect" -) - -// RandReader is the random reader the protocol package will use to read -// random bytes from. This is exported for testing, and should not be used. -var RandReader = rand.Reader - -const idempotencyTokenFillTag = `idempotencyToken` - -// CanSetIdempotencyToken returns true if the struct field should be -// automatically populated with a Idempotency token. -// -// Only *string and string type fields that are tagged with idempotencyToken -// which are not already set can be auto filled. -func CanSetIdempotencyToken(v reflect.Value, f reflect.StructField) bool { - switch u := v.Interface().(type) { - // To auto fill an Idempotency token the field must be a string, - // tagged for auto fill, and have a zero value. - case *string: - return u == nil && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - case string: - return len(u) == 0 && len(f.Tag.Get(idempotencyTokenFillTag)) != 0 - } - - return false -} - -// GetIdempotencyToken returns a randomly generated idempotency token. -func GetIdempotencyToken() string { - b := make([]byte, 16) - RandReader.Read(b) - - return UUIDVersion4(b) -} - -// SetIdempotencyToken will set the value provided with a Idempotency Token. -// Given that the value can be set. Will panic if value is not setable. -func SetIdempotencyToken(v reflect.Value) { - if v.Kind() == reflect.Ptr { - if v.IsNil() && v.CanSet() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - v = reflect.Indirect(v) - - if !v.CanSet() { - panic(fmt.Sprintf("unable to set idempotnecy token %v", v)) - } - - b := make([]byte, 16) - _, err := rand.Read(b) - if err != nil { - // TODO handle error - return - } - - v.Set(reflect.ValueOf(UUIDVersion4(b))) -} - -// UUIDVersion4 returns a Version 4 random UUID from the byte slice provided -func UUIDVersion4(u []byte) string { - // https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_.28random.29 - // 13th character is "4" - u[6] = (u[6] | 0x40) & 0x4F - // 17th character is "8", "9", "a", or "b" - u[8] = (u[8] | 0x80) & 0xBF - - return fmt.Sprintf(`%X-%X-%X-%X-%X`, u[0:4], u[4:6], u[6:8], u[8:10], u[10:]) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go deleted file mode 100644 index ec765ba25..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/build.go +++ /dev/null @@ -1,286 +0,0 @@ -// Package jsonutil provides JSON serialization of AWS requests and responses. -package jsonutil - -import ( - "bytes" - "encoding/base64" - "encoding/json" - "fmt" - "math" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/private/protocol" -) - -var timeType = reflect.ValueOf(time.Time{}).Type() -var byteSliceType = reflect.ValueOf([]byte{}).Type() - -// BuildJSON builds a JSON string for a given object v. -func BuildJSON(v interface{}) ([]byte, error) { - var buf bytes.Buffer - - err := buildAny(reflect.ValueOf(v), &buf, "") - return buf.Bytes(), err -} - -func buildAny(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - origVal := value - value = reflect.Indirect(value) - if !value.IsValid() { - return nil - } - - vtype := value.Type() - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if value.Type() != timeType { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return buildStruct(value, buf, tag) - case "list": - return buildList(value, buf, tag) - case "map": - return buildMap(value, buf, tag) - default: - return buildScalar(origVal, buf, tag) - } -} - -func buildStruct(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - buf.WriteByte('{') - - t := value.Type() - first := true - for i := 0; i < t.NumField(); i++ { - member := value.Field(i) - - // This allocates the most memory. - // Additionally, we cannot skip nil fields due to - // idempotency auto filling. - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("json") == "-" { - continue - } - if field.Tag.Get("location") != "" { - continue // ignore non-body elements - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(member, field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(&token) - } - - if (member.Kind() == reflect.Ptr || member.Kind() == reflect.Slice || member.Kind() == reflect.Map) && member.IsNil() { - continue // ignore unset fields - } - - if first { - first = false - } else { - buf.WriteByte(',') - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - writeString(name, buf) - buf.WriteString(`:`) - - err := buildAny(member, buf, field.Tag) - if err != nil { - return err - } - - } - - buf.WriteString("}") - - return nil -} - -func buildList(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("[") - - for i := 0; i < value.Len(); i++ { - buildAny(value.Index(i), buf, "") - - if i < value.Len()-1 { - buf.WriteString(",") - } - } - - buf.WriteString("]") - - return nil -} - -type sortedValues []reflect.Value - -func (sv sortedValues) Len() int { return len(sv) } -func (sv sortedValues) Swap(i, j int) { sv[i], sv[j] = sv[j], sv[i] } -func (sv sortedValues) Less(i, j int) bool { return sv[i].String() < sv[j].String() } - -func buildMap(value reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - buf.WriteString("{") - - sv := sortedValues(value.MapKeys()) - sort.Sort(sv) - - for i, k := range sv { - if i > 0 { - buf.WriteByte(',') - } - - writeString(k.String(), buf) - buf.WriteString(`:`) - - buildAny(value.MapIndex(k), buf, "") - } - - buf.WriteString("}") - - return nil -} - -func buildScalar(v reflect.Value, buf *bytes.Buffer, tag reflect.StructTag) error { - // prevents allocation on the heap. - scratch := [64]byte{} - switch value := reflect.Indirect(v); value.Kind() { - case reflect.String: - writeString(value.String(), buf) - case reflect.Bool: - if value.Bool() { - buf.WriteString("true") - } else { - buf.WriteString("false") - } - case reflect.Int64: - buf.Write(strconv.AppendInt(scratch[:0], value.Int(), 10)) - case reflect.Float64: - f := value.Float() - if math.IsInf(f, 0) || math.IsNaN(f) { - return &json.UnsupportedValueError{Value: v, Str: strconv.FormatFloat(f, 'f', -1, 64)} - } - buf.Write(strconv.AppendFloat(scratch[:0], f, 'f', -1, 64)) - default: - switch converted := value.Interface().(type) { - case time.Time: - buf.Write(strconv.AppendInt(scratch[:0], converted.UTC().Unix(), 10)) - case []byte: - if !value.IsNil() { - buf.WriteByte('"') - if len(converted) < 1024 { - // for small buffers, using Encode directly is much faster. - dst := make([]byte, base64.StdEncoding.EncodedLen(len(converted))) - base64.StdEncoding.Encode(dst, converted) - buf.Write(dst) - } else { - // for large buffers, avoid unnecessary extra temporary - // buffer space. - enc := base64.NewEncoder(base64.StdEncoding, buf) - enc.Write(converted) - enc.Close() - } - buf.WriteByte('"') - } - case aws.JSONValue: - str, err := protocol.EncodeJSONValue(converted, protocol.QuotedEscape) - if err != nil { - return fmt.Errorf("unable to encode JSONValue, %v", err) - } - buf.WriteString(str) - default: - return fmt.Errorf("unsupported JSON value %v (%s)", value.Interface(), value.Type()) - } - } - return nil -} - -var hex = "0123456789abcdef" - -func writeString(s string, buf *bytes.Buffer) { - buf.WriteByte('"') - for i := 0; i < len(s); i++ { - if s[i] == '"' { - buf.WriteString(`\"`) - } else if s[i] == '\\' { - buf.WriteString(`\\`) - } else if s[i] == '\b' { - buf.WriteString(`\b`) - } else if s[i] == '\f' { - buf.WriteString(`\f`) - } else if s[i] == '\r' { - buf.WriteString(`\r`) - } else if s[i] == '\t' { - buf.WriteString(`\t`) - } else if s[i] == '\n' { - buf.WriteString(`\n`) - } else if s[i] < 32 { - buf.WriteString("\\u00") - buf.WriteByte(hex[s[i]>>4]) - buf.WriteByte(hex[s[i]&0xF]) - } else { - buf.WriteByte(s[i]) - } - } - buf.WriteByte('"') -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go deleted file mode 100644 index 037e1e7be..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/json/jsonutil/unmarshal.go +++ /dev/null @@ -1,226 +0,0 @@ -package jsonutil - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "reflect" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalJSON reads a stream and unmarshals the results in object v. -func UnmarshalJSON(v interface{}, stream io.Reader) error { - var out interface{} - - b, err := ioutil.ReadAll(stream) - if err != nil { - return err - } - - if len(b) == 0 { - return nil - } - - if err := json.Unmarshal(b, &out); err != nil { - return err - } - - return unmarshalAny(reflect.ValueOf(v), out, "") -} - -func unmarshalAny(value reflect.Value, data interface{}, tag reflect.StructTag) error { - vtype := value.Type() - if vtype.Kind() == reflect.Ptr { - vtype = vtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch vtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := value.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := value.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - // cannot be a JSONValue map - if _, ok := value.Interface().(aws.JSONValue); !ok { - t = "map" - } - } - } - - switch t { - case "structure": - if field, ok := vtype.FieldByName("_"); ok { - tag = field.Tag - } - return unmarshalStruct(value, data, tag) - case "list": - return unmarshalList(value, data, tag) - case "map": - return unmarshalMap(value, data, tag) - default: - return unmarshalScalar(value, data, tag) - } -} - -func unmarshalStruct(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a structure (%#v)", data) - } - - t := value.Type() - if value.Kind() == reflect.Ptr { - if value.IsNil() { // create the structure if it's nil - s := reflect.New(value.Type().Elem()) - value.Set(s) - value = s - } - - value = value.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return unmarshalAny(value.FieldByName(payload), data, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if field.PkgPath != "" { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - member := value.FieldByIndex(field.Index) - err := unmarshalAny(member, mapData[name], field.Tag) - if err != nil { - return err - } - } - return nil -} - -func unmarshalList(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - listData, ok := data.([]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a list (%#v)", data) - } - - if value.IsNil() { - l := len(listData) - value.Set(reflect.MakeSlice(value.Type(), l, l)) - } - - for i, c := range listData { - err := unmarshalAny(value.Index(i), c, "") - if err != nil { - return err - } - } - - return nil -} - -func unmarshalMap(value reflect.Value, data interface{}, tag reflect.StructTag) error { - if data == nil { - return nil - } - mapData, ok := data.(map[string]interface{}) - if !ok { - return fmt.Errorf("JSON value is not a map (%#v)", data) - } - - if value.IsNil() { - value.Set(reflect.MakeMap(value.Type())) - } - - for k, v := range mapData { - kvalue := reflect.ValueOf(k) - vvalue := reflect.New(value.Type().Elem()).Elem() - - unmarshalAny(vvalue, v, "") - value.SetMapIndex(kvalue, vvalue) - } - - return nil -} - -func unmarshalScalar(value reflect.Value, data interface{}, tag reflect.StructTag) error { - errf := func() error { - return fmt.Errorf("unsupported value: %v (%s)", value.Interface(), value.Type()) - } - - switch d := data.(type) { - case nil: - return nil // nothing to do here - case string: - switch value.Interface().(type) { - case *string: - value.Set(reflect.ValueOf(&d)) - case []byte: - b, err := base64.StdEncoding.DecodeString(d) - if err != nil { - return err - } - value.Set(reflect.ValueOf(b)) - case aws.JSONValue: - // No need to use escaping as the value is a non-quoted string. - v, err := protocol.DecodeJSONValue(d, protocol.NoEscape) - if err != nil { - return err - } - value.Set(reflect.ValueOf(v)) - default: - return errf() - } - case float64: - switch value.Interface().(type) { - case *int64: - di := int64(d) - value.Set(reflect.ValueOf(&di)) - case *float64: - value.Set(reflect.ValueOf(&d)) - case *time.Time: - t := time.Unix(int64(d), 0).UTC() - value.Set(reflect.ValueOf(&t)) - default: - return errf() - } - case bool: - switch value.Interface().(type) { - case *bool: - value.Set(reflect.ValueOf(&d)) - default: - return errf() - } - default: - return fmt.Errorf("unsupported JSON value (%v)", data) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go deleted file mode 100644 index 56af4dc44..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonrpc/jsonrpc.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package jsonrpc provides JSON RPC utilities for serialization of AWS -// requests and responses. -package jsonrpc - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/json.json build_test.go -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/json.json unmarshal_test.go - -import ( - "encoding/json" - "io/ioutil" - "strings" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/json/jsonutil" - "github.com/aws/aws-sdk-go/private/protocol/rest" -) - -var emptyJSON = []byte("{}") - -// BuildHandler is a named request handler for building jsonrpc protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Build", Fn: Build} - -// UnmarshalHandler is a named request handler for unmarshaling jsonrpc protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.jsonrpc.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling jsonrpc protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalMeta", Fn: UnmarshalMeta} - -// UnmarshalErrorHandler is a named request handler for unmarshaling jsonrpc protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.jsonrpc.UnmarshalError", Fn: UnmarshalError} - -// Build builds a JSON payload for a JSON RPC request. -func Build(req *request.Request) { - var buf []byte - var err error - if req.ParamsFilled() { - buf, err = jsonutil.BuildJSON(req.Params) - if err != nil { - req.Error = awserr.New("SerializationError", "failed encoding JSON RPC request", err) - return - } - } else { - buf = emptyJSON - } - - if req.ClientInfo.TargetPrefix != "" || string(buf) != "{}" { - req.SetBufferBody(buf) - } - - if req.ClientInfo.TargetPrefix != "" { - target := req.ClientInfo.TargetPrefix + "." + req.Operation.Name - req.HTTPRequest.Header.Add("X-Amz-Target", target) - } - if req.ClientInfo.JSONVersion != "" { - jsonVersion := req.ClientInfo.JSONVersion - req.HTTPRequest.Header.Add("Content-Type", "application/x-amz-json-"+jsonVersion) - } -} - -// Unmarshal unmarshals a response for a JSON RPC service. -func Unmarshal(req *request.Request) { - defer req.HTTPResponse.Body.Close() - if req.DataFilled() { - err := jsonutil.UnmarshalJSON(req.Data, req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("SerializationError", "failed decoding JSON RPC response", err) - } - } - return -} - -// UnmarshalMeta unmarshals headers from a response for a JSON RPC service. -func UnmarshalMeta(req *request.Request) { - rest.UnmarshalMeta(req) -} - -// UnmarshalError unmarshals an error response for a JSON RPC service. -func UnmarshalError(req *request.Request) { - defer req.HTTPResponse.Body.Close() - bodyBytes, err := ioutil.ReadAll(req.HTTPResponse.Body) - if err != nil { - req.Error = awserr.New("SerializationError", "failed reading JSON RPC error response", err) - return - } - if len(bodyBytes) == 0 { - req.Error = awserr.NewRequestFailure( - awserr.New("SerializationError", req.HTTPResponse.Status, nil), - req.HTTPResponse.StatusCode, - "", - ) - return - } - var jsonErr jsonErrorResponse - if err := json.Unmarshal(bodyBytes, &jsonErr); err != nil { - req.Error = awserr.New("SerializationError", "failed decoding JSON RPC error response", err) - return - } - - codes := strings.SplitN(jsonErr.Code, "#", 2) - req.Error = awserr.NewRequestFailure( - awserr.New(codes[len(codes)-1], jsonErr.Message, nil), - req.HTTPResponse.StatusCode, - req.RequestID, - ) -} - -type jsonErrorResponse struct { - Code string `json:"__type"` - Message string `json:"message"` -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go deleted file mode 100644 index 776d11018..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/jsonvalue.go +++ /dev/null @@ -1,76 +0,0 @@ -package protocol - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "strconv" - - "github.com/aws/aws-sdk-go/aws" -) - -// EscapeMode is the mode that should be use for escaping a value -type EscapeMode uint - -// The modes for escaping a value before it is marshaled, and unmarshaled. -const ( - NoEscape EscapeMode = iota - Base64Escape - QuotedEscape -) - -// EncodeJSONValue marshals the value into a JSON string, and optionally base64 -// encodes the string before returning it. -// -// Will panic if the escape mode is unknown. -func EncodeJSONValue(v aws.JSONValue, escape EscapeMode) (string, error) { - b, err := json.Marshal(v) - if err != nil { - return "", err - } - - switch escape { - case NoEscape: - return string(b), nil - case Base64Escape: - return base64.StdEncoding.EncodeToString(b), nil - case QuotedEscape: - return strconv.Quote(string(b)), nil - } - - panic(fmt.Sprintf("EncodeJSONValue called with unknown EscapeMode, %v", escape)) -} - -// DecodeJSONValue will attempt to decode the string input as a JSONValue. -// Optionally decoding base64 the value first before JSON unmarshaling. -// -// Will panic if the escape mode is unknown. -func DecodeJSONValue(v string, escape EscapeMode) (aws.JSONValue, error) { - var b []byte - var err error - - switch escape { - case NoEscape: - b = []byte(v) - case Base64Escape: - b, err = base64.StdEncoding.DecodeString(v) - case QuotedEscape: - var u string - u, err = strconv.Unquote(v) - b = []byte(u) - default: - panic(fmt.Sprintf("DecodeJSONValue called with unknown EscapeMode, %v", escape)) - } - - if err != nil { - return nil, err - } - - m := aws.JSONValue{} - err = json.Unmarshal(b, &m) - if err != nil { - return nil, err - } - - return m, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go deleted file mode 100644 index 60e5b09d5..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/build.go +++ /dev/null @@ -1,36 +0,0 @@ -// Package query provides serialization of AWS query requests, and responses. -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/query.json build_test.go - -import ( - "net/url" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query/queryutil" -) - -// BuildHandler is a named request handler for building query protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.query.Build", Fn: Build} - -// Build builds a request for an AWS Query service. -func Build(r *request.Request) { - body := url.Values{ - "Action": {r.Operation.Name}, - "Version": {r.ClientInfo.APIVersion}, - } - if err := queryutil.Parse(body, r.Params, false); err != nil { - r.Error = awserr.New("SerializationError", "failed encoding Query request", err) - return - } - - if !r.IsPresigned() { - r.HTTPRequest.Method = "POST" - r.HTTPRequest.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8") - r.SetBufferBody([]byte(body.Encode())) - } else { // This is a pre-signed request - r.HTTPRequest.Method = "GET" - r.HTTPRequest.URL.RawQuery = body.Encode() - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go deleted file mode 100644 index 5ce9cba32..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/queryutil/queryutil.go +++ /dev/null @@ -1,241 +0,0 @@ -package queryutil - -import ( - "encoding/base64" - "fmt" - "net/url" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// Parse parses an object i and fills a url.Values object. The isEC2 flag -// indicates if this is the EC2 Query sub-protocol. -func Parse(body url.Values, i interface{}, isEC2 bool) error { - q := queryParser{isEC2: isEC2} - return q.parseValue(body, reflect.ValueOf(i), "", "") -} - -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -type queryParser struct { - isEC2 bool -} - -func (q *queryParser) parseValue(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - value = elemOf(value) - - // no need to handle zero values - if !value.IsValid() { - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - return q.parseStruct(v, value, prefix) - case "list": - return q.parseList(v, value, prefix, tag) - case "map": - return q.parseMap(v, value, prefix, tag) - default: - return q.parseScalar(v, value, prefix, tag) - } -} - -func (q *queryParser) parseStruct(v url.Values, value reflect.Value, prefix string) error { - if !value.IsValid() { - return nil - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - elemValue := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - elemValue = reflect.ValueOf(token) - } - - var name string - if q.isEC2 { - name = field.Tag.Get("queryName") - } - if name == "" { - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - if name != "" && q.isEC2 { - name = strings.ToUpper(name[0:1]) + name[1:] - } - } - if name == "" { - name = field.Name - } - - if prefix != "" { - name = prefix + "." + name - } - - if err := q.parseValue(v, elemValue, name, field.Tag); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseList(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - if _, ok := value.Interface().([]byte); ok { - return q.parseScalar(v, value, prefix, tag) - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - if listName := tag.Get("locationNameList"); listName == "" { - prefix += ".member" - } else { - prefix += "." + listName - } - } - - for i := 0; i < value.Len(); i++ { - slicePrefix := prefix - if slicePrefix == "" { - slicePrefix = strconv.Itoa(i + 1) - } else { - slicePrefix = slicePrefix + "." + strconv.Itoa(i+1) - } - if err := q.parseValue(v, value.Index(i), slicePrefix, ""); err != nil { - return err - } - } - return nil -} - -func (q *queryParser) parseMap(v url.Values, value reflect.Value, prefix string, tag reflect.StructTag) error { - // If it's empty, generate an empty value - if !value.IsNil() && value.Len() == 0 { - v.Set(prefix, "") - return nil - } - - // check for unflattened list member - if !q.isEC2 && tag.Get("flattened") == "" { - prefix += ".entry" - } - - // sort keys for improved serialization consistency. - // this is not strictly necessary for protocol support. - mapKeyValues := value.MapKeys() - mapKeys := map[string]reflect.Value{} - mapKeyNames := make([]string, len(mapKeyValues)) - for i, mapKey := range mapKeyValues { - name := mapKey.String() - mapKeys[name] = mapKey - mapKeyNames[i] = name - } - sort.Strings(mapKeyNames) - - for i, mapKeyName := range mapKeyNames { - mapKey := mapKeys[mapKeyName] - mapValue := value.MapIndex(mapKey) - - kname := tag.Get("locationNameKey") - if kname == "" { - kname = "key" - } - vname := tag.Get("locationNameValue") - if vname == "" { - vname = "value" - } - - // serialize key - var keyName string - if prefix == "" { - keyName = strconv.Itoa(i+1) + "." + kname - } else { - keyName = prefix + "." + strconv.Itoa(i+1) + "." + kname - } - - if err := q.parseValue(v, mapKey, keyName, ""); err != nil { - return err - } - - // serialize value - var valueName string - if prefix == "" { - valueName = strconv.Itoa(i+1) + "." + vname - } else { - valueName = prefix + "." + strconv.Itoa(i+1) + "." + vname - } - - if err := q.parseValue(v, mapValue, valueName, ""); err != nil { - return err - } - } - - return nil -} - -func (q *queryParser) parseScalar(v url.Values, r reflect.Value, name string, tag reflect.StructTag) error { - switch value := r.Interface().(type) { - case string: - v.Set(name, value) - case []byte: - if !r.IsNil() { - v.Set(name, base64.StdEncoding.EncodeToString(value)) - } - case bool: - v.Set(name, strconv.FormatBool(value)) - case int64: - v.Set(name, strconv.FormatInt(value, 10)) - case int: - v.Set(name, strconv.Itoa(value)) - case float64: - v.Set(name, strconv.FormatFloat(value, 'f', -1, 64)) - case float32: - v.Set(name, strconv.FormatFloat(float64(value), 'f', -1, 32)) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - v.Set(name, value.UTC().Format(ISO8601UTC)) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", name, r.Interface(), r.Type().Name()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go deleted file mode 100644 index e0f4d5a54..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal.go +++ /dev/null @@ -1,35 +0,0 @@ -package query - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/query.json unmarshal_test.go - -import ( - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// UnmarshalHandler is a named request handler for unmarshaling query protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.query.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling query protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals a response for an AWS Query service. -func Unmarshal(r *request.Request) { - defer r.HTTPResponse.Body.Close() - if r.DataFilled() { - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, r.Operation.Name+"Result") - if err != nil { - r.Error = awserr.New("SerializationError", "failed decoding Query response", err) - return - } - } -} - -// UnmarshalMeta unmarshals header response values for an AWS Query service. -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go deleted file mode 100644 index f21429617..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/query/unmarshal_error.go +++ /dev/null @@ -1,66 +0,0 @@ -package query - -import ( - "encoding/xml" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" -) - -type xmlErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type xmlServiceUnavailableResponse struct { - XMLName xml.Name `xml:"ServiceUnavailableException"` -} - -// UnmarshalErrorHandler is a name request handler to unmarshal request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.query.UnmarshalError", Fn: UnmarshalError} - -// UnmarshalError unmarshals an error response for an AWS Query service. -func UnmarshalError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - bodyBytes, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to read from query HTTP response body", err) - return - } - - // First check for specific error - resp := xmlErrorResponse{} - decodeErr := xml.Unmarshal(bodyBytes, &resp) - if decodeErr == nil { - reqID := resp.RequestID - if reqID == "" { - reqID = r.RequestID - } - r.Error = awserr.NewRequestFailure( - awserr.New(resp.Code, resp.Message, nil), - r.HTTPResponse.StatusCode, - reqID, - ) - return - } - - // Check for unhandled error - servUnavailResp := xmlServiceUnavailableResponse{} - unavailErr := xml.Unmarshal(bodyBytes, &servUnavailResp) - if unavailErr == nil { - r.Error = awserr.NewRequestFailure( - awserr.New("ServiceUnavailableException", "service is unavailable", nil), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - return - } - - // Failed to retrieve any error message from the response body - r.Error = awserr.New("SerializationError", - "failed to decode query XML error response", decodeErr) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go deleted file mode 100644 index c405288d7..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/build.go +++ /dev/null @@ -1,291 +0,0 @@ -// Package rest provides RESTful serialization of AWS requests and responses. -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "net/http" - "net/url" - "path" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// RFC822 returns an RFC822 formatted timestamp for AWS protocols -const RFC822 = "Mon, 2 Jan 2006 15:04:05 GMT" - -// Whether the byte value can be sent without escaping in AWS URLs -var noEscape [256]bool - -var errValueNotSet = fmt.Errorf("value not set") - -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 == '~' - } -} - -// BuildHandler is a named request handler for building rest protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.rest.Build", Fn: Build} - -// Build builds the REST component of a service request. -func Build(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, false) - buildBody(r, v) - } -} - -// BuildAsGET builds the REST component of a service request with the ability to hoist -// data from the body. -func BuildAsGET(r *request.Request) { - if r.ParamsFilled() { - v := reflect.ValueOf(r.Params).Elem() - buildLocationElements(r, v, true) - buildBody(r, v) - } -} - -func buildLocationElements(r *request.Request, v reflect.Value, buildGETQuery bool) { - query := r.HTTPRequest.URL.Query() - - // Setup the raw path to match the base path pattern. This is needed - // so that when the path is mutated a custom escaped version can be - // stored in RawPath that will be used by the Go client. - r.HTTPRequest.URL.RawPath = r.HTTPRequest.URL.Path - - for i := 0; i < v.NumField(); i++ { - m := v.Field(i) - if n := v.Type().Field(i).Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - field := v.Type().Field(i) - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - if kind := m.Kind(); kind == reflect.Ptr { - m = m.Elem() - } else if kind == reflect.Interface { - if !m.Elem().IsValid() { - continue - } - } - if !m.IsValid() { - continue - } - if field.Tag.Get("ignore") != "" { - continue - } - - var err error - switch field.Tag.Get("location") { - case "headers": // header maps - err = buildHeaderMap(&r.HTTPRequest.Header, m, field.Tag) - case "header": - err = buildHeader(&r.HTTPRequest.Header, m, name, field.Tag) - case "uri": - err = buildURI(r.HTTPRequest.URL, m, name, field.Tag) - case "querystring": - err = buildQueryString(query, m, name, field.Tag) - default: - if buildGETQuery { - err = buildQueryString(query, m, name, field.Tag) - } - } - r.Error = err - } - if r.Error != nil { - return - } - } - - r.HTTPRequest.URL.RawQuery = query.Encode() - if !aws.BoolValue(r.Config.DisableRestProtocolURICleaning) { - cleanPath(r.HTTPRequest.URL) - } -} - -func buildBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := reflect.Indirect(v.FieldByName(payloadName)) - if payload.IsValid() && payload.Interface() != nil { - switch reader := payload.Interface().(type) { - case io.ReadSeeker: - r.SetReaderBody(reader) - case []byte: - r.SetBufferBody(reader) - case string: - r.SetStringBody(reader) - default: - r.Error = awserr.New("SerializationError", - "failed to encode REST request", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } -} - -func buildHeader(header *http.Header, v reflect.Value, name string, tag reflect.StructTag) error { - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - header.Add(name, str) - - return nil -} - -func buildHeaderMap(header *http.Header, v reflect.Value, tag reflect.StructTag) error { - prefix := tag.Get("locationName") - for _, key := range v.MapKeys() { - str, err := convertType(v.MapIndex(key), tag) - if err == errValueNotSet { - continue - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - - } - - header.Add(prefix+key.String(), str) - } - return nil -} - -func buildURI(u *url.URL, v reflect.Value, name string, tag reflect.StructTag) error { - value, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - - u.Path = strings.Replace(u.Path, "{"+name+"}", value, -1) - u.Path = strings.Replace(u.Path, "{"+name+"+}", value, -1) - - u.RawPath = strings.Replace(u.RawPath, "{"+name+"}", EscapePath(value, true), -1) - u.RawPath = strings.Replace(u.RawPath, "{"+name+"+}", EscapePath(value, false), -1) - - return nil -} - -func buildQueryString(query url.Values, v reflect.Value, name string, tag reflect.StructTag) error { - switch value := v.Interface().(type) { - case []*string: - for _, item := range value { - query.Add(name, *item) - } - case map[string]*string: - for key, item := range value { - query.Add(key, *item) - } - case map[string][]*string: - for key, items := range value { - for _, item := range items { - query.Add(key, *item) - } - } - default: - str, err := convertType(v, tag) - if err == errValueNotSet { - return nil - } else if err != nil { - return awserr.New("SerializationError", "failed to encode REST request", err) - } - query.Set(name, str) - } - - return nil -} - -func cleanPath(u *url.URL) { - hasSlash := strings.HasSuffix(u.Path, "/") - - // clean up path, removing duplicate `/` - u.Path = path.Clean(u.Path) - u.RawPath = path.Clean(u.RawPath) - - if hasSlash && !strings.HasSuffix(u.Path, "/") { - u.Path += "/" - u.RawPath += "/" - } -} - -// 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() -} - -func convertType(v reflect.Value, tag reflect.StructTag) (str string, err error) { - v = reflect.Indirect(v) - if !v.IsValid() { - return "", errValueNotSet - } - - switch value := v.Interface().(type) { - case string: - str = value - case []byte: - str = base64.StdEncoding.EncodeToString(value) - case bool: - str = strconv.FormatBool(value) - case int64: - str = strconv.FormatInt(value, 10) - case float64: - str = strconv.FormatFloat(value, 'f', -1, 64) - case time.Time: - str = value.UTC().Format(RFC822) - case aws.JSONValue: - if len(value) == 0 { - return "", errValueNotSet - } - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - str, err = protocol.EncodeJSONValue(value, escaping) - if err != nil { - return "", fmt.Errorf("unable to encode JSONValue, %v", err) - } - default: - err := fmt.Errorf("unsupported value for param %v (%s)", v.Interface(), v.Type()) - return "", err - } - return str, nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go deleted file mode 100644 index 4366de2e1..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/payload.go +++ /dev/null @@ -1,45 +0,0 @@ -package rest - -import "reflect" - -// PayloadMember returns the payload field member of i if there is one, or nil. -func PayloadMember(i interface{}) interface{} { - if i == nil { - return nil - } - - v := reflect.ValueOf(i).Elem() - if !v.IsValid() { - return nil - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - field, _ := v.Type().FieldByName(payloadName) - if field.Tag.Get("type") != "structure" { - return nil - } - - payload := v.FieldByName(payloadName) - if payload.IsValid() || (payload.Kind() == reflect.Ptr && !payload.IsNil()) { - return payload.Interface() - } - } - } - return nil -} - -// PayloadType returns the type of a payload field member of i if there is one, or "". -func PayloadType(i interface{}) string { - v := reflect.Indirect(reflect.ValueOf(i)) - if !v.IsValid() { - return "" - } - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - if member, ok := v.Type().FieldByName(payloadName); ok { - return member.Tag.Get("type") - } - } - } - return "" -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go deleted file mode 100644 index 823f045ee..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/rest/unmarshal.go +++ /dev/null @@ -1,221 +0,0 @@ -package rest - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "io/ioutil" - "net/http" - "reflect" - "strconv" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol" -) - -// UnmarshalHandler is a named request handler for unmarshaling rest protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.rest.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling rest protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.rest.UnmarshalMeta", Fn: UnmarshalMeta} - -// Unmarshal unmarshals the REST component of a response in a REST service. -func Unmarshal(r *request.Request) { - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalBody(r, v) - } -} - -// UnmarshalMeta unmarshals the REST metadata of a response in a REST service -func UnmarshalMeta(r *request.Request) { - r.RequestID = r.HTTPResponse.Header.Get("X-Amzn-Requestid") - if r.RequestID == "" { - // Alternative version of request id in the header - r.RequestID = r.HTTPResponse.Header.Get("X-Amz-Request-Id") - } - if r.DataFilled() { - v := reflect.Indirect(reflect.ValueOf(r.Data)) - unmarshalLocationElements(r, v) - } -} - -func unmarshalBody(r *request.Request, v reflect.Value) { - if field, ok := v.Type().FieldByName("_"); ok { - if payloadName := field.Tag.Get("payload"); payloadName != "" { - pfield, _ := v.Type().FieldByName(payloadName) - if ptag := pfield.Tag.Get("type"); ptag != "" && ptag != "structure" { - payload := v.FieldByName(payloadName) - if payload.IsValid() { - switch payload.Interface().(type) { - case []byte: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - payload.Set(reflect.ValueOf(b)) - } - case *string: - defer r.HTTPResponse.Body.Close() - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - } else { - str := string(b) - payload.Set(reflect.ValueOf(&str)) - } - default: - switch payload.Type().String() { - case "io.ReadCloser": - payload.Set(reflect.ValueOf(r.HTTPResponse.Body)) - case "io.ReadSeeker": - b, err := ioutil.ReadAll(r.HTTPResponse.Body) - if err != nil { - r.Error = awserr.New("SerializationError", - "failed to read response body", err) - return - } - payload.Set(reflect.ValueOf(ioutil.NopCloser(bytes.NewReader(b)))) - default: - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - defer r.HTTPResponse.Body.Close() - r.Error = awserr.New("SerializationError", - "failed to decode REST response", - fmt.Errorf("unknown payload type %s", payload.Type())) - } - } - } - } - } - } -} - -func unmarshalLocationElements(r *request.Request, v reflect.Value) { - for i := 0; i < v.NumField(); i++ { - m, field := v.Field(i), v.Type().Field(i) - if n := field.Name; n[0:1] == strings.ToLower(n[0:1]) { - continue - } - - if m.IsValid() { - name := field.Tag.Get("locationName") - if name == "" { - name = field.Name - } - - switch field.Tag.Get("location") { - case "statusCode": - unmarshalStatusCode(m, r.HTTPResponse.StatusCode) - case "header": - err := unmarshalHeader(m, r.HTTPResponse.Header.Get(name), field.Tag) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - case "headers": - prefix := field.Tag.Get("locationName") - err := unmarshalHeaderMap(m, r.HTTPResponse.Header, prefix) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST response", err) - break - } - } - } - if r.Error != nil { - return - } - } -} - -func unmarshalStatusCode(v reflect.Value, statusCode int) { - if !v.IsValid() { - return - } - - switch v.Interface().(type) { - case *int64: - s := int64(statusCode) - v.Set(reflect.ValueOf(&s)) - } -} - -func unmarshalHeaderMap(r reflect.Value, headers http.Header, prefix string) error { - switch r.Interface().(type) { - case map[string]*string: // we only support string map value types - out := map[string]*string{} - for k, v := range headers { - k = http.CanonicalHeaderKey(k) - if strings.HasPrefix(strings.ToLower(k), strings.ToLower(prefix)) { - out[k[len(prefix):]] = &v[0] - } - } - r.Set(reflect.ValueOf(out)) - } - return nil -} - -func unmarshalHeader(v reflect.Value, header string, tag reflect.StructTag) error { - isJSONValue := tag.Get("type") == "jsonvalue" - if isJSONValue { - if len(header) == 0 { - return nil - } - } else if !v.IsValid() || (header == "" && v.Elem().Kind() != reflect.String) { - return nil - } - - switch v.Interface().(type) { - case *string: - v.Set(reflect.ValueOf(&header)) - case []byte: - b, err := base64.StdEncoding.DecodeString(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *bool: - b, err := strconv.ParseBool(header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&b)) - case *int64: - i, err := strconv.ParseInt(header, 10, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&i)) - case *float64: - f, err := strconv.ParseFloat(header, 64) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&f)) - case *time.Time: - t, err := time.Parse(RFC822, header) - if err != nil { - return err - } - v.Set(reflect.ValueOf(&t)) - case aws.JSONValue: - escaping := protocol.NoEscape - if tag.Get("location") == "header" { - escaping = protocol.Base64Escape - } - m, err := protocol.DecodeJSONValue(header, escaping) - if err != nil { - return err - } - v.Set(reflect.ValueOf(m)) - default: - err := fmt.Errorf("Unsupported value for param %v (%s)", v.Interface(), v.Type()) - return err - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go deleted file mode 100644 index 7bdf4c853..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/restxml/restxml.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package restxml provides RESTful XML serialization of AWS -// requests and responses. -package restxml - -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/input/rest-xml.json build_test.go -//go:generate go run -tags codegen ../../../models/protocol_tests/generate.go ../../../models/protocol_tests/output/rest-xml.json unmarshal_test.go - -import ( - "bytes" - "encoding/xml" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/query" - "github.com/aws/aws-sdk-go/private/protocol/rest" - "github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil" -) - -// BuildHandler is a named request handler for building restxml protocol requests -var BuildHandler = request.NamedHandler{Name: "awssdk.restxml.Build", Fn: Build} - -// UnmarshalHandler is a named request handler for unmarshaling restxml protocol requests -var UnmarshalHandler = request.NamedHandler{Name: "awssdk.restxml.Unmarshal", Fn: Unmarshal} - -// UnmarshalMetaHandler is a named request handler for unmarshaling restxml protocol request metadata -var UnmarshalMetaHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalMeta", Fn: UnmarshalMeta} - -// UnmarshalErrorHandler is a named request handler for unmarshaling restxml protocol request errors -var UnmarshalErrorHandler = request.NamedHandler{Name: "awssdk.restxml.UnmarshalError", Fn: UnmarshalError} - -// Build builds a request payload for the REST XML protocol. -func Build(r *request.Request) { - rest.Build(r) - - if t := rest.PayloadType(r.Params); t == "structure" || t == "" { - var buf bytes.Buffer - err := xmlutil.BuildXML(r.Params, xml.NewEncoder(&buf)) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to encode rest XML request", err) - return - } - r.SetBufferBody(buf.Bytes()) - } -} - -// Unmarshal unmarshals a payload response for the REST XML protocol. -func Unmarshal(r *request.Request) { - if t := rest.PayloadType(r.Data); t == "structure" || t == "" { - defer r.HTTPResponse.Body.Close() - decoder := xml.NewDecoder(r.HTTPResponse.Body) - err := xmlutil.UnmarshalXML(r.Data, decoder, "") - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode REST XML response", err) - return - } - } else { - rest.Unmarshal(r) - } -} - -// UnmarshalMeta unmarshals response headers for the REST XML protocol. -func UnmarshalMeta(r *request.Request) { - rest.UnmarshalMeta(r) -} - -// UnmarshalError unmarshals a response error for the REST XML protocol. -func UnmarshalError(r *request.Request) { - query.UnmarshalError(r) -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go deleted file mode 100644 index da1a68111..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/unmarshal.go +++ /dev/null @@ -1,21 +0,0 @@ -package protocol - -import ( - "io" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/request" -) - -// UnmarshalDiscardBodyHandler is a named request handler to empty and close a response's body -var UnmarshalDiscardBodyHandler = request.NamedHandler{Name: "awssdk.shared.UnmarshalDiscardBody", Fn: UnmarshalDiscardBody} - -// UnmarshalDiscardBody is a request handler to empty a response's body and closing it. -func UnmarshalDiscardBody(r *request.Request) { - if r.HTTPResponse == nil || r.HTTPResponse.Body == nil { - return - } - - io.Copy(ioutil.Discard, r.HTTPResponse.Body) - r.HTTPResponse.Body.Close() -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go deleted file mode 100644 index 7091b456d..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/build.go +++ /dev/null @@ -1,296 +0,0 @@ -// Package xmlutil provides XML serialization of AWS requests and responses. -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "reflect" - "sort" - "strconv" - "time" - - "github.com/aws/aws-sdk-go/private/protocol" -) - -// BuildXML will serialize params into an xml.Encoder. -// Error will be returned if the serialization of any of the params or nested values fails. -func BuildXML(params interface{}, e *xml.Encoder) error { - b := xmlBuilder{encoder: e, namespaces: map[string]string{}} - root := NewXMLElement(xml.Name{}) - if err := b.buildValue(reflect.ValueOf(params), root, ""); err != nil { - return err - } - for _, c := range root.Children { - for _, v := range c { - return StructToXML(e, v, false) - } - } - return nil -} - -// Returns the reflection element of a value, if it is a pointer. -func elemOf(value reflect.Value) reflect.Value { - for value.Kind() == reflect.Ptr { - value = value.Elem() - } - return value -} - -// A xmlBuilder serializes values from Go code to XML -type xmlBuilder struct { - encoder *xml.Encoder - namespaces map[string]string -} - -// buildValue generic XMLNode builder for any type. Will build value for their specific type -// struct, list, map, scalar. -// -// Also takes a "type" tag value to set what type a value should be converted to XMLNode as. If -// type is not provided reflect will be used to determine the value's type. -func (b *xmlBuilder) buildValue(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - value = elemOf(value) - if !value.IsValid() { // no need to handle zero values - return nil - } else if tag.Get("location") != "" { // don't handle non-body location values - return nil - } - - t := tag.Get("type") - if t == "" { - switch value.Kind() { - case reflect.Struct: - t = "structure" - case reflect.Slice: - t = "list" - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := value.Type().FieldByName("_"); ok { - tag = tag + reflect.StructTag(" ") + field.Tag - } - return b.buildStruct(value, current, tag) - case "list": - return b.buildList(value, current, tag) - case "map": - return b.buildMap(value, current, tag) - default: - return b.buildScalar(value, current, tag) - } -} - -// buildStruct adds a struct and its fields to the current XMLNode. All fields any any nested -// types are converted to XMLNodes also. -func (b *xmlBuilder) buildStruct(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if !value.IsValid() { - return nil - } - - fieldAdded := false - - // unwrap payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := value.Type().FieldByName(payload) - tag = field.Tag - value = elemOf(value.FieldByName(payload)) - - if !value.IsValid() { - return nil - } - } - - child := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - - // there is an xmlNamespace associated with this struct - if prefix, uri := tag.Get("xmlPrefix"), tag.Get("xmlURI"); uri != "" { - ns := xml.Attr{ - Name: xml.Name{Local: "xmlns"}, - Value: uri, - } - if prefix != "" { - b.namespaces[prefix] = uri // register the namespace - ns.Name.Local = "xmlns:" + prefix - } - - child.Attr = append(child.Attr, ns) - } - - t := value.Type() - for i := 0; i < value.NumField(); i++ { - member := elemOf(value.Field(i)) - field := t.Field(i) - - if field.PkgPath != "" { - continue // ignore unexported fields - } - if field.Tag.Get("ignore") != "" { - continue - } - - mTag := field.Tag - if mTag.Get("location") != "" { // skip non-body members - continue - } - - if protocol.CanSetIdempotencyToken(value.Field(i), field) { - token := protocol.GetIdempotencyToken() - member = reflect.ValueOf(token) - } - - memberName := mTag.Get("locationName") - if memberName == "" { - memberName = field.Name - mTag = reflect.StructTag(string(mTag) + ` locationName:"` + memberName + `"`) - } - if err := b.buildValue(member, child, mTag); err != nil { - return err - } - - fieldAdded = true - } - - if fieldAdded { // only append this child if we have one ore more valid members - current.AddChild(child) - } - - return nil -} - -// buildList adds the value's list items to the current XMLNode as children nodes. All -// nested values in the list are converted to XMLNodes also. -func (b *xmlBuilder) buildList(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted lists - return nil - } - - // check for unflattened list member - flattened := tag.Get("flattened") != "" - - xname := xml.Name{Local: tag.Get("locationName")} - if flattened { - for i := 0; i < value.Len(); i++ { - child := NewXMLElement(xname) - current.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } else { - list := NewXMLElement(xname) - current.AddChild(list) - - for i := 0; i < value.Len(); i++ { - iname := tag.Get("locationNameList") - if iname == "" { - iname = "member" - } - - child := NewXMLElement(xml.Name{Local: iname}) - list.AddChild(child) - if err := b.buildValue(value.Index(i), child, ""); err != nil { - return err - } - } - } - - return nil -} - -// buildMap adds the value's key/value pairs to the current XMLNode as children nodes. All -// nested values in the map are converted to XMLNodes also. -// -// Error will be returned if it is unable to build the map's values into XMLNodes -func (b *xmlBuilder) buildMap(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - if value.IsNil() { // don't build omitted maps - return nil - } - - maproot := NewXMLElement(xml.Name{Local: tag.Get("locationName")}) - current.AddChild(maproot) - current = maproot - - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - // sorting is not required for compliance, but it makes testing easier - keys := make([]string, value.Len()) - for i, k := range value.MapKeys() { - keys[i] = k.String() - } - sort.Strings(keys) - - for _, k := range keys { - v := value.MapIndex(reflect.ValueOf(k)) - - mapcur := current - if tag.Get("flattened") == "" { // add "entry" tag to non-flat maps - child := NewXMLElement(xml.Name{Local: "entry"}) - mapcur.AddChild(child) - mapcur = child - } - - kchild := NewXMLElement(xml.Name{Local: kname}) - kchild.Text = k - vchild := NewXMLElement(xml.Name{Local: vname}) - mapcur.AddChild(kchild) - mapcur.AddChild(vchild) - - if err := b.buildValue(v, vchild, ""); err != nil { - return err - } - } - - return nil -} - -// buildScalar will convert the value into a string and append it as a attribute or child -// of the current XMLNode. -// -// The value will be added as an attribute if tag contains a "xmlAttribute" attribute value. -// -// Error will be returned if the value type is unsupported. -func (b *xmlBuilder) buildScalar(value reflect.Value, current *XMLNode, tag reflect.StructTag) error { - var str string - switch converted := value.Interface().(type) { - case string: - str = converted - case []byte: - if !value.IsNil() { - str = base64.StdEncoding.EncodeToString(converted) - } - case bool: - str = strconv.FormatBool(converted) - case int64: - str = strconv.FormatInt(converted, 10) - case int: - str = strconv.Itoa(converted) - case float64: - str = strconv.FormatFloat(converted, 'f', -1, 64) - case float32: - str = strconv.FormatFloat(float64(converted), 'f', -1, 32) - case time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - str = converted.UTC().Format(ISO8601UTC) - default: - return fmt.Errorf("unsupported value for param %s: %v (%s)", - tag.Get("locationName"), value.Interface(), value.Type().Name()) - } - - xname := xml.Name{Local: tag.Get("locationName")} - if tag.Get("xmlAttribute") != "" { // put into current node's attribute list - attr := xml.Attr{Name: xname, Value: str} - current.Attr = append(current.Attr, attr) - } else { // regular text node - current.AddChild(&XMLNode{Name: xname, Text: str}) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go deleted file mode 100644 index a6c25ba37..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/unmarshal.go +++ /dev/null @@ -1,266 +0,0 @@ -package xmlutil - -import ( - "encoding/base64" - "encoding/xml" - "fmt" - "io" - "reflect" - "strconv" - "strings" - "time" -) - -// UnmarshalXML deserializes an xml.Decoder into the container v. V -// needs to match the shape of the XML expected to be decoded. -// If the shape doesn't match unmarshaling will fail. -func UnmarshalXML(v interface{}, d *xml.Decoder, wrapper string) error { - n, err := XMLToStruct(d, nil) - if err != nil { - return err - } - if n.Children != nil { - for _, root := range n.Children { - for _, c := range root { - if wrappedChild, ok := c.Children[wrapper]; ok { - c = wrappedChild[0] // pull out wrapped element - } - - err = parse(reflect.ValueOf(v), c, "") - if err != nil { - if err == io.EOF { - return nil - } - return err - } - } - } - return nil - } - return nil -} - -// parse deserializes any value from the XMLNode. The type tag is used to infer the type, or reflect -// will be used to determine the type from r. -func parse(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - rtype := r.Type() - if rtype.Kind() == reflect.Ptr { - rtype = rtype.Elem() // check kind of actual element type - } - - t := tag.Get("type") - if t == "" { - switch rtype.Kind() { - case reflect.Struct: - // also it can't be a time object - if _, ok := r.Interface().(*time.Time); !ok { - t = "structure" - } - case reflect.Slice: - // also it can't be a byte slice - if _, ok := r.Interface().([]byte); !ok { - t = "list" - } - case reflect.Map: - t = "map" - } - } - - switch t { - case "structure": - if field, ok := rtype.FieldByName("_"); ok { - tag = field.Tag - } - return parseStruct(r, node, tag) - case "list": - return parseList(r, node, tag) - case "map": - return parseMap(r, node, tag) - default: - return parseScalar(r, node, tag) - } -} - -// parseStruct deserializes a structure and its fields from an XMLNode. Any nested -// types in the structure will also be deserialized. -func parseStruct(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - if r.Kind() == reflect.Ptr { - if r.IsNil() { // create the structure if it's nil - s := reflect.New(r.Type().Elem()) - r.Set(s) - r = s - } - - r = r.Elem() - t = t.Elem() - } - - // unwrap any payloads - if payload := tag.Get("payload"); payload != "" { - field, _ := t.FieldByName(payload) - return parseStruct(r.FieldByName(payload), node, field.Tag) - } - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - if c := field.Name[0:1]; strings.ToLower(c) == c { - continue // ignore unexported fields - } - - // figure out what this field is called - name := field.Name - if field.Tag.Get("flattened") != "" && field.Tag.Get("locationNameList") != "" { - name = field.Tag.Get("locationNameList") - } else if locName := field.Tag.Get("locationName"); locName != "" { - name = locName - } - - // try to find the field by name in elements - elems := node.Children[name] - - if elems == nil { // try to find the field in attributes - if val, ok := node.findElem(name); ok { - elems = []*XMLNode{{Text: val}} - } - } - - member := r.FieldByName(field.Name) - for _, elem := range elems { - err := parse(member, elem, field.Tag) - if err != nil { - return err - } - } - } - return nil -} - -// parseList deserializes a list of values from an XML node. Each list entry -// will also be deserialized. -func parseList(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - t := r.Type() - - if tag.Get("flattened") == "" { // look at all item entries - mname := "member" - if name := tag.Get("locationNameList"); name != "" { - mname = name - } - - if Children, ok := node.Children[mname]; ok { - if r.IsNil() { - r.Set(reflect.MakeSlice(t, len(Children), len(Children))) - } - - for i, c := range Children { - err := parse(r.Index(i), c, "") - if err != nil { - return err - } - } - } - } else { // flattened list means this is a single element - if r.IsNil() { - r.Set(reflect.MakeSlice(t, 0, 0)) - } - - childR := reflect.Zero(t.Elem()) - r.Set(reflect.Append(r, childR)) - err := parse(r.Index(r.Len()-1), node, "") - if err != nil { - return err - } - } - - return nil -} - -// parseMap deserializes a map from an XMLNode. The direct children of the XMLNode -// will also be deserialized as map entries. -func parseMap(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - if r.IsNil() { - r.Set(reflect.MakeMap(r.Type())) - } - - if tag.Get("flattened") == "" { // look at all child entries - for _, entry := range node.Children["entry"] { - parseMapEntry(r, entry, tag) - } - } else { // this element is itself an entry - parseMapEntry(r, node, tag) - } - - return nil -} - -// parseMapEntry deserializes a map entry from a XML node. -func parseMapEntry(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - kname, vname := "key", "value" - if n := tag.Get("locationNameKey"); n != "" { - kname = n - } - if n := tag.Get("locationNameValue"); n != "" { - vname = n - } - - keys, ok := node.Children[kname] - values := node.Children[vname] - if ok { - for i, key := range keys { - keyR := reflect.ValueOf(key.Text) - value := values[i] - valueR := reflect.New(r.Type().Elem()).Elem() - - parse(valueR, value, "") - r.SetMapIndex(keyR, valueR) - } - } - return nil -} - -// parseScaller deserializes an XMLNode value into a concrete type based on the -// interface type of r. -// -// Error is returned if the deserialization fails due to invalid type conversion, -// or unsupported interface type. -func parseScalar(r reflect.Value, node *XMLNode, tag reflect.StructTag) error { - switch r.Interface().(type) { - case *string: - r.Set(reflect.ValueOf(&node.Text)) - return nil - case []byte: - b, err := base64.StdEncoding.DecodeString(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(b)) - case *bool: - v, err := strconv.ParseBool(node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *int64: - v, err := strconv.ParseInt(node.Text, 10, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *float64: - v, err := strconv.ParseFloat(node.Text, 64) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&v)) - case *time.Time: - const ISO8601UTC = "2006-01-02T15:04:05Z" - t, err := time.Parse(ISO8601UTC, node.Text) - if err != nil { - return err - } - r.Set(reflect.ValueOf(&t)) - default: - return fmt.Errorf("unsupported value: %v (%s)", r.Interface(), r.Type()) - } - return nil -} diff --git a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go b/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go deleted file mode 100644 index 3e970b629..000000000 --- a/vendor/github.com/aws/aws-sdk-go/private/protocol/xml/xmlutil/xml_to_struct.go +++ /dev/null @@ -1,147 +0,0 @@ -package xmlutil - -import ( - "encoding/xml" - "fmt" - "io" - "sort" -) - -// A XMLNode contains the values to be encoded or decoded. -type XMLNode struct { - Name xml.Name `json:",omitempty"` - Children map[string][]*XMLNode `json:",omitempty"` - Text string `json:",omitempty"` - Attr []xml.Attr `json:",omitempty"` - - namespaces map[string]string - parent *XMLNode -} - -// NewXMLElement returns a pointer to a new XMLNode initialized to default values. -func NewXMLElement(name xml.Name) *XMLNode { - return &XMLNode{ - Name: name, - Children: map[string][]*XMLNode{}, - Attr: []xml.Attr{}, - } -} - -// AddChild adds child to the XMLNode. -func (n *XMLNode) AddChild(child *XMLNode) { - if _, ok := n.Children[child.Name.Local]; !ok { - n.Children[child.Name.Local] = []*XMLNode{} - } - n.Children[child.Name.Local] = append(n.Children[child.Name.Local], child) -} - -// XMLToStruct converts a xml.Decoder stream to XMLNode with nested values. -func XMLToStruct(d *xml.Decoder, s *xml.StartElement) (*XMLNode, error) { - out := &XMLNode{} - for { - tok, err := d.Token() - if err != nil { - if err == io.EOF { - break - } else { - return out, err - } - } - - if tok == nil { - break - } - - switch typed := tok.(type) { - case xml.CharData: - out.Text = string(typed.Copy()) - case xml.StartElement: - el := typed.Copy() - out.Attr = el.Attr - if out.Children == nil { - out.Children = map[string][]*XMLNode{} - } - - name := typed.Name.Local - slice := out.Children[name] - if slice == nil { - slice = []*XMLNode{} - } - node, e := XMLToStruct(d, &el) - out.findNamespaces() - if e != nil { - return out, e - } - node.Name = typed.Name - node.findNamespaces() - tempOut := *out - // Save into a temp variable, simply because out gets squashed during - // loop iterations - node.parent = &tempOut - slice = append(slice, node) - out.Children[name] = slice - case xml.EndElement: - if s != nil && s.Name.Local == typed.Name.Local { // matching end token - return out, nil - } - out = &XMLNode{} - } - } - return out, nil -} - -func (n *XMLNode) findNamespaces() { - ns := map[string]string{} - for _, a := range n.Attr { - if a.Name.Space == "xmlns" { - ns[a.Value] = a.Name.Local - } - } - - n.namespaces = ns -} - -func (n *XMLNode) findElem(name string) (string, bool) { - for node := n; node != nil; node = node.parent { - for _, a := range node.Attr { - namespace := a.Name.Space - if v, ok := node.namespaces[namespace]; ok { - namespace = v - } - if name == fmt.Sprintf("%s:%s", namespace, a.Name.Local) { - return a.Value, true - } - } - } - return "", false -} - -// StructToXML writes an XMLNode to a xml.Encoder as tokens. -func StructToXML(e *xml.Encoder, node *XMLNode, sorted bool) error { - e.EncodeToken(xml.StartElement{Name: node.Name, Attr: node.Attr}) - - if node.Text != "" { - e.EncodeToken(xml.CharData([]byte(node.Text))) - } else if sorted { - sortedNames := []string{} - for k := range node.Children { - sortedNames = append(sortedNames, k) - } - sort.Strings(sortedNames) - - for _, k := range sortedNames { - for _, v := range node.Children[k] { - StructToXML(e, v, sorted) - } - } - } else { - for _, c := range node.Children { - for _, v := range c { - StructToXML(e, v, sorted) - } - } - } - - e.EncodeToken(xml.EndElement{Name: node.Name}) - return e.Flush() -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go deleted file mode 100644 index 0feedda0a..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/api.go +++ /dev/null @@ -1,16202 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAllocateStaticIp = "AllocateStaticIp" - -// AllocateStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the AllocateStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AllocateStaticIp for more information on using the AllocateStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AllocateStaticIpRequest method. -// req, resp := client.AllocateStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIp -func (c *Lightsail) AllocateStaticIpRequest(input *AllocateStaticIpInput) (req *request.Request, output *AllocateStaticIpOutput) { - op := &request.Operation{ - Name: opAllocateStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AllocateStaticIpInput{} - } - - output = &AllocateStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// AllocateStaticIp API operation for Amazon Lightsail. -// -// Allocates a static IP address. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AllocateStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AllocateStaticIp -func (c *Lightsail) AllocateStaticIp(input *AllocateStaticIpInput) (*AllocateStaticIpOutput, error) { - req, out := c.AllocateStaticIpRequest(input) - return out, req.Send() -} - -// AllocateStaticIpWithContext is the same as AllocateStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See AllocateStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AllocateStaticIpWithContext(ctx aws.Context, input *AllocateStaticIpInput, opts ...request.Option) (*AllocateStaticIpOutput, error) { - req, out := c.AllocateStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachDisk = "AttachDisk" - -// AttachDiskRequest generates a "aws/request.Request" representing the -// client's request for the AttachDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachDisk for more information on using the AttachDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachDiskRequest method. -// req, resp := client.AttachDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachDisk -func (c *Lightsail) AttachDiskRequest(input *AttachDiskInput) (req *request.Request, output *AttachDiskOutput) { - op := &request.Operation{ - Name: opAttachDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachDiskInput{} - } - - output = &AttachDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachDisk API operation for Amazon Lightsail. -// -// Attaches a block storage disk to a running or stopped Lightsail instance -// and exposes it to the instance with the specified disk name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachDisk -func (c *Lightsail) AttachDisk(input *AttachDiskInput) (*AttachDiskOutput, error) { - req, out := c.AttachDiskRequest(input) - return out, req.Send() -} - -// AttachDiskWithContext is the same as AttachDisk with the addition of -// the ability to pass a context and additional request options. -// -// See AttachDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachDiskWithContext(ctx aws.Context, input *AttachDiskInput, opts ...request.Option) (*AttachDiskOutput, error) { - req, out := c.AttachDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachInstancesToLoadBalancer = "AttachInstancesToLoadBalancer" - -// AttachInstancesToLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the AttachInstancesToLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachInstancesToLoadBalancer for more information on using the AttachInstancesToLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachInstancesToLoadBalancerRequest method. -// req, resp := client.AttachInstancesToLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachInstancesToLoadBalancer -func (c *Lightsail) AttachInstancesToLoadBalancerRequest(input *AttachInstancesToLoadBalancerInput) (req *request.Request, output *AttachInstancesToLoadBalancerOutput) { - op := &request.Operation{ - Name: opAttachInstancesToLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachInstancesToLoadBalancerInput{} - } - - output = &AttachInstancesToLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachInstancesToLoadBalancer API operation for Amazon Lightsail. -// -// Attaches one or more Lightsail instances to a load balancer. -// -// After some time, the instances are attached to the load balancer and the -// health check status is available. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachInstancesToLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachInstancesToLoadBalancer -func (c *Lightsail) AttachInstancesToLoadBalancer(input *AttachInstancesToLoadBalancerInput) (*AttachInstancesToLoadBalancerOutput, error) { - req, out := c.AttachInstancesToLoadBalancerRequest(input) - return out, req.Send() -} - -// AttachInstancesToLoadBalancerWithContext is the same as AttachInstancesToLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See AttachInstancesToLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachInstancesToLoadBalancerWithContext(ctx aws.Context, input *AttachInstancesToLoadBalancerInput, opts ...request.Option) (*AttachInstancesToLoadBalancerOutput, error) { - req, out := c.AttachInstancesToLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachLoadBalancerTlsCertificate = "AttachLoadBalancerTlsCertificate" - -// AttachLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the AttachLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachLoadBalancerTlsCertificate for more information on using the AttachLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachLoadBalancerTlsCertificateRequest method. -// req, resp := client.AttachLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachLoadBalancerTlsCertificate -func (c *Lightsail) AttachLoadBalancerTlsCertificateRequest(input *AttachLoadBalancerTlsCertificateInput) (req *request.Request, output *AttachLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opAttachLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachLoadBalancerTlsCertificateInput{} - } - - output = &AttachLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Attaches a Transport Layer Security (TLS) certificate to your load balancer. -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// Once you create and validate your certificate, you can attach it to your -// load balancer. You can also use this API to rotate the certificates on your -// account. Use the AttachLoadBalancerTlsCertificate operation with the non-attached -// certificate, and it will replace the existing one and become the attached -// certificate. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachLoadBalancerTlsCertificate -func (c *Lightsail) AttachLoadBalancerTlsCertificate(input *AttachLoadBalancerTlsCertificateInput) (*AttachLoadBalancerTlsCertificateOutput, error) { - req, out := c.AttachLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// AttachLoadBalancerTlsCertificateWithContext is the same as AttachLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See AttachLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *AttachLoadBalancerTlsCertificateInput, opts ...request.Option) (*AttachLoadBalancerTlsCertificateOutput, error) { - req, out := c.AttachLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAttachStaticIp = "AttachStaticIp" - -// AttachStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the AttachStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AttachStaticIp for more information on using the AttachStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AttachStaticIpRequest method. -// req, resp := client.AttachStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachStaticIp -func (c *Lightsail) AttachStaticIpRequest(input *AttachStaticIpInput) (req *request.Request, output *AttachStaticIpOutput) { - op := &request.Operation{ - Name: opAttachStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AttachStaticIpInput{} - } - - output = &AttachStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// AttachStaticIp API operation for Amazon Lightsail. -// -// Attaches a static IP address to a specific Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation AttachStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/AttachStaticIp -func (c *Lightsail) AttachStaticIp(input *AttachStaticIpInput) (*AttachStaticIpOutput, error) { - req, out := c.AttachStaticIpRequest(input) - return out, req.Send() -} - -// AttachStaticIpWithContext is the same as AttachStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See AttachStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) AttachStaticIpWithContext(ctx aws.Context, input *AttachStaticIpInput, opts ...request.Option) (*AttachStaticIpOutput, error) { - req, out := c.AttachStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCloseInstancePublicPorts = "CloseInstancePublicPorts" - -// CloseInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the CloseInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CloseInstancePublicPorts for more information on using the CloseInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CloseInstancePublicPortsRequest method. -// req, resp := client.CloseInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloseInstancePublicPorts -func (c *Lightsail) CloseInstancePublicPortsRequest(input *CloseInstancePublicPortsInput) (req *request.Request, output *CloseInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opCloseInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CloseInstancePublicPortsInput{} - } - - output = &CloseInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// CloseInstancePublicPorts API operation for Amazon Lightsail. -// -// Closes the public ports on a specific Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CloseInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CloseInstancePublicPorts -func (c *Lightsail) CloseInstancePublicPorts(input *CloseInstancePublicPortsInput) (*CloseInstancePublicPortsOutput, error) { - req, out := c.CloseInstancePublicPortsRequest(input) - return out, req.Send() -} - -// CloseInstancePublicPortsWithContext is the same as CloseInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See CloseInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CloseInstancePublicPortsWithContext(ctx aws.Context, input *CloseInstancePublicPortsInput, opts ...request.Option) (*CloseInstancePublicPortsOutput, error) { - req, out := c.CloseInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDisk = "CreateDisk" - -// CreateDiskRequest generates a "aws/request.Request" representing the -// client's request for the CreateDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDisk for more information on using the CreateDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskRequest method. -// req, resp := client.CreateDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDisk -func (c *Lightsail) CreateDiskRequest(input *CreateDiskInput) (req *request.Request, output *CreateDiskOutput) { - op := &request.Operation{ - Name: opCreateDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskInput{} - } - - output = &CreateDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDisk API operation for Amazon Lightsail. -// -// Creates a block storage disk that can be attached to a Lightsail instance -// in the same Availability Zone (e.g., us-east-2a). The disk is created in -// the regional endpoint that you send the HTTP request to. For more information, -// see Regions and Availability Zones in Lightsail (https://lightsail.aws.amazon.com/ls/docs/overview/article/understanding-regions-and-availability-zones-in-amazon-lightsail). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDisk -func (c *Lightsail) CreateDisk(input *CreateDiskInput) (*CreateDiskOutput, error) { - req, out := c.CreateDiskRequest(input) - return out, req.Send() -} - -// CreateDiskWithContext is the same as CreateDisk with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskWithContext(ctx aws.Context, input *CreateDiskInput, opts ...request.Option) (*CreateDiskOutput, error) { - req, out := c.CreateDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDiskFromSnapshot = "CreateDiskFromSnapshot" - -// CreateDiskFromSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateDiskFromSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDiskFromSnapshot for more information on using the CreateDiskFromSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskFromSnapshotRequest method. -// req, resp := client.CreateDiskFromSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskFromSnapshot -func (c *Lightsail) CreateDiskFromSnapshotRequest(input *CreateDiskFromSnapshotInput) (req *request.Request, output *CreateDiskFromSnapshotOutput) { - op := &request.Operation{ - Name: opCreateDiskFromSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskFromSnapshotInput{} - } - - output = &CreateDiskFromSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDiskFromSnapshot API operation for Amazon Lightsail. -// -// Creates a block storage disk from a disk snapshot that can be attached to -// a Lightsail instance in the same Availability Zone (e.g., us-east-2a). The -// disk is created in the regional endpoint that you send the HTTP request to. -// For more information, see Regions and Availability Zones in Lightsail (https://lightsail.aws.amazon.com/ls/docs/overview/article/understanding-regions-and-availability-zones-in-amazon-lightsail). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDiskFromSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskFromSnapshot -func (c *Lightsail) CreateDiskFromSnapshot(input *CreateDiskFromSnapshotInput) (*CreateDiskFromSnapshotOutput, error) { - req, out := c.CreateDiskFromSnapshotRequest(input) - return out, req.Send() -} - -// CreateDiskFromSnapshotWithContext is the same as CreateDiskFromSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDiskFromSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskFromSnapshotWithContext(ctx aws.Context, input *CreateDiskFromSnapshotInput, opts ...request.Option) (*CreateDiskFromSnapshotOutput, error) { - req, out := c.CreateDiskFromSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDiskSnapshot = "CreateDiskSnapshot" - -// CreateDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDiskSnapshot for more information on using the CreateDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDiskSnapshotRequest method. -// req, resp := client.CreateDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskSnapshot -func (c *Lightsail) CreateDiskSnapshotRequest(input *CreateDiskSnapshotInput) (req *request.Request, output *CreateDiskSnapshotOutput) { - op := &request.Operation{ - Name: opCreateDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDiskSnapshotInput{} - } - - output = &CreateDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDiskSnapshot API operation for Amazon Lightsail. -// -// Creates a snapshot of a block storage disk. You can use snapshots for backups, -// to make copies of disks, and to save data before shutting down a Lightsail -// instance. -// -// You can take a snapshot of an attached disk that is in use; however, snapshots -// only capture data that has been written to your disk at the time the snapshot -// command is issued. This may exclude any data that has been cached by any -// applications or the operating system. If you can pause any file systems on -// the disk long enough to take a snapshot, your snapshot should be complete. -// Nevertheless, if you cannot pause all file writes to the disk, you should -// unmount the disk from within the Lightsail instance, issue the create disk -// snapshot command, and then remount the disk to ensure a consistent and complete -// snapshot. You may remount and use your disk while the snapshot status is -// pending. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDiskSnapshot -func (c *Lightsail) CreateDiskSnapshot(input *CreateDiskSnapshotInput) (*CreateDiskSnapshotOutput, error) { - req, out := c.CreateDiskSnapshotRequest(input) - return out, req.Send() -} - -// CreateDiskSnapshotWithContext is the same as CreateDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDiskSnapshotWithContext(ctx aws.Context, input *CreateDiskSnapshotInput, opts ...request.Option) (*CreateDiskSnapshotOutput, error) { - req, out := c.CreateDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDomain = "CreateDomain" - -// CreateDomainRequest generates a "aws/request.Request" representing the -// client's request for the CreateDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDomain for more information on using the CreateDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDomainRequest method. -// req, resp := client.CreateDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomain -func (c *Lightsail) CreateDomainRequest(input *CreateDomainInput) (req *request.Request, output *CreateDomainOutput) { - op := &request.Operation{ - Name: opCreateDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDomainInput{} - } - - output = &CreateDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDomain API operation for Amazon Lightsail. -// -// Creates a domain resource for the specified domain (e.g., example.com). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomain -func (c *Lightsail) CreateDomain(input *CreateDomainInput) (*CreateDomainOutput, error) { - req, out := c.CreateDomainRequest(input) - return out, req.Send() -} - -// CreateDomainWithContext is the same as CreateDomain with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDomainWithContext(ctx aws.Context, input *CreateDomainInput, opts ...request.Option) (*CreateDomainOutput, error) { - req, out := c.CreateDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateDomainEntry = "CreateDomainEntry" - -// CreateDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the CreateDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateDomainEntry for more information on using the CreateDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateDomainEntryRequest method. -// req, resp := client.CreateDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomainEntry -func (c *Lightsail) CreateDomainEntryRequest(input *CreateDomainEntryInput) (req *request.Request, output *CreateDomainEntryOutput) { - op := &request.Operation{ - Name: opCreateDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateDomainEntryInput{} - } - - output = &CreateDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateDomainEntry API operation for Amazon Lightsail. -// -// Creates one of the following entry records associated with the domain: A -// record, CNAME record, TXT record, or MX record. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateDomainEntry -func (c *Lightsail) CreateDomainEntry(input *CreateDomainEntryInput) (*CreateDomainEntryOutput, error) { - req, out := c.CreateDomainEntryRequest(input) - return out, req.Send() -} - -// CreateDomainEntryWithContext is the same as CreateDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See CreateDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateDomainEntryWithContext(ctx aws.Context, input *CreateDomainEntryInput, opts ...request.Option) (*CreateDomainEntryOutput, error) { - req, out := c.CreateDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstanceSnapshot = "CreateInstanceSnapshot" - -// CreateInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstanceSnapshot for more information on using the CreateInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstanceSnapshotRequest method. -// req, resp := client.CreateInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot -func (c *Lightsail) CreateInstanceSnapshotRequest(input *CreateInstanceSnapshotInput) (req *request.Request, output *CreateInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opCreateInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstanceSnapshotInput{} - } - - output = &CreateInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstanceSnapshot API operation for Amazon Lightsail. -// -// Creates a snapshot of a specific virtual private server, or instance. You -// can use a snapshot to create a new instance that is based on that snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstanceSnapshot -func (c *Lightsail) CreateInstanceSnapshot(input *CreateInstanceSnapshotInput) (*CreateInstanceSnapshotOutput, error) { - req, out := c.CreateInstanceSnapshotRequest(input) - return out, req.Send() -} - -// CreateInstanceSnapshotWithContext is the same as CreateInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstanceSnapshotWithContext(ctx aws.Context, input *CreateInstanceSnapshotInput, opts ...request.Option) (*CreateInstanceSnapshotOutput, error) { - req, out := c.CreateInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstances = "CreateInstances" - -// CreateInstancesRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstances for more information on using the CreateInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstancesRequest method. -// req, resp := client.CreateInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstances -func (c *Lightsail) CreateInstancesRequest(input *CreateInstancesInput) (req *request.Request, output *CreateInstancesOutput) { - op := &request.Operation{ - Name: opCreateInstances, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstancesInput{} - } - - output = &CreateInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstances API operation for Amazon Lightsail. -// -// Creates one or more Amazon Lightsail virtual private servers, or instances. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstances -func (c *Lightsail) CreateInstances(input *CreateInstancesInput) (*CreateInstancesOutput, error) { - req, out := c.CreateInstancesRequest(input) - return out, req.Send() -} - -// CreateInstancesWithContext is the same as CreateInstances with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstancesWithContext(ctx aws.Context, input *CreateInstancesInput, opts ...request.Option) (*CreateInstancesOutput, error) { - req, out := c.CreateInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateInstancesFromSnapshot = "CreateInstancesFromSnapshot" - -// CreateInstancesFromSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the CreateInstancesFromSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateInstancesFromSnapshot for more information on using the CreateInstancesFromSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateInstancesFromSnapshotRequest method. -// req, resp := client.CreateInstancesFromSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstancesFromSnapshot -func (c *Lightsail) CreateInstancesFromSnapshotRequest(input *CreateInstancesFromSnapshotInput) (req *request.Request, output *CreateInstancesFromSnapshotOutput) { - op := &request.Operation{ - Name: opCreateInstancesFromSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateInstancesFromSnapshotInput{} - } - - output = &CreateInstancesFromSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateInstancesFromSnapshot API operation for Amazon Lightsail. -// -// Uses a specific snapshot as a blueprint for creating one or more new instances -// that are based on that identical configuration. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateInstancesFromSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateInstancesFromSnapshot -func (c *Lightsail) CreateInstancesFromSnapshot(input *CreateInstancesFromSnapshotInput) (*CreateInstancesFromSnapshotOutput, error) { - req, out := c.CreateInstancesFromSnapshotRequest(input) - return out, req.Send() -} - -// CreateInstancesFromSnapshotWithContext is the same as CreateInstancesFromSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See CreateInstancesFromSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateInstancesFromSnapshotWithContext(ctx aws.Context, input *CreateInstancesFromSnapshotInput, opts ...request.Option) (*CreateInstancesFromSnapshotOutput, error) { - req, out := c.CreateInstancesFromSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateKeyPair = "CreateKeyPair" - -// CreateKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the CreateKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateKeyPair for more information on using the CreateKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateKeyPairRequest method. -// req, resp := client.CreateKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateKeyPair -func (c *Lightsail) CreateKeyPairRequest(input *CreateKeyPairInput) (req *request.Request, output *CreateKeyPairOutput) { - op := &request.Operation{ - Name: opCreateKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateKeyPairInput{} - } - - output = &CreateKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateKeyPair API operation for Amazon Lightsail. -// -// Creates sn SSH key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateKeyPair -func (c *Lightsail) CreateKeyPair(input *CreateKeyPairInput) (*CreateKeyPairOutput, error) { - req, out := c.CreateKeyPairRequest(input) - return out, req.Send() -} - -// CreateKeyPairWithContext is the same as CreateKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See CreateKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateKeyPairWithContext(ctx aws.Context, input *CreateKeyPairInput, opts ...request.Option) (*CreateKeyPairOutput, error) { - req, out := c.CreateKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLoadBalancer = "CreateLoadBalancer" - -// CreateLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the CreateLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLoadBalancer for more information on using the CreateLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateLoadBalancerRequest method. -// req, resp := client.CreateLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancer -func (c *Lightsail) CreateLoadBalancerRequest(input *CreateLoadBalancerInput) (req *request.Request, output *CreateLoadBalancerOutput) { - op := &request.Operation{ - Name: opCreateLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLoadBalancerInput{} - } - - output = &CreateLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateLoadBalancer API operation for Amazon Lightsail. -// -// Creates a Lightsail load balancer. To learn more about deciding whether to -// load balance your application, see Configure your Lightsail instances for -// load balancing (https://lightsail.aws.amazon.com/ls/docs/how-to/article/configure-lightsail-instances-for-load-balancing). -// You can create up to 5 load balancers per AWS Region in your account. -// -// When you create a load balancer, you can specify a unique name and port settings. -// To change additional load balancer settings, use the UpdateLoadBalancerAttribute -// operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancer -func (c *Lightsail) CreateLoadBalancer(input *CreateLoadBalancerInput) (*CreateLoadBalancerOutput, error) { - req, out := c.CreateLoadBalancerRequest(input) - return out, req.Send() -} - -// CreateLoadBalancerWithContext is the same as CreateLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateLoadBalancerWithContext(ctx aws.Context, input *CreateLoadBalancerInput, opts ...request.Option) (*CreateLoadBalancerOutput, error) { - req, out := c.CreateLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateLoadBalancerTlsCertificate = "CreateLoadBalancerTlsCertificate" - -// CreateLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the CreateLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateLoadBalancerTlsCertificate for more information on using the CreateLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateLoadBalancerTlsCertificateRequest method. -// req, resp := client.CreateLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancerTlsCertificate -func (c *Lightsail) CreateLoadBalancerTlsCertificateRequest(input *CreateLoadBalancerTlsCertificateInput) (req *request.Request, output *CreateLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opCreateLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &CreateLoadBalancerTlsCertificateInput{} - } - - output = &CreateLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Creates a Lightsail load balancer TLS certificate. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation CreateLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/CreateLoadBalancerTlsCertificate -func (c *Lightsail) CreateLoadBalancerTlsCertificate(input *CreateLoadBalancerTlsCertificateInput) (*CreateLoadBalancerTlsCertificateOutput, error) { - req, out := c.CreateLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// CreateLoadBalancerTlsCertificateWithContext is the same as CreateLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See CreateLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) CreateLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *CreateLoadBalancerTlsCertificateInput, opts ...request.Option) (*CreateLoadBalancerTlsCertificateOutput, error) { - req, out := c.CreateLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDisk = "DeleteDisk" - -// DeleteDiskRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDisk for more information on using the DeleteDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDiskRequest method. -// req, resp := client.DeleteDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDisk -func (c *Lightsail) DeleteDiskRequest(input *DeleteDiskInput) (req *request.Request, output *DeleteDiskOutput) { - op := &request.Operation{ - Name: opDeleteDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDiskInput{} - } - - output = &DeleteDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDisk API operation for Amazon Lightsail. -// -// Deletes the specified block storage disk. The disk must be in the available -// state (not attached to a Lightsail instance). -// -// The disk may remain in the deleting state for several minutes. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDisk -func (c *Lightsail) DeleteDisk(input *DeleteDiskInput) (*DeleteDiskOutput, error) { - req, out := c.DeleteDiskRequest(input) - return out, req.Send() -} - -// DeleteDiskWithContext is the same as DeleteDisk with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDiskWithContext(ctx aws.Context, input *DeleteDiskInput, opts ...request.Option) (*DeleteDiskOutput, error) { - req, out := c.DeleteDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDiskSnapshot = "DeleteDiskSnapshot" - -// DeleteDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDiskSnapshot for more information on using the DeleteDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDiskSnapshotRequest method. -// req, resp := client.DeleteDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDiskSnapshot -func (c *Lightsail) DeleteDiskSnapshotRequest(input *DeleteDiskSnapshotInput) (req *request.Request, output *DeleteDiskSnapshotOutput) { - op := &request.Operation{ - Name: opDeleteDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDiskSnapshotInput{} - } - - output = &DeleteDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDiskSnapshot API operation for Amazon Lightsail. -// -// Deletes the specified disk snapshot. -// -// When you make periodic snapshots of a disk, the snapshots are incremental, -// and only the blocks on the device that have changed since your last snapshot -// are saved in the new snapshot. When you delete a snapshot, only the data -// not needed for any other snapshot is removed. So regardless of which prior -// snapshots have been deleted, all active snapshots will have access to all -// the information needed to restore the disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDiskSnapshot -func (c *Lightsail) DeleteDiskSnapshot(input *DeleteDiskSnapshotInput) (*DeleteDiskSnapshotOutput, error) { - req, out := c.DeleteDiskSnapshotRequest(input) - return out, req.Send() -} - -// DeleteDiskSnapshotWithContext is the same as DeleteDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDiskSnapshotWithContext(ctx aws.Context, input *DeleteDiskSnapshotInput, opts ...request.Option) (*DeleteDiskSnapshotOutput, error) { - req, out := c.DeleteDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDomain = "DeleteDomain" - -// DeleteDomainRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDomain for more information on using the DeleteDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDomainRequest method. -// req, resp := client.DeleteDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomain -func (c *Lightsail) DeleteDomainRequest(input *DeleteDomainInput) (req *request.Request, output *DeleteDomainOutput) { - op := &request.Operation{ - Name: opDeleteDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDomainInput{} - } - - output = &DeleteDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDomain API operation for Amazon Lightsail. -// -// Deletes the specified domain recordset and all of its domain records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomain -func (c *Lightsail) DeleteDomain(input *DeleteDomainInput) (*DeleteDomainOutput, error) { - req, out := c.DeleteDomainRequest(input) - return out, req.Send() -} - -// DeleteDomainWithContext is the same as DeleteDomain with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDomainWithContext(ctx aws.Context, input *DeleteDomainInput, opts ...request.Option) (*DeleteDomainOutput, error) { - req, out := c.DeleteDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteDomainEntry = "DeleteDomainEntry" - -// DeleteDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the DeleteDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteDomainEntry for more information on using the DeleteDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteDomainEntryRequest method. -// req, resp := client.DeleteDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomainEntry -func (c *Lightsail) DeleteDomainEntryRequest(input *DeleteDomainEntryInput) (req *request.Request, output *DeleteDomainEntryOutput) { - op := &request.Operation{ - Name: opDeleteDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteDomainEntryInput{} - } - - output = &DeleteDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteDomainEntry API operation for Amazon Lightsail. -// -// Deletes a specific domain entry. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteDomainEntry -func (c *Lightsail) DeleteDomainEntry(input *DeleteDomainEntryInput) (*DeleteDomainEntryOutput, error) { - req, out := c.DeleteDomainEntryRequest(input) - return out, req.Send() -} - -// DeleteDomainEntryWithContext is the same as DeleteDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteDomainEntryWithContext(ctx aws.Context, input *DeleteDomainEntryInput, opts ...request.Option) (*DeleteDomainEntryOutput, error) { - req, out := c.DeleteDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteInstance = "DeleteInstance" - -// DeleteInstanceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteInstance for more information on using the DeleteInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteInstanceRequest method. -// req, resp := client.DeleteInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstance -func (c *Lightsail) DeleteInstanceRequest(input *DeleteInstanceInput) (req *request.Request, output *DeleteInstanceOutput) { - op := &request.Operation{ - Name: opDeleteInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteInstanceInput{} - } - - output = &DeleteInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteInstance API operation for Amazon Lightsail. -// -// Deletes a specific Amazon Lightsail virtual private server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstance -func (c *Lightsail) DeleteInstance(input *DeleteInstanceInput) (*DeleteInstanceOutput, error) { - req, out := c.DeleteInstanceRequest(input) - return out, req.Send() -} - -// DeleteInstanceWithContext is the same as DeleteInstance with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteInstanceWithContext(ctx aws.Context, input *DeleteInstanceInput, opts ...request.Option) (*DeleteInstanceOutput, error) { - req, out := c.DeleteInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteInstanceSnapshot = "DeleteInstanceSnapshot" - -// DeleteInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the DeleteInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteInstanceSnapshot for more information on using the DeleteInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteInstanceSnapshotRequest method. -// req, resp := client.DeleteInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstanceSnapshot -func (c *Lightsail) DeleteInstanceSnapshotRequest(input *DeleteInstanceSnapshotInput) (req *request.Request, output *DeleteInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opDeleteInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteInstanceSnapshotInput{} - } - - output = &DeleteInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteInstanceSnapshot API operation for Amazon Lightsail. -// -// Deletes a specific snapshot of a virtual private server (or instance). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteInstanceSnapshot -func (c *Lightsail) DeleteInstanceSnapshot(input *DeleteInstanceSnapshotInput) (*DeleteInstanceSnapshotOutput, error) { - req, out := c.DeleteInstanceSnapshotRequest(input) - return out, req.Send() -} - -// DeleteInstanceSnapshotWithContext is the same as DeleteInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteInstanceSnapshotWithContext(ctx aws.Context, input *DeleteInstanceSnapshotInput, opts ...request.Option) (*DeleteInstanceSnapshotOutput, error) { - req, out := c.DeleteInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteKeyPair = "DeleteKeyPair" - -// DeleteKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the DeleteKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteKeyPair for more information on using the DeleteKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteKeyPairRequest method. -// req, resp := client.DeleteKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteKeyPair -func (c *Lightsail) DeleteKeyPairRequest(input *DeleteKeyPairInput) (req *request.Request, output *DeleteKeyPairOutput) { - op := &request.Operation{ - Name: opDeleteKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteKeyPairInput{} - } - - output = &DeleteKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteKeyPair API operation for Amazon Lightsail. -// -// Deletes a specific SSH key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteKeyPair -func (c *Lightsail) DeleteKeyPair(input *DeleteKeyPairInput) (*DeleteKeyPairOutput, error) { - req, out := c.DeleteKeyPairRequest(input) - return out, req.Send() -} - -// DeleteKeyPairWithContext is the same as DeleteKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteKeyPairWithContext(ctx aws.Context, input *DeleteKeyPairInput, opts ...request.Option) (*DeleteKeyPairOutput, error) { - req, out := c.DeleteKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLoadBalancer = "DeleteLoadBalancer" - -// DeleteLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLoadBalancer for more information on using the DeleteLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteLoadBalancerRequest method. -// req, resp := client.DeleteLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancer -func (c *Lightsail) DeleteLoadBalancerRequest(input *DeleteLoadBalancerInput) (req *request.Request, output *DeleteLoadBalancerOutput) { - op := &request.Operation{ - Name: opDeleteLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLoadBalancerInput{} - } - - output = &DeleteLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteLoadBalancer API operation for Amazon Lightsail. -// -// Deletes a Lightsail load balancer and all its associated SSL/TLS certificates. -// Once the load balancer is deleted, you will need to create a new load balancer, -// create a new certificate, and verify domain ownership again. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancer -func (c *Lightsail) DeleteLoadBalancer(input *DeleteLoadBalancerInput) (*DeleteLoadBalancerOutput, error) { - req, out := c.DeleteLoadBalancerRequest(input) - return out, req.Send() -} - -// DeleteLoadBalancerWithContext is the same as DeleteLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteLoadBalancerWithContext(ctx aws.Context, input *DeleteLoadBalancerInput, opts ...request.Option) (*DeleteLoadBalancerOutput, error) { - req, out := c.DeleteLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteLoadBalancerTlsCertificate = "DeleteLoadBalancerTlsCertificate" - -// DeleteLoadBalancerTlsCertificateRequest generates a "aws/request.Request" representing the -// client's request for the DeleteLoadBalancerTlsCertificate operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteLoadBalancerTlsCertificate for more information on using the DeleteLoadBalancerTlsCertificate -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteLoadBalancerTlsCertificateRequest method. -// req, resp := client.DeleteLoadBalancerTlsCertificateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancerTlsCertificate -func (c *Lightsail) DeleteLoadBalancerTlsCertificateRequest(input *DeleteLoadBalancerTlsCertificateInput) (req *request.Request, output *DeleteLoadBalancerTlsCertificateOutput) { - op := &request.Operation{ - Name: opDeleteLoadBalancerTlsCertificate, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DeleteLoadBalancerTlsCertificateInput{} - } - - output = &DeleteLoadBalancerTlsCertificateOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteLoadBalancerTlsCertificate API operation for Amazon Lightsail. -// -// Deletes an SSL/TLS certificate associated with a Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DeleteLoadBalancerTlsCertificate for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DeleteLoadBalancerTlsCertificate -func (c *Lightsail) DeleteLoadBalancerTlsCertificate(input *DeleteLoadBalancerTlsCertificateInput) (*DeleteLoadBalancerTlsCertificateOutput, error) { - req, out := c.DeleteLoadBalancerTlsCertificateRequest(input) - return out, req.Send() -} - -// DeleteLoadBalancerTlsCertificateWithContext is the same as DeleteLoadBalancerTlsCertificate with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteLoadBalancerTlsCertificate for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DeleteLoadBalancerTlsCertificateWithContext(ctx aws.Context, input *DeleteLoadBalancerTlsCertificateInput, opts ...request.Option) (*DeleteLoadBalancerTlsCertificateOutput, error) { - req, out := c.DeleteLoadBalancerTlsCertificateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachDisk = "DetachDisk" - -// DetachDiskRequest generates a "aws/request.Request" representing the -// client's request for the DetachDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachDisk for more information on using the DetachDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachDiskRequest method. -// req, resp := client.DetachDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachDisk -func (c *Lightsail) DetachDiskRequest(input *DetachDiskInput) (req *request.Request, output *DetachDiskOutput) { - op := &request.Operation{ - Name: opDetachDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachDiskInput{} - } - - output = &DetachDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachDisk API operation for Amazon Lightsail. -// -// Detaches a stopped block storage disk from a Lightsail instance. Make sure -// to unmount any file systems on the device within your operating system before -// stopping the instance and detaching the disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachDisk -func (c *Lightsail) DetachDisk(input *DetachDiskInput) (*DetachDiskOutput, error) { - req, out := c.DetachDiskRequest(input) - return out, req.Send() -} - -// DetachDiskWithContext is the same as DetachDisk with the addition of -// the ability to pass a context and additional request options. -// -// See DetachDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachDiskWithContext(ctx aws.Context, input *DetachDiskInput, opts ...request.Option) (*DetachDiskOutput, error) { - req, out := c.DetachDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachInstancesFromLoadBalancer = "DetachInstancesFromLoadBalancer" - -// DetachInstancesFromLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the DetachInstancesFromLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachInstancesFromLoadBalancer for more information on using the DetachInstancesFromLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachInstancesFromLoadBalancerRequest method. -// req, resp := client.DetachInstancesFromLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachInstancesFromLoadBalancer -func (c *Lightsail) DetachInstancesFromLoadBalancerRequest(input *DetachInstancesFromLoadBalancerInput) (req *request.Request, output *DetachInstancesFromLoadBalancerOutput) { - op := &request.Operation{ - Name: opDetachInstancesFromLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachInstancesFromLoadBalancerInput{} - } - - output = &DetachInstancesFromLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachInstancesFromLoadBalancer API operation for Amazon Lightsail. -// -// Detaches the specified instances from a Lightsail load balancer. -// -// This operation waits until the instances are no longer needed before they -// are detached from the load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachInstancesFromLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachInstancesFromLoadBalancer -func (c *Lightsail) DetachInstancesFromLoadBalancer(input *DetachInstancesFromLoadBalancerInput) (*DetachInstancesFromLoadBalancerOutput, error) { - req, out := c.DetachInstancesFromLoadBalancerRequest(input) - return out, req.Send() -} - -// DetachInstancesFromLoadBalancerWithContext is the same as DetachInstancesFromLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See DetachInstancesFromLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachInstancesFromLoadBalancerWithContext(ctx aws.Context, input *DetachInstancesFromLoadBalancerInput, opts ...request.Option) (*DetachInstancesFromLoadBalancerOutput, error) { - req, out := c.DetachInstancesFromLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDetachStaticIp = "DetachStaticIp" - -// DetachStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the DetachStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DetachStaticIp for more information on using the DetachStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DetachStaticIpRequest method. -// req, resp := client.DetachStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachStaticIp -func (c *Lightsail) DetachStaticIpRequest(input *DetachStaticIpInput) (req *request.Request, output *DetachStaticIpOutput) { - op := &request.Operation{ - Name: opDetachStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DetachStaticIpInput{} - } - - output = &DetachStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// DetachStaticIp API operation for Amazon Lightsail. -// -// Detaches a static IP from the Amazon Lightsail instance to which it is attached. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DetachStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DetachStaticIp -func (c *Lightsail) DetachStaticIp(input *DetachStaticIpInput) (*DetachStaticIpOutput, error) { - req, out := c.DetachStaticIpRequest(input) - return out, req.Send() -} - -// DetachStaticIpWithContext is the same as DetachStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See DetachStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DetachStaticIpWithContext(ctx aws.Context, input *DetachStaticIpInput, opts ...request.Option) (*DetachStaticIpOutput, error) { - req, out := c.DetachStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDownloadDefaultKeyPair = "DownloadDefaultKeyPair" - -// DownloadDefaultKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the DownloadDefaultKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DownloadDefaultKeyPair for more information on using the DownloadDefaultKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DownloadDefaultKeyPairRequest method. -// req, resp := client.DownloadDefaultKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DownloadDefaultKeyPair -func (c *Lightsail) DownloadDefaultKeyPairRequest(input *DownloadDefaultKeyPairInput) (req *request.Request, output *DownloadDefaultKeyPairOutput) { - op := &request.Operation{ - Name: opDownloadDefaultKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DownloadDefaultKeyPairInput{} - } - - output = &DownloadDefaultKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// DownloadDefaultKeyPair API operation for Amazon Lightsail. -// -// Downloads the default SSH key pair from the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation DownloadDefaultKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/DownloadDefaultKeyPair -func (c *Lightsail) DownloadDefaultKeyPair(input *DownloadDefaultKeyPairInput) (*DownloadDefaultKeyPairOutput, error) { - req, out := c.DownloadDefaultKeyPairRequest(input) - return out, req.Send() -} - -// DownloadDefaultKeyPairWithContext is the same as DownloadDefaultKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See DownloadDefaultKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) DownloadDefaultKeyPairWithContext(ctx aws.Context, input *DownloadDefaultKeyPairInput, opts ...request.Option) (*DownloadDefaultKeyPairOutput, error) { - req, out := c.DownloadDefaultKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetActiveNames = "GetActiveNames" - -// GetActiveNamesRequest generates a "aws/request.Request" representing the -// client's request for the GetActiveNames operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetActiveNames for more information on using the GetActiveNames -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetActiveNamesRequest method. -// req, resp := client.GetActiveNamesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetActiveNames -func (c *Lightsail) GetActiveNamesRequest(input *GetActiveNamesInput) (req *request.Request, output *GetActiveNamesOutput) { - op := &request.Operation{ - Name: opGetActiveNames, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetActiveNamesInput{} - } - - output = &GetActiveNamesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetActiveNames API operation for Amazon Lightsail. -// -// Returns the names of all active (not deleted) resources. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetActiveNames for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetActiveNames -func (c *Lightsail) GetActiveNames(input *GetActiveNamesInput) (*GetActiveNamesOutput, error) { - req, out := c.GetActiveNamesRequest(input) - return out, req.Send() -} - -// GetActiveNamesWithContext is the same as GetActiveNames with the addition of -// the ability to pass a context and additional request options. -// -// See GetActiveNames for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetActiveNamesWithContext(ctx aws.Context, input *GetActiveNamesInput, opts ...request.Option) (*GetActiveNamesOutput, error) { - req, out := c.GetActiveNamesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBlueprints = "GetBlueprints" - -// GetBlueprintsRequest generates a "aws/request.Request" representing the -// client's request for the GetBlueprints operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBlueprints for more information on using the GetBlueprints -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBlueprintsRequest method. -// req, resp := client.GetBlueprintsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBlueprints -func (c *Lightsail) GetBlueprintsRequest(input *GetBlueprintsInput) (req *request.Request, output *GetBlueprintsOutput) { - op := &request.Operation{ - Name: opGetBlueprints, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetBlueprintsInput{} - } - - output = &GetBlueprintsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBlueprints API operation for Amazon Lightsail. -// -// Returns the list of available instance images, or blueprints. You can use -// a blueprint to create a new virtual private server already running a specific -// operating system, as well as a preinstalled app or development stack. The -// software each instance is running depends on the blueprint image you choose. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetBlueprints for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBlueprints -func (c *Lightsail) GetBlueprints(input *GetBlueprintsInput) (*GetBlueprintsOutput, error) { - req, out := c.GetBlueprintsRequest(input) - return out, req.Send() -} - -// GetBlueprintsWithContext is the same as GetBlueprints with the addition of -// the ability to pass a context and additional request options. -// -// See GetBlueprints for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetBlueprintsWithContext(ctx aws.Context, input *GetBlueprintsInput, opts ...request.Option) (*GetBlueprintsOutput, error) { - req, out := c.GetBlueprintsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetBundles = "GetBundles" - -// GetBundlesRequest generates a "aws/request.Request" representing the -// client's request for the GetBundles operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetBundles for more information on using the GetBundles -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetBundlesRequest method. -// req, resp := client.GetBundlesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBundles -func (c *Lightsail) GetBundlesRequest(input *GetBundlesInput) (req *request.Request, output *GetBundlesOutput) { - op := &request.Operation{ - Name: opGetBundles, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetBundlesInput{} - } - - output = &GetBundlesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetBundles API operation for Amazon Lightsail. -// -// Returns the list of bundles that are available for purchase. A bundle describes -// the specs for your virtual private server (or instance). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetBundles for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetBundles -func (c *Lightsail) GetBundles(input *GetBundlesInput) (*GetBundlesOutput, error) { - req, out := c.GetBundlesRequest(input) - return out, req.Send() -} - -// GetBundlesWithContext is the same as GetBundles with the addition of -// the ability to pass a context and additional request options. -// -// See GetBundles for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetBundlesWithContext(ctx aws.Context, input *GetBundlesInput, opts ...request.Option) (*GetBundlesOutput, error) { - req, out := c.GetBundlesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDisk = "GetDisk" - -// GetDiskRequest generates a "aws/request.Request" representing the -// client's request for the GetDisk operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDisk for more information on using the GetDisk -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskRequest method. -// req, resp := client.GetDiskRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisk -func (c *Lightsail) GetDiskRequest(input *GetDiskInput) (req *request.Request, output *GetDiskOutput) { - op := &request.Operation{ - Name: opGetDisk, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskInput{} - } - - output = &GetDiskOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDisk API operation for Amazon Lightsail. -// -// Returns information about a specific block storage disk. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDisk for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisk -func (c *Lightsail) GetDisk(input *GetDiskInput) (*GetDiskOutput, error) { - req, out := c.GetDiskRequest(input) - return out, req.Send() -} - -// GetDiskWithContext is the same as GetDisk with the addition of -// the ability to pass a context and additional request options. -// -// See GetDisk for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskWithContext(ctx aws.Context, input *GetDiskInput, opts ...request.Option) (*GetDiskOutput, error) { - req, out := c.GetDiskRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDiskSnapshot = "GetDiskSnapshot" - -// GetDiskSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetDiskSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDiskSnapshot for more information on using the GetDiskSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskSnapshotRequest method. -// req, resp := client.GetDiskSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshot -func (c *Lightsail) GetDiskSnapshotRequest(input *GetDiskSnapshotInput) (req *request.Request, output *GetDiskSnapshotOutput) { - op := &request.Operation{ - Name: opGetDiskSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskSnapshotInput{} - } - - output = &GetDiskSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDiskSnapshot API operation for Amazon Lightsail. -// -// Returns information about a specific block storage disk snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDiskSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshot -func (c *Lightsail) GetDiskSnapshot(input *GetDiskSnapshotInput) (*GetDiskSnapshotOutput, error) { - req, out := c.GetDiskSnapshotRequest(input) - return out, req.Send() -} - -// GetDiskSnapshotWithContext is the same as GetDiskSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See GetDiskSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskSnapshotWithContext(ctx aws.Context, input *GetDiskSnapshotInput, opts ...request.Option) (*GetDiskSnapshotOutput, error) { - req, out := c.GetDiskSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDiskSnapshots = "GetDiskSnapshots" - -// GetDiskSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetDiskSnapshots operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDiskSnapshots for more information on using the GetDiskSnapshots -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDiskSnapshotsRequest method. -// req, resp := client.GetDiskSnapshotsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshots -func (c *Lightsail) GetDiskSnapshotsRequest(input *GetDiskSnapshotsInput) (req *request.Request, output *GetDiskSnapshotsOutput) { - op := &request.Operation{ - Name: opGetDiskSnapshots, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDiskSnapshotsInput{} - } - - output = &GetDiskSnapshotsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDiskSnapshots API operation for Amazon Lightsail. -// -// Returns information about all block storage disk snapshots in your AWS account -// and region. -// -// If you are describing a long list of disk snapshots, you can paginate the -// output to make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDiskSnapshots for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDiskSnapshots -func (c *Lightsail) GetDiskSnapshots(input *GetDiskSnapshotsInput) (*GetDiskSnapshotsOutput, error) { - req, out := c.GetDiskSnapshotsRequest(input) - return out, req.Send() -} - -// GetDiskSnapshotsWithContext is the same as GetDiskSnapshots with the addition of -// the ability to pass a context and additional request options. -// -// See GetDiskSnapshots for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDiskSnapshotsWithContext(ctx aws.Context, input *GetDiskSnapshotsInput, opts ...request.Option) (*GetDiskSnapshotsOutput, error) { - req, out := c.GetDiskSnapshotsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDisks = "GetDisks" - -// GetDisksRequest generates a "aws/request.Request" representing the -// client's request for the GetDisks operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDisks for more information on using the GetDisks -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDisksRequest method. -// req, resp := client.GetDisksRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisks -func (c *Lightsail) GetDisksRequest(input *GetDisksInput) (req *request.Request, output *GetDisksOutput) { - op := &request.Operation{ - Name: opGetDisks, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDisksInput{} - } - - output = &GetDisksOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDisks API operation for Amazon Lightsail. -// -// Returns information about all block storage disks in your AWS account and -// region. -// -// If you are describing a long list of disks, you can paginate the output to -// make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDisks for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDisks -func (c *Lightsail) GetDisks(input *GetDisksInput) (*GetDisksOutput, error) { - req, out := c.GetDisksRequest(input) - return out, req.Send() -} - -// GetDisksWithContext is the same as GetDisks with the addition of -// the ability to pass a context and additional request options. -// -// See GetDisks for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDisksWithContext(ctx aws.Context, input *GetDisksInput, opts ...request.Option) (*GetDisksOutput, error) { - req, out := c.GetDisksRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDomain = "GetDomain" - -// GetDomainRequest generates a "aws/request.Request" representing the -// client's request for the GetDomain operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDomain for more information on using the GetDomain -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDomainRequest method. -// req, resp := client.GetDomainRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain -func (c *Lightsail) GetDomainRequest(input *GetDomainInput) (req *request.Request, output *GetDomainOutput) { - op := &request.Operation{ - Name: opGetDomain, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDomainInput{} - } - - output = &GetDomainOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDomain API operation for Amazon Lightsail. -// -// Returns information about a specific domain recordset. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDomain for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomain -func (c *Lightsail) GetDomain(input *GetDomainInput) (*GetDomainOutput, error) { - req, out := c.GetDomainRequest(input) - return out, req.Send() -} - -// GetDomainWithContext is the same as GetDomain with the addition of -// the ability to pass a context and additional request options. -// -// See GetDomain for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDomainWithContext(ctx aws.Context, input *GetDomainInput, opts ...request.Option) (*GetDomainOutput, error) { - req, out := c.GetDomainRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetDomains = "GetDomains" - -// GetDomainsRequest generates a "aws/request.Request" representing the -// client's request for the GetDomains operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetDomains for more information on using the GetDomains -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetDomainsRequest method. -// req, resp := client.GetDomainsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains -func (c *Lightsail) GetDomainsRequest(input *GetDomainsInput) (req *request.Request, output *GetDomainsOutput) { - op := &request.Operation{ - Name: opGetDomains, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetDomainsInput{} - } - - output = &GetDomainsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetDomains API operation for Amazon Lightsail. -// -// Returns a list of all domains in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetDomains for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetDomains -func (c *Lightsail) GetDomains(input *GetDomainsInput) (*GetDomainsOutput, error) { - req, out := c.GetDomainsRequest(input) - return out, req.Send() -} - -// GetDomainsWithContext is the same as GetDomains with the addition of -// the ability to pass a context and additional request options. -// -// See GetDomains for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetDomainsWithContext(ctx aws.Context, input *GetDomainsInput, opts ...request.Option) (*GetDomainsOutput, error) { - req, out := c.GetDomainsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstance = "GetInstance" - -// GetInstanceRequest generates a "aws/request.Request" representing the -// client's request for the GetInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstance for more information on using the GetInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceRequest method. -// req, resp := client.GetInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance -func (c *Lightsail) GetInstanceRequest(input *GetInstanceInput) (req *request.Request, output *GetInstanceOutput) { - op := &request.Operation{ - Name: opGetInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceInput{} - } - - output = &GetInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstance API operation for Amazon Lightsail. -// -// Returns information about a specific Amazon Lightsail instance, which is -// a virtual private server. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstance -func (c *Lightsail) GetInstance(input *GetInstanceInput) (*GetInstanceOutput, error) { - req, out := c.GetInstanceRequest(input) - return out, req.Send() -} - -// GetInstanceWithContext is the same as GetInstance with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceWithContext(ctx aws.Context, input *GetInstanceInput, opts ...request.Option) (*GetInstanceOutput, error) { - req, out := c.GetInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceAccessDetails = "GetInstanceAccessDetails" - -// GetInstanceAccessDetailsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceAccessDetails operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceAccessDetails for more information on using the GetInstanceAccessDetails -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceAccessDetailsRequest method. -// req, resp := client.GetInstanceAccessDetailsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails -func (c *Lightsail) GetInstanceAccessDetailsRequest(input *GetInstanceAccessDetailsInput) (req *request.Request, output *GetInstanceAccessDetailsOutput) { - op := &request.Operation{ - Name: opGetInstanceAccessDetails, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceAccessDetailsInput{} - } - - output = &GetInstanceAccessDetailsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceAccessDetails API operation for Amazon Lightsail. -// -// Returns temporary SSH keys you can use to connect to a specific virtual private -// server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceAccessDetails for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceAccessDetails -func (c *Lightsail) GetInstanceAccessDetails(input *GetInstanceAccessDetailsInput) (*GetInstanceAccessDetailsOutput, error) { - req, out := c.GetInstanceAccessDetailsRequest(input) - return out, req.Send() -} - -// GetInstanceAccessDetailsWithContext is the same as GetInstanceAccessDetails with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceAccessDetails for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceAccessDetailsWithContext(ctx aws.Context, input *GetInstanceAccessDetailsInput, opts ...request.Option) (*GetInstanceAccessDetailsOutput, error) { - req, out := c.GetInstanceAccessDetailsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceMetricData = "GetInstanceMetricData" - -// GetInstanceMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceMetricData operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceMetricData for more information on using the GetInstanceMetricData -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceMetricDataRequest method. -// req, resp := client.GetInstanceMetricDataRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData -func (c *Lightsail) GetInstanceMetricDataRequest(input *GetInstanceMetricDataInput) (req *request.Request, output *GetInstanceMetricDataOutput) { - op := &request.Operation{ - Name: opGetInstanceMetricData, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceMetricDataInput{} - } - - output = &GetInstanceMetricDataOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceMetricData API operation for Amazon Lightsail. -// -// Returns the data points for the specified Amazon Lightsail instance metric, -// given an instance name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceMetricData for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceMetricData -func (c *Lightsail) GetInstanceMetricData(input *GetInstanceMetricDataInput) (*GetInstanceMetricDataOutput, error) { - req, out := c.GetInstanceMetricDataRequest(input) - return out, req.Send() -} - -// GetInstanceMetricDataWithContext is the same as GetInstanceMetricData with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceMetricData for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceMetricDataWithContext(ctx aws.Context, input *GetInstanceMetricDataInput, opts ...request.Option) (*GetInstanceMetricDataOutput, error) { - req, out := c.GetInstanceMetricDataRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstancePortStates = "GetInstancePortStates" - -// GetInstancePortStatesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstancePortStates operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstancePortStates for more information on using the GetInstancePortStates -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstancePortStatesRequest method. -// req, resp := client.GetInstancePortStatesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates -func (c *Lightsail) GetInstancePortStatesRequest(input *GetInstancePortStatesInput) (req *request.Request, output *GetInstancePortStatesOutput) { - op := &request.Operation{ - Name: opGetInstancePortStates, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstancePortStatesInput{} - } - - output = &GetInstancePortStatesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstancePortStates API operation for Amazon Lightsail. -// -// Returns the port states for a specific virtual private server, or instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstancePortStates for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstancePortStates -func (c *Lightsail) GetInstancePortStates(input *GetInstancePortStatesInput) (*GetInstancePortStatesOutput, error) { - req, out := c.GetInstancePortStatesRequest(input) - return out, req.Send() -} - -// GetInstancePortStatesWithContext is the same as GetInstancePortStates with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstancePortStates for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstancePortStatesWithContext(ctx aws.Context, input *GetInstancePortStatesInput, opts ...request.Option) (*GetInstancePortStatesOutput, error) { - req, out := c.GetInstancePortStatesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceSnapshot = "GetInstanceSnapshot" - -// GetInstanceSnapshotRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshot operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceSnapshot for more information on using the GetInstanceSnapshot -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceSnapshotRequest method. -// req, resp := client.GetInstanceSnapshotRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot -func (c *Lightsail) GetInstanceSnapshotRequest(input *GetInstanceSnapshotInput) (req *request.Request, output *GetInstanceSnapshotOutput) { - op := &request.Operation{ - Name: opGetInstanceSnapshot, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceSnapshotInput{} - } - - output = &GetInstanceSnapshotOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceSnapshot API operation for Amazon Lightsail. -// -// Returns information about a specific instance snapshot. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceSnapshot for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshot -func (c *Lightsail) GetInstanceSnapshot(input *GetInstanceSnapshotInput) (*GetInstanceSnapshotOutput, error) { - req, out := c.GetInstanceSnapshotRequest(input) - return out, req.Send() -} - -// GetInstanceSnapshotWithContext is the same as GetInstanceSnapshot with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceSnapshot for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceSnapshotWithContext(ctx aws.Context, input *GetInstanceSnapshotInput, opts ...request.Option) (*GetInstanceSnapshotOutput, error) { - req, out := c.GetInstanceSnapshotRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceSnapshots = "GetInstanceSnapshots" - -// GetInstanceSnapshotsRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceSnapshots operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceSnapshots for more information on using the GetInstanceSnapshots -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceSnapshotsRequest method. -// req, resp := client.GetInstanceSnapshotsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots -func (c *Lightsail) GetInstanceSnapshotsRequest(input *GetInstanceSnapshotsInput) (req *request.Request, output *GetInstanceSnapshotsOutput) { - op := &request.Operation{ - Name: opGetInstanceSnapshots, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceSnapshotsInput{} - } - - output = &GetInstanceSnapshotsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceSnapshots API operation for Amazon Lightsail. -// -// Returns all instance snapshots for the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceSnapshots for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceSnapshots -func (c *Lightsail) GetInstanceSnapshots(input *GetInstanceSnapshotsInput) (*GetInstanceSnapshotsOutput, error) { - req, out := c.GetInstanceSnapshotsRequest(input) - return out, req.Send() -} - -// GetInstanceSnapshotsWithContext is the same as GetInstanceSnapshots with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceSnapshots for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceSnapshotsWithContext(ctx aws.Context, input *GetInstanceSnapshotsInput, opts ...request.Option) (*GetInstanceSnapshotsOutput, error) { - req, out := c.GetInstanceSnapshotsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstanceState = "GetInstanceState" - -// GetInstanceStateRequest generates a "aws/request.Request" representing the -// client's request for the GetInstanceState operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstanceState for more information on using the GetInstanceState -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstanceStateRequest method. -// req, resp := client.GetInstanceStateRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState -func (c *Lightsail) GetInstanceStateRequest(input *GetInstanceStateInput) (req *request.Request, output *GetInstanceStateOutput) { - op := &request.Operation{ - Name: opGetInstanceState, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstanceStateInput{} - } - - output = &GetInstanceStateOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstanceState API operation for Amazon Lightsail. -// -// Returns the state of a specific instance. Works on one instance at a time. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstanceState for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstanceState -func (c *Lightsail) GetInstanceState(input *GetInstanceStateInput) (*GetInstanceStateOutput, error) { - req, out := c.GetInstanceStateRequest(input) - return out, req.Send() -} - -// GetInstanceStateWithContext is the same as GetInstanceState with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstanceState for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstanceStateWithContext(ctx aws.Context, input *GetInstanceStateInput, opts ...request.Option) (*GetInstanceStateOutput, error) { - req, out := c.GetInstanceStateRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetInstances = "GetInstances" - -// GetInstancesRequest generates a "aws/request.Request" representing the -// client's request for the GetInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetInstances for more information on using the GetInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetInstancesRequest method. -// req, resp := client.GetInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances -func (c *Lightsail) GetInstancesRequest(input *GetInstancesInput) (req *request.Request, output *GetInstancesOutput) { - op := &request.Operation{ - Name: opGetInstances, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetInstancesInput{} - } - - output = &GetInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetInstances API operation for Amazon Lightsail. -// -// Returns information about all Amazon Lightsail virtual private servers, or -// instances. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetInstances -func (c *Lightsail) GetInstances(input *GetInstancesInput) (*GetInstancesOutput, error) { - req, out := c.GetInstancesRequest(input) - return out, req.Send() -} - -// GetInstancesWithContext is the same as GetInstances with the addition of -// the ability to pass a context and additional request options. -// -// See GetInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetInstancesWithContext(ctx aws.Context, input *GetInstancesInput, opts ...request.Option) (*GetInstancesOutput, error) { - req, out := c.GetInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetKeyPair = "GetKeyPair" - -// GetKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetKeyPair for more information on using the GetKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetKeyPairRequest method. -// req, resp := client.GetKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair -func (c *Lightsail) GetKeyPairRequest(input *GetKeyPairInput) (req *request.Request, output *GetKeyPairOutput) { - op := &request.Operation{ - Name: opGetKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetKeyPairInput{} - } - - output = &GetKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetKeyPair API operation for Amazon Lightsail. -// -// Returns information about a specific key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPair -func (c *Lightsail) GetKeyPair(input *GetKeyPairInput) (*GetKeyPairOutput, error) { - req, out := c.GetKeyPairRequest(input) - return out, req.Send() -} - -// GetKeyPairWithContext is the same as GetKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See GetKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetKeyPairWithContext(ctx aws.Context, input *GetKeyPairInput, opts ...request.Option) (*GetKeyPairOutput, error) { - req, out := c.GetKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetKeyPairs = "GetKeyPairs" - -// GetKeyPairsRequest generates a "aws/request.Request" representing the -// client's request for the GetKeyPairs operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetKeyPairs for more information on using the GetKeyPairs -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetKeyPairsRequest method. -// req, resp := client.GetKeyPairsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs -func (c *Lightsail) GetKeyPairsRequest(input *GetKeyPairsInput) (req *request.Request, output *GetKeyPairsOutput) { - op := &request.Operation{ - Name: opGetKeyPairs, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetKeyPairsInput{} - } - - output = &GetKeyPairsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetKeyPairs API operation for Amazon Lightsail. -// -// Returns information about all key pairs in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetKeyPairs for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetKeyPairs -func (c *Lightsail) GetKeyPairs(input *GetKeyPairsInput) (*GetKeyPairsOutput, error) { - req, out := c.GetKeyPairsRequest(input) - return out, req.Send() -} - -// GetKeyPairsWithContext is the same as GetKeyPairs with the addition of -// the ability to pass a context and additional request options. -// -// See GetKeyPairs for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetKeyPairsWithContext(ctx aws.Context, input *GetKeyPairsInput, opts ...request.Option) (*GetKeyPairsOutput, error) { - req, out := c.GetKeyPairsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancer = "GetLoadBalancer" - -// GetLoadBalancerRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancer for more information on using the GetLoadBalancer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerRequest method. -// req, resp := client.GetLoadBalancerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancerRequest(input *GetLoadBalancerInput) (req *request.Request, output *GetLoadBalancerOutput) { - op := &request.Operation{ - Name: opGetLoadBalancer, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerInput{} - } - - output = &GetLoadBalancerOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancer API operation for Amazon Lightsail. -// -// Returns information about the specified Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancer -func (c *Lightsail) GetLoadBalancer(input *GetLoadBalancerInput) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) - return out, req.Send() -} - -// GetLoadBalancerWithContext is the same as GetLoadBalancer with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerWithContext(ctx aws.Context, input *GetLoadBalancerInput, opts ...request.Option) (*GetLoadBalancerOutput, error) { - req, out := c.GetLoadBalancerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancerMetricData = "GetLoadBalancerMetricData" - -// GetLoadBalancerMetricDataRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerMetricData operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancerMetricData for more information on using the GetLoadBalancerMetricData -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerMetricDataRequest method. -// req, resp := client.GetLoadBalancerMetricDataRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricDataRequest(input *GetLoadBalancerMetricDataInput) (req *request.Request, output *GetLoadBalancerMetricDataOutput) { - op := &request.Operation{ - Name: opGetLoadBalancerMetricData, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerMetricDataInput{} - } - - output = &GetLoadBalancerMetricDataOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancerMetricData API operation for Amazon Lightsail. -// -// Returns information about health metrics for your Lightsail load balancer. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancerMetricData for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerMetricData -func (c *Lightsail) GetLoadBalancerMetricData(input *GetLoadBalancerMetricDataInput) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) - return out, req.Send() -} - -// GetLoadBalancerMetricDataWithContext is the same as GetLoadBalancerMetricData with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancerMetricData for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerMetricDataWithContext(ctx aws.Context, input *GetLoadBalancerMetricDataInput, opts ...request.Option) (*GetLoadBalancerMetricDataOutput, error) { - req, out := c.GetLoadBalancerMetricDataRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancerTlsCertificates = "GetLoadBalancerTlsCertificates" - -// GetLoadBalancerTlsCertificatesRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancerTlsCertificates operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancerTlsCertificates for more information on using the GetLoadBalancerTlsCertificates -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancerTlsCertificatesRequest method. -// req, resp := client.GetLoadBalancerTlsCertificatesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificatesRequest(input *GetLoadBalancerTlsCertificatesInput) (req *request.Request, output *GetLoadBalancerTlsCertificatesOutput) { - op := &request.Operation{ - Name: opGetLoadBalancerTlsCertificates, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancerTlsCertificatesInput{} - } - - output = &GetLoadBalancerTlsCertificatesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancerTlsCertificates API operation for Amazon Lightsail. -// -// Returns information about the TLS certificates that are associated with the -// specified Lightsail load balancer. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -// -// You can have a maximum of 2 certificates associated with a Lightsail load -// balancer. One is active and the other is inactive. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancerTlsCertificates for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancerTlsCertificates -func (c *Lightsail) GetLoadBalancerTlsCertificates(input *GetLoadBalancerTlsCertificatesInput) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) - return out, req.Send() -} - -// GetLoadBalancerTlsCertificatesWithContext is the same as GetLoadBalancerTlsCertificates with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancerTlsCertificates for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancerTlsCertificatesWithContext(ctx aws.Context, input *GetLoadBalancerTlsCertificatesInput, opts ...request.Option) (*GetLoadBalancerTlsCertificatesOutput, error) { - req, out := c.GetLoadBalancerTlsCertificatesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetLoadBalancers = "GetLoadBalancers" - -// GetLoadBalancersRequest generates a "aws/request.Request" representing the -// client's request for the GetLoadBalancers operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetLoadBalancers for more information on using the GetLoadBalancers -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetLoadBalancersRequest method. -// req, resp := client.GetLoadBalancersRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancersRequest(input *GetLoadBalancersInput) (req *request.Request, output *GetLoadBalancersOutput) { - op := &request.Operation{ - Name: opGetLoadBalancers, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetLoadBalancersInput{} - } - - output = &GetLoadBalancersOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetLoadBalancers API operation for Amazon Lightsail. -// -// Returns information about all load balancers in an account. -// -// If you are describing a long list of load balancers, you can paginate the -// output to make the list more manageable. You can use the pageToken and nextPageToken -// values to retrieve the next items in the list. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetLoadBalancers for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetLoadBalancers -func (c *Lightsail) GetLoadBalancers(input *GetLoadBalancersInput) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) - return out, req.Send() -} - -// GetLoadBalancersWithContext is the same as GetLoadBalancers with the addition of -// the ability to pass a context and additional request options. -// -// See GetLoadBalancers for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetLoadBalancersWithContext(ctx aws.Context, input *GetLoadBalancersInput, opts ...request.Option) (*GetLoadBalancersOutput, error) { - req, out := c.GetLoadBalancersRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperation = "GetOperation" - -// GetOperationRequest generates a "aws/request.Request" representing the -// client's request for the GetOperation operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperation for more information on using the GetOperation -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationRequest method. -// req, resp := client.GetOperationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation -func (c *Lightsail) GetOperationRequest(input *GetOperationInput) (req *request.Request, output *GetOperationOutput) { - op := &request.Operation{ - Name: opGetOperation, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationInput{} - } - - output = &GetOperationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperation API operation for Amazon Lightsail. -// -// Returns information about a specific operation. Operations include events -// such as when you create an instance, allocate a static IP, attach a static -// IP, and so on. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperation for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperation -func (c *Lightsail) GetOperation(input *GetOperationInput) (*GetOperationOutput, error) { - req, out := c.GetOperationRequest(input) - return out, req.Send() -} - -// GetOperationWithContext is the same as GetOperation with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperation for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationWithContext(ctx aws.Context, input *GetOperationInput, opts ...request.Option) (*GetOperationOutput, error) { - req, out := c.GetOperationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperations = "GetOperations" - -// GetOperationsRequest generates a "aws/request.Request" representing the -// client's request for the GetOperations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperations for more information on using the GetOperations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationsRequest method. -// req, resp := client.GetOperationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations -func (c *Lightsail) GetOperationsRequest(input *GetOperationsInput) (req *request.Request, output *GetOperationsOutput) { - op := &request.Operation{ - Name: opGetOperations, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationsInput{} - } - - output = &GetOperationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperations API operation for Amazon Lightsail. -// -// Returns information about all operations. -// -// Results are returned from oldest to newest, up to a maximum of 200. Results -// can be paged by making each subsequent call to GetOperations use the maximum -// (last) statusChangedAt value from the previous request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperations -func (c *Lightsail) GetOperations(input *GetOperationsInput) (*GetOperationsOutput, error) { - req, out := c.GetOperationsRequest(input) - return out, req.Send() -} - -// GetOperationsWithContext is the same as GetOperations with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationsWithContext(ctx aws.Context, input *GetOperationsInput, opts ...request.Option) (*GetOperationsOutput, error) { - req, out := c.GetOperationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetOperationsForResource = "GetOperationsForResource" - -// GetOperationsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the GetOperationsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetOperationsForResource for more information on using the GetOperationsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetOperationsForResourceRequest method. -// req, resp := client.GetOperationsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource -func (c *Lightsail) GetOperationsForResourceRequest(input *GetOperationsForResourceInput) (req *request.Request, output *GetOperationsForResourceOutput) { - op := &request.Operation{ - Name: opGetOperationsForResource, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetOperationsForResourceInput{} - } - - output = &GetOperationsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetOperationsForResource API operation for Amazon Lightsail. -// -// Gets operations for a specific resource (e.g., an instance or a static IP). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetOperationsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetOperationsForResource -func (c *Lightsail) GetOperationsForResource(input *GetOperationsForResourceInput) (*GetOperationsForResourceOutput, error) { - req, out := c.GetOperationsForResourceRequest(input) - return out, req.Send() -} - -// GetOperationsForResourceWithContext is the same as GetOperationsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See GetOperationsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetOperationsForResourceWithContext(ctx aws.Context, input *GetOperationsForResourceInput, opts ...request.Option) (*GetOperationsForResourceOutput, error) { - req, out := c.GetOperationsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetRegions = "GetRegions" - -// GetRegionsRequest generates a "aws/request.Request" representing the -// client's request for the GetRegions operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetRegions for more information on using the GetRegions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetRegionsRequest method. -// req, resp := client.GetRegionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions -func (c *Lightsail) GetRegionsRequest(input *GetRegionsInput) (req *request.Request, output *GetRegionsOutput) { - op := &request.Operation{ - Name: opGetRegions, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetRegionsInput{} - } - - output = &GetRegionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetRegions API operation for Amazon Lightsail. -// -// Returns a list of all valid regions for Amazon Lightsail. Use the include -// availability zones parameter to also return the availability zones in a region. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetRegions for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetRegions -func (c *Lightsail) GetRegions(input *GetRegionsInput) (*GetRegionsOutput, error) { - req, out := c.GetRegionsRequest(input) - return out, req.Send() -} - -// GetRegionsWithContext is the same as GetRegions with the addition of -// the ability to pass a context and additional request options. -// -// See GetRegions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetRegionsWithContext(ctx aws.Context, input *GetRegionsInput, opts ...request.Option) (*GetRegionsOutput, error) { - req, out := c.GetRegionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetStaticIp = "GetStaticIp" - -// GetStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetStaticIp for more information on using the GetStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetStaticIpRequest method. -// req, resp := client.GetStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp -func (c *Lightsail) GetStaticIpRequest(input *GetStaticIpInput) (req *request.Request, output *GetStaticIpOutput) { - op := &request.Operation{ - Name: opGetStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetStaticIpInput{} - } - - output = &GetStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetStaticIp API operation for Amazon Lightsail. -// -// Returns information about a specific static IP. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIp -func (c *Lightsail) GetStaticIp(input *GetStaticIpInput) (*GetStaticIpOutput, error) { - req, out := c.GetStaticIpRequest(input) - return out, req.Send() -} - -// GetStaticIpWithContext is the same as GetStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See GetStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetStaticIpWithContext(ctx aws.Context, input *GetStaticIpInput, opts ...request.Option) (*GetStaticIpOutput, error) { - req, out := c.GetStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetStaticIps = "GetStaticIps" - -// GetStaticIpsRequest generates a "aws/request.Request" representing the -// client's request for the GetStaticIps operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetStaticIps for more information on using the GetStaticIps -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetStaticIpsRequest method. -// req, resp := client.GetStaticIpsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps -func (c *Lightsail) GetStaticIpsRequest(input *GetStaticIpsInput) (req *request.Request, output *GetStaticIpsOutput) { - op := &request.Operation{ - Name: opGetStaticIps, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetStaticIpsInput{} - } - - output = &GetStaticIpsOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetStaticIps API operation for Amazon Lightsail. -// -// Returns information about all static IPs in the user's account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation GetStaticIps for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/GetStaticIps -func (c *Lightsail) GetStaticIps(input *GetStaticIpsInput) (*GetStaticIpsOutput, error) { - req, out := c.GetStaticIpsRequest(input) - return out, req.Send() -} - -// GetStaticIpsWithContext is the same as GetStaticIps with the addition of -// the ability to pass a context and additional request options. -// -// See GetStaticIps for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) GetStaticIpsWithContext(ctx aws.Context, input *GetStaticIpsInput, opts ...request.Option) (*GetStaticIpsOutput, error) { - req, out := c.GetStaticIpsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opImportKeyPair = "ImportKeyPair" - -// ImportKeyPairRequest generates a "aws/request.Request" representing the -// client's request for the ImportKeyPair operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ImportKeyPair for more information on using the ImportKeyPair -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ImportKeyPairRequest method. -// req, resp := client.ImportKeyPairRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair -func (c *Lightsail) ImportKeyPairRequest(input *ImportKeyPairInput) (req *request.Request, output *ImportKeyPairOutput) { - op := &request.Operation{ - Name: opImportKeyPair, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ImportKeyPairInput{} - } - - output = &ImportKeyPairOutput{} - req = c.newRequest(op, input, output) - return -} - -// ImportKeyPair API operation for Amazon Lightsail. -// -// Imports a public SSH key from a specific key pair. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation ImportKeyPair for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ImportKeyPair -func (c *Lightsail) ImportKeyPair(input *ImportKeyPairInput) (*ImportKeyPairOutput, error) { - req, out := c.ImportKeyPairRequest(input) - return out, req.Send() -} - -// ImportKeyPairWithContext is the same as ImportKeyPair with the addition of -// the ability to pass a context and additional request options. -// -// See ImportKeyPair for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) ImportKeyPairWithContext(ctx aws.Context, input *ImportKeyPairInput, opts ...request.Option) (*ImportKeyPairOutput, error) { - req, out := c.ImportKeyPairRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opIsVpcPeered = "IsVpcPeered" - -// IsVpcPeeredRequest generates a "aws/request.Request" representing the -// client's request for the IsVpcPeered operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See IsVpcPeered for more information on using the IsVpcPeered -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the IsVpcPeeredRequest method. -// req, resp := client.IsVpcPeeredRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered -func (c *Lightsail) IsVpcPeeredRequest(input *IsVpcPeeredInput) (req *request.Request, output *IsVpcPeeredOutput) { - op := &request.Operation{ - Name: opIsVpcPeered, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &IsVpcPeeredInput{} - } - - output = &IsVpcPeeredOutput{} - req = c.newRequest(op, input, output) - return -} - -// IsVpcPeered API operation for Amazon Lightsail. -// -// Returns a Boolean value indicating whether your Lightsail VPC is peered. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation IsVpcPeered for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/IsVpcPeered -func (c *Lightsail) IsVpcPeered(input *IsVpcPeeredInput) (*IsVpcPeeredOutput, error) { - req, out := c.IsVpcPeeredRequest(input) - return out, req.Send() -} - -// IsVpcPeeredWithContext is the same as IsVpcPeered with the addition of -// the ability to pass a context and additional request options. -// -// See IsVpcPeered for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) IsVpcPeeredWithContext(ctx aws.Context, input *IsVpcPeeredInput, opts ...request.Option) (*IsVpcPeeredOutput, error) { - req, out := c.IsVpcPeeredRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opOpenInstancePublicPorts = "OpenInstancePublicPorts" - -// OpenInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the OpenInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See OpenInstancePublicPorts for more information on using the OpenInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the OpenInstancePublicPortsRequest method. -// req, resp := client.OpenInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts -func (c *Lightsail) OpenInstancePublicPortsRequest(input *OpenInstancePublicPortsInput) (req *request.Request, output *OpenInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opOpenInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &OpenInstancePublicPortsInput{} - } - - output = &OpenInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// OpenInstancePublicPorts API operation for Amazon Lightsail. -// -// Adds public ports to an Amazon Lightsail instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation OpenInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/OpenInstancePublicPorts -func (c *Lightsail) OpenInstancePublicPorts(input *OpenInstancePublicPortsInput) (*OpenInstancePublicPortsOutput, error) { - req, out := c.OpenInstancePublicPortsRequest(input) - return out, req.Send() -} - -// OpenInstancePublicPortsWithContext is the same as OpenInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See OpenInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) OpenInstancePublicPortsWithContext(ctx aws.Context, input *OpenInstancePublicPortsInput, opts ...request.Option) (*OpenInstancePublicPortsOutput, error) { - req, out := c.OpenInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPeerVpc = "PeerVpc" - -// PeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the PeerVpc operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PeerVpc for more information on using the PeerVpc -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PeerVpcRequest method. -// req, resp := client.PeerVpcRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc -func (c *Lightsail) PeerVpcRequest(input *PeerVpcInput) (req *request.Request, output *PeerVpcOutput) { - op := &request.Operation{ - Name: opPeerVpc, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PeerVpcInput{} - } - - output = &PeerVpcOutput{} - req = c.newRequest(op, input, output) - return -} - -// PeerVpc API operation for Amazon Lightsail. -// -// Tries to peer the Lightsail VPC with the user's default VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation PeerVpc for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PeerVpc -func (c *Lightsail) PeerVpc(input *PeerVpcInput) (*PeerVpcOutput, error) { - req, out := c.PeerVpcRequest(input) - return out, req.Send() -} - -// PeerVpcWithContext is the same as PeerVpc with the addition of -// the ability to pass a context and additional request options. -// -// See PeerVpc for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) PeerVpcWithContext(ctx aws.Context, input *PeerVpcInput, opts ...request.Option) (*PeerVpcOutput, error) { - req, out := c.PeerVpcRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opPutInstancePublicPorts = "PutInstancePublicPorts" - -// PutInstancePublicPortsRequest generates a "aws/request.Request" representing the -// client's request for the PutInstancePublicPorts operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See PutInstancePublicPorts for more information on using the PutInstancePublicPorts -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the PutInstancePublicPortsRequest method. -// req, resp := client.PutInstancePublicPortsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPortsRequest(input *PutInstancePublicPortsInput) (req *request.Request, output *PutInstancePublicPortsOutput) { - op := &request.Operation{ - Name: opPutInstancePublicPorts, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &PutInstancePublicPortsInput{} - } - - output = &PutInstancePublicPortsOutput{} - req = c.newRequest(op, input, output) - return -} - -// PutInstancePublicPorts API operation for Amazon Lightsail. -// -// Sets the specified open ports for an Amazon Lightsail instance, and closes -// all ports for every protocol not included in the current request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation PutInstancePublicPorts for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/PutInstancePublicPorts -func (c *Lightsail) PutInstancePublicPorts(input *PutInstancePublicPortsInput) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) - return out, req.Send() -} - -// PutInstancePublicPortsWithContext is the same as PutInstancePublicPorts with the addition of -// the ability to pass a context and additional request options. -// -// See PutInstancePublicPorts for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) PutInstancePublicPortsWithContext(ctx aws.Context, input *PutInstancePublicPortsInput, opts ...request.Option) (*PutInstancePublicPortsOutput, error) { - req, out := c.PutInstancePublicPortsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opRebootInstance = "RebootInstance" - -// RebootInstanceRequest generates a "aws/request.Request" representing the -// client's request for the RebootInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See RebootInstance for more information on using the RebootInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the RebootInstanceRequest method. -// req, resp := client.RebootInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance -func (c *Lightsail) RebootInstanceRequest(input *RebootInstanceInput) (req *request.Request, output *RebootInstanceOutput) { - op := &request.Operation{ - Name: opRebootInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &RebootInstanceInput{} - } - - output = &RebootInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// RebootInstance API operation for Amazon Lightsail. -// -// Restarts a specific instance. When your Amazon Lightsail instance is finished -// rebooting, Lightsail assigns a new public IP address. To use the same IP -// address after restarting, create a static IP address and attach it to the -// instance. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation RebootInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/RebootInstance -func (c *Lightsail) RebootInstance(input *RebootInstanceInput) (*RebootInstanceOutput, error) { - req, out := c.RebootInstanceRequest(input) - return out, req.Send() -} - -// RebootInstanceWithContext is the same as RebootInstance with the addition of -// the ability to pass a context and additional request options. -// -// See RebootInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) RebootInstanceWithContext(ctx aws.Context, input *RebootInstanceInput, opts ...request.Option) (*RebootInstanceOutput, error) { - req, out := c.RebootInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opReleaseStaticIp = "ReleaseStaticIp" - -// ReleaseStaticIpRequest generates a "aws/request.Request" representing the -// client's request for the ReleaseStaticIp operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ReleaseStaticIp for more information on using the ReleaseStaticIp -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ReleaseStaticIpRequest method. -// req, resp := client.ReleaseStaticIpRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp -func (c *Lightsail) ReleaseStaticIpRequest(input *ReleaseStaticIpInput) (req *request.Request, output *ReleaseStaticIpOutput) { - op := &request.Operation{ - Name: opReleaseStaticIp, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &ReleaseStaticIpInput{} - } - - output = &ReleaseStaticIpOutput{} - req = c.newRequest(op, input, output) - return -} - -// ReleaseStaticIp API operation for Amazon Lightsail. -// -// Deletes a specific static IP from your account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation ReleaseStaticIp for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/ReleaseStaticIp -func (c *Lightsail) ReleaseStaticIp(input *ReleaseStaticIpInput) (*ReleaseStaticIpOutput, error) { - req, out := c.ReleaseStaticIpRequest(input) - return out, req.Send() -} - -// ReleaseStaticIpWithContext is the same as ReleaseStaticIp with the addition of -// the ability to pass a context and additional request options. -// -// See ReleaseStaticIp for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) ReleaseStaticIpWithContext(ctx aws.Context, input *ReleaseStaticIpInput, opts ...request.Option) (*ReleaseStaticIpOutput, error) { - req, out := c.ReleaseStaticIpRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStartInstance = "StartInstance" - -// StartInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StartInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StartInstance for more information on using the StartInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the StartInstanceRequest method. -// req, resp := client.StartInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance -func (c *Lightsail) StartInstanceRequest(input *StartInstanceInput) (req *request.Request, output *StartInstanceOutput) { - op := &request.Operation{ - Name: opStartInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StartInstanceInput{} - } - - output = &StartInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// StartInstance API operation for Amazon Lightsail. -// -// Starts a specific Amazon Lightsail instance from a stopped state. To restart -// an instance, use the reboot instance operation. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation StartInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StartInstance -func (c *Lightsail) StartInstance(input *StartInstanceInput) (*StartInstanceOutput, error) { - req, out := c.StartInstanceRequest(input) - return out, req.Send() -} - -// StartInstanceWithContext is the same as StartInstance with the addition of -// the ability to pass a context and additional request options. -// -// See StartInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) StartInstanceWithContext(ctx aws.Context, input *StartInstanceInput, opts ...request.Option) (*StartInstanceOutput, error) { - req, out := c.StartInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opStopInstance = "StopInstance" - -// StopInstanceRequest generates a "aws/request.Request" representing the -// client's request for the StopInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See StopInstance for more information on using the StopInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the StopInstanceRequest method. -// req, resp := client.StopInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance -func (c *Lightsail) StopInstanceRequest(input *StopInstanceInput) (req *request.Request, output *StopInstanceOutput) { - op := &request.Operation{ - Name: opStopInstance, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &StopInstanceInput{} - } - - output = &StopInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// StopInstance API operation for Amazon Lightsail. -// -// Stops a specific Amazon Lightsail instance that is currently running. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation StopInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/StopInstance -func (c *Lightsail) StopInstance(input *StopInstanceInput) (*StopInstanceOutput, error) { - req, out := c.StopInstanceRequest(input) - return out, req.Send() -} - -// StopInstanceWithContext is the same as StopInstance with the addition of -// the ability to pass a context and additional request options. -// -// See StopInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) StopInstanceWithContext(ctx aws.Context, input *StopInstanceInput, opts ...request.Option) (*StopInstanceOutput, error) { - req, out := c.StopInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUnpeerVpc = "UnpeerVpc" - -// UnpeerVpcRequest generates a "aws/request.Request" representing the -// client's request for the UnpeerVpc operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UnpeerVpc for more information on using the UnpeerVpc -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UnpeerVpcRequest method. -// req, resp := client.UnpeerVpcRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc -func (c *Lightsail) UnpeerVpcRequest(input *UnpeerVpcInput) (req *request.Request, output *UnpeerVpcOutput) { - op := &request.Operation{ - Name: opUnpeerVpc, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UnpeerVpcInput{} - } - - output = &UnpeerVpcOutput{} - req = c.newRequest(op, input, output) - return -} - -// UnpeerVpc API operation for Amazon Lightsail. -// -// Attempts to unpeer the Lightsail VPC from the user's default VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UnpeerVpc for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UnpeerVpc -func (c *Lightsail) UnpeerVpc(input *UnpeerVpcInput) (*UnpeerVpcOutput, error) { - req, out := c.UnpeerVpcRequest(input) - return out, req.Send() -} - -// UnpeerVpcWithContext is the same as UnpeerVpc with the addition of -// the ability to pass a context and additional request options. -// -// See UnpeerVpc for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UnpeerVpcWithContext(ctx aws.Context, input *UnpeerVpcInput, opts ...request.Option) (*UnpeerVpcOutput, error) { - req, out := c.UnpeerVpcRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateDomainEntry = "UpdateDomainEntry" - -// UpdateDomainEntryRequest generates a "aws/request.Request" representing the -// client's request for the UpdateDomainEntry operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateDomainEntry for more information on using the UpdateDomainEntry -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateDomainEntryRequest method. -// req, resp := client.UpdateDomainEntryRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry -func (c *Lightsail) UpdateDomainEntryRequest(input *UpdateDomainEntryInput) (req *request.Request, output *UpdateDomainEntryOutput) { - op := &request.Operation{ - Name: opUpdateDomainEntry, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateDomainEntryInput{} - } - - output = &UpdateDomainEntryOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateDomainEntry API operation for Amazon Lightsail. -// -// Updates a domain recordset after it is created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateDomainEntry for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateDomainEntry -func (c *Lightsail) UpdateDomainEntry(input *UpdateDomainEntryInput) (*UpdateDomainEntryOutput, error) { - req, out := c.UpdateDomainEntryRequest(input) - return out, req.Send() -} - -// UpdateDomainEntryWithContext is the same as UpdateDomainEntry with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateDomainEntry for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UpdateDomainEntryWithContext(ctx aws.Context, input *UpdateDomainEntryInput, opts ...request.Option) (*UpdateDomainEntryOutput, error) { - req, out := c.UpdateDomainEntryRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" - -// UpdateLoadBalancerAttributeRequest generates a "aws/request.Request" representing the -// client's request for the UpdateLoadBalancerAttribute operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateLoadBalancerAttribute for more information on using the UpdateLoadBalancerAttribute -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateLoadBalancerAttributeRequest method. -// req, resp := client.UpdateLoadBalancerAttributeRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttributeRequest(input *UpdateLoadBalancerAttributeInput) (req *request.Request, output *UpdateLoadBalancerAttributeOutput) { - op := &request.Operation{ - Name: opUpdateLoadBalancerAttribute, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &UpdateLoadBalancerAttributeInput{} - } - - output = &UpdateLoadBalancerAttributeOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateLoadBalancerAttribute API operation for Amazon Lightsail. -// -// Updates the specified attribute for a load balancer. You can only update -// one attribute at a time. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Lightsail's -// API operation UpdateLoadBalancerAttribute for usage and error information. -// -// Returned Error Codes: -// * ErrCodeServiceException "ServiceException" -// A general service exception. -// -// * ErrCodeInvalidInputException "InvalidInputException" -// Lightsail throws this exception when user input does not conform to the validation -// rules of an input field. -// -// Domain-related APIs are only available in the N. Virginia (us-east-1) Region. -// Please set your AWS Region configuration to us-east-1 to create, view, or -// edit these resources. -// -// * ErrCodeNotFoundException "NotFoundException" -// Lightsail throws this exception when it cannot find a resource. -// -// * ErrCodeOperationFailureException "OperationFailureException" -// Lightsail throws this exception when an operation fails to execute. -// -// * ErrCodeAccessDeniedException "AccessDeniedException" -// Lightsail throws this exception when the user cannot be authenticated or -// uses invalid credentials to access a resource. -// -// * ErrCodeAccountSetupInProgressException "AccountSetupInProgressException" -// Lightsail throws this exception when an account is still in the setup in -// progress state. -// -// * ErrCodeUnauthenticatedException "UnauthenticatedException" -// Lightsail throws this exception when the user has not been authenticated. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28/UpdateLoadBalancerAttribute -func (c *Lightsail) UpdateLoadBalancerAttribute(input *UpdateLoadBalancerAttributeInput) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) - return out, req.Send() -} - -// UpdateLoadBalancerAttributeWithContext is the same as UpdateLoadBalancerAttribute with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateLoadBalancerAttribute for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Lightsail) UpdateLoadBalancerAttributeWithContext(ctx aws.Context, input *UpdateLoadBalancerAttributeInput, opts ...request.Option) (*UpdateLoadBalancerAttributeOutput, error) { - req, out := c.UpdateLoadBalancerAttributeRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type AllocateStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP address. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AllocateStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AllocateStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AllocateStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AllocateStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *AllocateStaticIpInput) SetStaticIpName(v string) *AllocateStaticIpInput { - s.StaticIpName = &v - return s -} - -type AllocateStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the static IP address - // you allocated. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AllocateStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AllocateStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AllocateStaticIpOutput) SetOperations(v []*Operation) *AllocateStaticIpOutput { - s.Operations = v - return s -} - -type AttachDiskInput struct { - _ struct{} `type:"structure"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The disk path to expose to the instance (e.g., /dev/xvdf). - // - // DiskPath is a required field - DiskPath *string `locationName:"diskPath" type:"string" required:"true"` - - // The name of the Lightsail instance where you want to utilize the storage - // disk. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskPath == nil { - invalidParams.Add(request.NewErrParamRequired("DiskPath")) - } - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *AttachDiskInput) SetDiskName(v string) *AttachDiskInput { - s.DiskName = &v - return s -} - -// SetDiskPath sets the DiskPath field's value. -func (s *AttachDiskInput) SetDiskPath(v string) *AttachDiskInput { - s.DiskPath = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *AttachDiskInput) SetInstanceName(v string) *AttachDiskInput { - s.InstanceName = &v - return s -} - -type AttachDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachDiskOutput) SetOperations(v []*Operation) *AttachDiskOutput { - s.Operations = v - return s -} - -type AttachInstancesToLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // An array of strings representing the instance name(s) you want to attach - // to your load balancer. - // - // An instance must be running before you can attach it to your load balancer. - // - // There are no additional limits on the number of instances you can attach - // to your load balancer, aside from the limit of Lightsail instances you can - // create in your account (20). - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachInstancesToLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachInstancesToLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachInstancesToLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachInstancesToLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *AttachInstancesToLoadBalancerInput) SetInstanceNames(v []*string) *AttachInstancesToLoadBalancerInput { - s.InstanceNames = v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachInstancesToLoadBalancerInput) SetLoadBalancerName(v string) *AttachInstancesToLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type AttachInstancesToLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object representing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachInstancesToLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachInstancesToLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachInstancesToLoadBalancerOutput) SetOperations(v []*Operation) *AttachInstancesToLoadBalancerOutput { - s.Operations = v - return s -} - -type AttachLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // The name of your SSL/TLS certificate. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // The name of the load balancer to which you want to associate the SSL/TLS - // certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateName sets the CertificateName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetCertificateName(v string) *AttachLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *AttachLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *AttachLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type AttachLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object representing the API operations. - // - // These SSL/TLS certificates are only usable by Lightsail load balancers. You - // can't get the certificate and use it for another purpose. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *AttachLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type AttachStaticIpInput struct { - _ struct{} `type:"structure"` - - // The instance name to which you want to attach the static IP address. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The name of the static IP. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s AttachStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AttachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AttachStaticIpInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *AttachStaticIpInput) SetInstanceName(v string) *AttachStaticIpInput { - s.InstanceName = &v - return s -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *AttachStaticIpInput) SetStaticIpName(v string) *AttachStaticIpInput { - s.StaticIpName = &v - return s -} - -type AttachStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s AttachStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AttachStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *AttachStaticIpOutput) SetOperations(v []*Operation) *AttachStaticIpOutput { - s.Operations = v - return s -} - -// Describes an Availability Zone. -type AvailabilityZone struct { - _ struct{} `type:"structure"` - - // The state of the Availability Zone. - State *string `locationName:"state" type:"string"` - - // The name of the Availability Zone. The format is us-east-2a (case-sensitive). - ZoneName *string `locationName:"zoneName" type:"string"` -} - -// String returns the string representation -func (s AvailabilityZone) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AvailabilityZone) GoString() string { - return s.String() -} - -// SetState sets the State field's value. -func (s *AvailabilityZone) SetState(v string) *AvailabilityZone { - s.State = &v - return s -} - -// SetZoneName sets the ZoneName field's value. -func (s *AvailabilityZone) SetZoneName(v string) *AvailabilityZone { - s.ZoneName = &v - return s -} - -// Describes a blueprint (a virtual private server image). -type Blueprint struct { - _ struct{} `type:"structure"` - - // The ID for the virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - BlueprintId *string `locationName:"blueprintId" type:"string"` - - // The description of the blueprint. - Description *string `locationName:"description" type:"string"` - - // The group name of the blueprint (e.g., amazon-linux). - Group *string `locationName:"group" type:"string"` - - // A Boolean value indicating whether the blueprint is active. When you update - // your blueprints, you will inactivate old blueprints and keep the most recent - // versions active. - IsActive *bool `locationName:"isActive" type:"boolean"` - - // The end-user license agreement URL for the image or blueprint. - LicenseUrl *string `locationName:"licenseUrl" type:"string"` - - // The minimum bundle power required to run this blueprint. For example, you - // need a bundle with a power value of 500 or more to create an instance that - // uses a blueprint with a minimum power value of 500. 0 indicates that the - // blueprint runs on all instance sizes. - MinPower *int64 `locationName:"minPower" type:"integer"` - - // The friendly name of the blueprint (e.g., Amazon Linux). - Name *string `locationName:"name" type:"string"` - - // The operating system platform (either Linux/Unix-based or Windows Server-based) - // of the blueprint. - Platform *string `locationName:"platform" type:"string" enum:"InstancePlatform"` - - // The product URL to learn more about the image or blueprint. - ProductUrl *string `locationName:"productUrl" type:"string"` - - // The type of the blueprint (e.g., os or app). - Type *string `locationName:"type" type:"string" enum:"BlueprintType"` - - // The version number of the operating system, application, or stack (e.g., - // 2016.03.0). - Version *string `locationName:"version" type:"string"` - - // The version code. - VersionCode *string `locationName:"versionCode" type:"string"` -} - -// String returns the string representation -func (s Blueprint) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Blueprint) GoString() string { - return s.String() -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *Blueprint) SetBlueprintId(v string) *Blueprint { - s.BlueprintId = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Blueprint) SetDescription(v string) *Blueprint { - s.Description = &v - return s -} - -// SetGroup sets the Group field's value. -func (s *Blueprint) SetGroup(v string) *Blueprint { - s.Group = &v - return s -} - -// SetIsActive sets the IsActive field's value. -func (s *Blueprint) SetIsActive(v bool) *Blueprint { - s.IsActive = &v - return s -} - -// SetLicenseUrl sets the LicenseUrl field's value. -func (s *Blueprint) SetLicenseUrl(v string) *Blueprint { - s.LicenseUrl = &v - return s -} - -// SetMinPower sets the MinPower field's value. -func (s *Blueprint) SetMinPower(v int64) *Blueprint { - s.MinPower = &v - return s -} - -// SetName sets the Name field's value. -func (s *Blueprint) SetName(v string) *Blueprint { - s.Name = &v - return s -} - -// SetPlatform sets the Platform field's value. -func (s *Blueprint) SetPlatform(v string) *Blueprint { - s.Platform = &v - return s -} - -// SetProductUrl sets the ProductUrl field's value. -func (s *Blueprint) SetProductUrl(v string) *Blueprint { - s.ProductUrl = &v - return s -} - -// SetType sets the Type field's value. -func (s *Blueprint) SetType(v string) *Blueprint { - s.Type = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *Blueprint) SetVersion(v string) *Blueprint { - s.Version = &v - return s -} - -// SetVersionCode sets the VersionCode field's value. -func (s *Blueprint) SetVersionCode(v string) *Blueprint { - s.VersionCode = &v - return s -} - -// Describes a bundle, which is a set of specs describing your virtual private -// server (or instance). -type Bundle struct { - _ struct{} `type:"structure"` - - // The bundle ID (e.g., micro_1_0). - BundleId *string `locationName:"bundleId" type:"string"` - - // The number of vCPUs included in the bundle (e.g., 2). - CpuCount *int64 `locationName:"cpuCount" type:"integer"` - - // The size of the SSD (e.g., 30). - DiskSizeInGb *int64 `locationName:"diskSizeInGb" type:"integer"` - - // The Amazon EC2 instance type (e.g., t2.micro). - InstanceType *string `locationName:"instanceType" type:"string"` - - // A Boolean value indicating whether the bundle is active. - IsActive *bool `locationName:"isActive" type:"boolean"` - - // A friendly name for the bundle (e.g., Micro). - Name *string `locationName:"name" type:"string"` - - // A numeric value that represents the power of the bundle (e.g., 500). You - // can use the bundle's power value in conjunction with a blueprint's minimum - // power value to determine whether the blueprint will run on the bundle. For - // example, you need a bundle with a power value of 500 or more to create an - // instance that uses a blueprint with a minimum power value of 500. - Power *int64 `locationName:"power" type:"integer"` - - // The price in US dollars (e.g., 5.0). - Price *float64 `locationName:"price" type:"float"` - - // The amount of RAM in GB (e.g., 2.0). - RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` - - // The operating system platform (Linux/Unix-based or Windows Server-based) - // that the bundle supports. You can only launch a WINDOWS bundle on a blueprint - // that supports the WINDOWS platform. LINUX_UNIX blueprints require a LINUX_UNIX - // bundle. - SupportedPlatforms []*string `locationName:"supportedPlatforms" type:"list"` - - // The data transfer rate per month in GB (e.g., 2000). - TransferPerMonthInGb *int64 `locationName:"transferPerMonthInGb" type:"integer"` -} - -// String returns the string representation -func (s Bundle) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Bundle) GoString() string { - return s.String() -} - -// SetBundleId sets the BundleId field's value. -func (s *Bundle) SetBundleId(v string) *Bundle { - s.BundleId = &v - return s -} - -// SetCpuCount sets the CpuCount field's value. -func (s *Bundle) SetCpuCount(v int64) *Bundle { - s.CpuCount = &v - return s -} - -// SetDiskSizeInGb sets the DiskSizeInGb field's value. -func (s *Bundle) SetDiskSizeInGb(v int64) *Bundle { - s.DiskSizeInGb = &v - return s -} - -// SetInstanceType sets the InstanceType field's value. -func (s *Bundle) SetInstanceType(v string) *Bundle { - s.InstanceType = &v - return s -} - -// SetIsActive sets the IsActive field's value. -func (s *Bundle) SetIsActive(v bool) *Bundle { - s.IsActive = &v - return s -} - -// SetName sets the Name field's value. -func (s *Bundle) SetName(v string) *Bundle { - s.Name = &v - return s -} - -// SetPower sets the Power field's value. -func (s *Bundle) SetPower(v int64) *Bundle { - s.Power = &v - return s -} - -// SetPrice sets the Price field's value. -func (s *Bundle) SetPrice(v float64) *Bundle { - s.Price = &v - return s -} - -// SetRamSizeInGb sets the RamSizeInGb field's value. -func (s *Bundle) SetRamSizeInGb(v float64) *Bundle { - s.RamSizeInGb = &v - return s -} - -// SetSupportedPlatforms sets the SupportedPlatforms field's value. -func (s *Bundle) SetSupportedPlatforms(v []*string) *Bundle { - s.SupportedPlatforms = v - return s -} - -// SetTransferPerMonthInGb sets the TransferPerMonthInGb field's value. -func (s *Bundle) SetTransferPerMonthInGb(v int64) *Bundle { - s.TransferPerMonthInGb = &v - return s -} - -type CloseInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance on which you're attempting to close the public ports. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // Information about the public port you are trying to close. - // - // PortInfo is a required field - PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` -} - -// String returns the string representation -func (s CloseInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloseInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CloseInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CloseInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfo == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfo")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CloseInstancePublicPortsInput) SetInstanceName(v string) *CloseInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfo sets the PortInfo field's value. -func (s *CloseInstancePublicPortsInput) SetPortInfo(v *PortInfo) *CloseInstancePublicPortsInput { - s.PortInfo = v - return s -} - -type CloseInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CloseInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloseInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CloseInstancePublicPortsOutput) SetOperation(v *Operation) *CloseInstancePublicPortsOutput { - s.Operation = v - return s -} - -type CreateDiskFromSnapshotInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. - // - // Use the GetRegions operation to list the Availability Zones where Lightsail - // is currently available. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The name of the disk snapshot (e.g., my-snapshot) from which to create the - // new storage disk. - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` - - // The size of the disk in GB (e.g., 32). - // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateDiskFromSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskFromSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskFromSnapshotInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskFromSnapshotInput) SetAvailabilityZone(v string) *CreateDiskFromSnapshotInput { - s.AvailabilityZone = &v - return s -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskName(v string) *CreateDiskFromSnapshotInput { - s.DiskName = &v - return s -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskFromSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskFromSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskFromSnapshotInput) SetSizeInGb(v int64) *CreateDiskFromSnapshotInput { - s.SizeInGb = &v - return s -} - -type CreateDiskFromSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskFromSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskFromSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskFromSnapshotOutput) SetOperations(v []*Operation) *CreateDiskFromSnapshotOutput { - s.Operations = v - return s -} - -type CreateDiskInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone where you want to create the disk (e.g., us-east-2a). - // Choose the same Availability Zone as the Lightsail instance where you want - // to create the disk. - // - // Use the GetRegions operation to list the Availability Zones where Lightsail - // is currently available. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The unique Lightsail disk name (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The size of the disk in GB (e.g., 32). - // - // SizeInGb is a required field - SizeInGb *int64 `locationName:"sizeInGb" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.SizeInGb == nil { - invalidParams.Add(request.NewErrParamRequired("SizeInGb")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateDiskInput) SetAvailabilityZone(v string) *CreateDiskInput { - s.AvailabilityZone = &v - return s -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskInput) SetDiskName(v string) *CreateDiskInput { - s.DiskName = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *CreateDiskInput) SetSizeInGb(v int64) *CreateDiskInput { - s.SizeInGb = &v - return s -} - -type CreateDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskOutput) SetOperations(v []*Operation) *CreateDiskOutput { - s.Operations = v - return s -} - -type CreateDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The unique name of the source disk (e.g., my-source-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` - - // The name of the destination disk snapshot (e.g., my-disk-snapshot) based - // on the source disk. - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDiskSnapshotInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *CreateDiskSnapshotInput) SetDiskName(v string) *CreateDiskSnapshotInput { - s.DiskName = &v - return s -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *CreateDiskSnapshotInput) SetDiskSnapshotName(v string) *CreateDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type CreateDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateDiskSnapshotOutput) SetOperations(v []*Operation) *CreateDiskSnapshotOutput { - s.Operations = v - return s -} - -type CreateDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain entry - // request. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The domain name (e.g., example.com) for which you want to create the domain - // entry. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *CreateDomainEntryInput) SetDomainEntry(v *DomainEntry) *CreateDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainEntryInput) SetDomainName(v string) *CreateDomainEntryInput { - s.DomainName = &v - return s -} - -type CreateDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CreateDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CreateDomainEntryOutput) SetOperation(v *Operation) *CreateDomainEntryOutput { - s.Operation = v - return s -} - -type CreateDomainInput struct { - _ struct{} `type:"structure"` - - // The domain name to manage (e.g., example.com). - // - // You cannot register a new domain name using Lightsail. You must register - // a domain name using Amazon Route 53 or another domain name registrar. If - // you have already registered your domain, you can enter its name in this parameter - // to manage the DNS records for that domain. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *CreateDomainInput) SetDomainName(v string) *CreateDomainInput { - s.DomainName = &v - return s -} - -type CreateDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain resource - // you created. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s CreateDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateDomainOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *CreateDomainOutput) SetOperation(v *Operation) *CreateDomainOutput { - s.Operation = v - return s -} - -type CreateInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The Lightsail instance on which to base your snapshot. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The name for your new snapshot. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstanceSnapshotInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceName(v string) *CreateInstanceSnapshotInput { - s.InstanceName = &v - return s -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstanceSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type CreateInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstanceSnapshotOutput) SetOperations(v []*Operation) *CreateInstanceSnapshotOutput { - s.Operations = v - return s -} - -type CreateInstancesFromSnapshotInput struct { - _ struct{} `type:"structure"` - - // An object containing information about one or more disk mappings. - AttachedDiskMapping map[string][]*DiskMap `locationName:"attachedDiskMapping" type:"map"` - - // The Availability Zone where you want to create your instances. Use the following - // formatting: us-east-2a (case sensitive). You can get a list of availability - // zones by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include availability zones parameter to your - // request. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). - // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` - - // The names for your new instances. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the instance snapshot on which you are basing your new instances. - // Use the get instance snapshots operation to return information about your - // existing snapshots. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` - - // The name for your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` - - // You can create a launch script that configures a server with additional user - // data. For example, apt-get -y update. - // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (http://lightsail.aws.amazon.com/ls/docs/getting-started/articles/pre-installed-apps). - UserData *string `locationName:"userData" type:"string"` -} - -// String returns the string representation -func (s CreateInstancesFromSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesFromSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesFromSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesFromSnapshotInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) - } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAttachedDiskMapping sets the AttachedDiskMapping field's value. -func (s *CreateInstancesFromSnapshotInput) SetAttachedDiskMapping(v map[string][]*DiskMap) *CreateInstancesFromSnapshotInput { - s.AttachedDiskMapping = v - return s -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesFromSnapshotInput) SetAvailabilityZone(v string) *CreateInstancesFromSnapshotInput { - s.AvailabilityZone = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesFromSnapshotInput) SetBundleId(v string) *CreateInstancesFromSnapshotInput { - s.BundleId = &v - return s -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceNames(v []*string) *CreateInstancesFromSnapshotInput { - s.InstanceNames = v - return s -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *CreateInstancesFromSnapshotInput) SetInstanceSnapshotName(v string) *CreateInstancesFromSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesFromSnapshotInput) SetKeyPairName(v string) *CreateInstancesFromSnapshotInput { - s.KeyPairName = &v - return s -} - -// SetUserData sets the UserData field's value. -func (s *CreateInstancesFromSnapshotInput) SetUserData(v string) *CreateInstancesFromSnapshotInput { - s.UserData = &v - return s -} - -type CreateInstancesFromSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances from snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstancesFromSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesFromSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstancesFromSnapshotOutput) SetOperations(v []*Operation) *CreateInstancesFromSnapshotOutput { - s.Operations = v - return s -} - -type CreateInstancesInput struct { - _ struct{} `type:"structure"` - - // The Availability Zone in which to create your instance. Use the following - // format: us-east-2a (case sensitive). You can get a list of availability zones - // by using the get regions (http://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRegions.html) - // operation. Be sure to add the include availability zones parameter to your - // request. - // - // AvailabilityZone is a required field - AvailabilityZone *string `locationName:"availabilityZone" type:"string" required:"true"` - - // The ID for a virtual private server image (e.g., app_wordpress_4_4 or app_lamp_7_0). - // Use the get blueprints operation to return a list of available images (or - // blueprints). - // - // BlueprintId is a required field - BlueprintId *string `locationName:"blueprintId" type:"string" required:"true"` - - // The bundle of specification information for your virtual private server (or - // instance), including the pricing plan (e.g., micro_1_0). - // - // BundleId is a required field - BundleId *string `locationName:"bundleId" type:"string" required:"true"` - - // (Deprecated) The name for your custom image. - // - // In releases prior to June 12, 2017, this parameter was ignored by the API. - // It is now deprecated. - CustomImageName *string `locationName:"customImageName" deprecated:"true" type:"string"` - - // The names to use for your new Lightsail instances. Separate multiple values - // using quotation marks and commas, for example: ["MyFirstInstance","MySecondInstance"] - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of your key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` - - // A launch script you can create that configures a server with additional user - // data. For example, you might want to run apt-get -y update. - // - // Depending on the machine image you choose, the command to get software on - // your instance varies. Amazon Linux and CentOS use yum, Debian and Ubuntu - // use apt-get, and FreeBSD uses pkg. For a complete list, see the Dev Guide - // (https://lightsail.aws.amazon.com/ls/docs/getting-started/article/compare-options-choose-lightsail-instance-image). - UserData *string `locationName:"userData" type:"string"` -} - -// String returns the string representation -func (s CreateInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateInstancesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateInstancesInput"} - if s.AvailabilityZone == nil { - invalidParams.Add(request.NewErrParamRequired("AvailabilityZone")) - } - if s.BlueprintId == nil { - invalidParams.Add(request.NewErrParamRequired("BlueprintId")) - } - if s.BundleId == nil { - invalidParams.Add(request.NewErrParamRequired("BundleId")) - } - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *CreateInstancesInput) SetAvailabilityZone(v string) *CreateInstancesInput { - s.AvailabilityZone = &v - return s -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *CreateInstancesInput) SetBlueprintId(v string) *CreateInstancesInput { - s.BlueprintId = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *CreateInstancesInput) SetBundleId(v string) *CreateInstancesInput { - s.BundleId = &v - return s -} - -// SetCustomImageName sets the CustomImageName field's value. -func (s *CreateInstancesInput) SetCustomImageName(v string) *CreateInstancesInput { - s.CustomImageName = &v - return s -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *CreateInstancesInput) SetInstanceNames(v []*string) *CreateInstancesInput { - s.InstanceNames = v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateInstancesInput) SetKeyPairName(v string) *CreateInstancesInput { - s.KeyPairName = &v - return s -} - -// SetUserData sets the UserData field's value. -func (s *CreateInstancesInput) SetUserData(v string) *CreateInstancesInput { - s.UserData = &v - return s -} - -type CreateInstancesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create instances request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateInstancesOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateInstancesOutput) SetOperations(v []*Operation) *CreateInstancesOutput { - s.Operations = v - return s -} - -type CreateKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name for your new key pair. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *CreateKeyPairInput) SetKeyPairName(v string) *CreateKeyPairInput { - s.KeyPairName = &v - return s -} - -type CreateKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the new key pair - // you just created. - KeyPair *KeyPair `locationName:"keyPair" type:"structure"` - - // An array of key-value pairs containing information about the results of your - // create key pair request. - Operation *Operation `locationName:"operation" type:"structure"` - - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` -} - -// String returns the string representation -func (s CreateKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateKeyPairOutput) GoString() string { - return s.String() -} - -// SetKeyPair sets the KeyPair field's value. -func (s *CreateKeyPairOutput) SetKeyPair(v *KeyPair) *CreateKeyPairOutput { - s.KeyPair = v - return s -} - -// SetOperation sets the Operation field's value. -func (s *CreateKeyPairOutput) SetOperation(v *Operation) *CreateKeyPairOutput { - s.Operation = v - return s -} - -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPrivateKeyBase64(v string) *CreateKeyPairOutput { - s.PrivateKeyBase64 = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *CreateKeyPairOutput) SetPublicKeyBase64(v string) *CreateKeyPairOutput { - s.PublicKeyBase64 = &v - return s -} - -type CreateLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The optional alternative domains and subdomains to use with your SSL/TLS - // certificate (e.g., www.example.com, example.com, m.example.com, blog.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - - // The domain name with which your certificate is associated (e.g., example.com). - // - // If you specify certificateDomainName, then certificateName is required (and - // vice-versa). - CertificateDomainName *string `locationName:"certificateDomainName" type:"string"` - - // The name of the SSL/TLS certificate. - // - // If you specify certificateName, then certificateDomainName is required (and - // vice-versa). - CertificateName *string `locationName:"certificateName" type:"string"` - - // The path you provided to perform the load balancer health check. If you didn't - // specify a health check path, Lightsail uses the root path of your website - // (e.g., "/"). - // - // You may want to specify a custom health check path other than the root of - // your application if your home page loads slowly or has a lot of media or - // scripting on it. - HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` - - // The instance port where you're creating your load balancer. - // - // InstancePort is a required field - InstancePort *int64 `locationName:"instancePort" type:"integer" required:"true"` - - // The name of your load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerInput"} - if s.InstancePort == nil { - invalidParams.Add(request.NewErrParamRequired("InstancePort")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerInput) SetCertificateDomainName(v string) *CreateLoadBalancerInput { - s.CertificateDomainName = &v - return s -} - -// SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerInput) SetCertificateName(v string) *CreateLoadBalancerInput { - s.CertificateName = &v - return s -} - -// SetHealthCheckPath sets the HealthCheckPath field's value. -func (s *CreateLoadBalancerInput) SetHealthCheckPath(v string) *CreateLoadBalancerInput { - s.HealthCheckPath = &v - return s -} - -// SetInstancePort sets the InstancePort field's value. -func (s *CreateLoadBalancerInput) SetInstancePort(v int64) *CreateLoadBalancerInput { - s.InstancePort = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerInput) SetLoadBalancerName(v string) *CreateLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type CreateLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerOutput) SetOperations(v []*Operation) *CreateLoadBalancerOutput { - s.Operations = v - return s -} - -type CreateLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // An array of strings listing alternative domains and subdomains for your SSL/TLS - // certificate. Lightsail will de-dupe the names for you. You can have a maximum - // of 9 alternative names (in addition to the 1 primary domain). We do not support - // wildcards (e.g., *.example.com). - CertificateAlternativeNames []*string `locationName:"certificateAlternativeNames" type:"list"` - - // The domain name (e.g., example.com) for your SSL/TLS certificate. - // - // CertificateDomainName is a required field - CertificateDomainName *string `locationName:"certificateDomainName" type:"string" required:"true"` - - // The SSL/TLS certificate name. - // - // You can have up to 10 certificates in your account at one time. Each Lightsail - // load balancer can have up to 2 certificates associated with it at one time. - // There is also an overall limit to the number of certificates that can be - // issue in a 365-day period. For more information, see Limits (http://docs.aws.amazon.com/acm/latest/userguide/acm-limits.html). - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // The load balancer name where you want to create the SSL/TLS certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateLoadBalancerTlsCertificateInput"} - if s.CertificateDomainName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateDomainName")) - } - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateAlternativeNames sets the CertificateAlternativeNames field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateAlternativeNames(v []*string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateAlternativeNames = v - return s -} - -// SetCertificateDomainName sets the CertificateDomainName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateDomainName(v string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateDomainName = &v - return s -} - -// SetCertificateName sets the CertificateName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetCertificateName(v string) *CreateLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *CreateLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *CreateLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type CreateLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *CreateLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *CreateLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type DeleteDiskInput struct { - _ struct{} `type:"structure"` - - // The unique name of the disk you want to delete (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *DeleteDiskInput) SetDiskName(v string) *DeleteDiskInput { - s.DiskName = &v - return s -} - -type DeleteDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteDiskOutput) SetOperations(v []*Operation) *DeleteDiskOutput { - s.Operations = v - return s -} - -type DeleteDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the disk snapshot you want to delete (e.g., my-disk-snapshot). - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *DeleteDiskSnapshotInput) SetDiskSnapshotName(v string) *DeleteDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type DeleteDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteDiskSnapshotOutput) SetOperations(v []*Operation) *DeleteDiskSnapshotOutput { - s.Operations = v - return s -} - -type DeleteDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your domain entries. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The name of the domain entry to delete. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *DeleteDomainEntryInput) SetDomainEntry(v *DomainEntry) *DeleteDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainEntryInput) SetDomainName(v string) *DeleteDomainEntryInput { - s.DomainName = &v - return s -} - -type DeleteDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete domain entry request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteDomainEntryOutput) SetOperation(v *Operation) *DeleteDomainEntryOutput { - s.Operation = v - return s -} - -type DeleteDomainInput struct { - _ struct{} `type:"structure"` - - // The specific domain name to delete. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *DeleteDomainInput) SetDomainName(v string) *DeleteDomainInput { - s.DomainName = &v - return s -} - -type DeleteDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete domain request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteDomainOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteDomainOutput) SetOperation(v *Operation) *DeleteDomainOutput { - s.Operation = v - return s -} - -type DeleteInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to delete. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *DeleteInstanceInput) SetInstanceName(v string) *DeleteInstanceInput { - s.InstanceName = &v - return s -} - -type DeleteInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete instance request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteInstanceOutput) SetOperations(v []*Operation) *DeleteInstanceOutput { - s.Operations = v - return s -} - -type DeleteInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the snapshot to delete. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteInstanceSnapshotInput"} - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *DeleteInstanceSnapshotInput) SetInstanceSnapshotName(v string) *DeleteInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type DeleteInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete instance snapshot request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteInstanceSnapshotOutput) SetOperations(v []*Operation) *DeleteInstanceSnapshotOutput { - s.Operations = v - return s -} - -type DeleteKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair to delete. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *DeleteKeyPairInput) SetKeyPairName(v string) *DeleteKeyPairInput { - s.KeyPairName = &v - return s -} - -type DeleteKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // delete key pair request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s DeleteKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteKeyPairOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *DeleteKeyPairOutput) SetOperation(v *Operation) *DeleteKeyPairOutput { - s.Operation = v - return s -} - -type DeleteLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer you want to delete. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerInput) SetLoadBalancerName(v string) *DeleteLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type DeleteLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerOutput) SetOperations(v []*Operation) *DeleteLoadBalancerOutput { - s.Operations = v - return s -} - -type DeleteLoadBalancerTlsCertificateInput struct { - _ struct{} `type:"structure"` - - // The SSL/TLS certificate name. - // - // CertificateName is a required field - CertificateName *string `locationName:"certificateName" type:"string" required:"true"` - - // When true, forces the deletion of an SSL/TLS certificate. - // - // There can be two certificates associated with a Lightsail load balancer: - // the primary and the backup. The force parameter is required when the primary - // SSL/TLS certificate is in use by an instance attached to the load balancer. - Force *bool `locationName:"force" type:"boolean"` - - // The load balancer name. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteLoadBalancerTlsCertificateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteLoadBalancerTlsCertificateInput"} - if s.CertificateName == nil { - invalidParams.Add(request.NewErrParamRequired("CertificateName")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCertificateName sets the CertificateName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetCertificateName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.CertificateName = &v - return s -} - -// SetForce sets the Force field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetForce(v bool) *DeleteLoadBalancerTlsCertificateInput { - s.Force = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DeleteLoadBalancerTlsCertificateInput) SetLoadBalancerName(v string) *DeleteLoadBalancerTlsCertificateInput { - s.LoadBalancerName = &v - return s -} - -type DeleteLoadBalancerTlsCertificateOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteLoadBalancerTlsCertificateOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DeleteLoadBalancerTlsCertificateOutput) SetOperations(v []*Operation) *DeleteLoadBalancerTlsCertificateOutput { - s.Operations = v - return s -} - -type DetachDiskInput struct { - _ struct{} `type:"structure"` - - // The unique name of the disk you want to detach from your instance (e.g., - // my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *DetachDiskInput) SetDiskName(v string) *DetachDiskInput { - s.DiskName = &v - return s -} - -type DetachDiskOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachDiskOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachDiskOutput) SetOperations(v []*Operation) *DetachDiskOutput { - s.Operations = v - return s -} - -type DetachInstancesFromLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // An array of strings containing the names of the instances you want to detach - // from the load balancer. - // - // InstanceNames is a required field - InstanceNames []*string `locationName:"instanceNames" type:"list" required:"true"` - - // The name of the Lightsail load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachInstancesFromLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachInstancesFromLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachInstancesFromLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachInstancesFromLoadBalancerInput"} - if s.InstanceNames == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceNames")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceNames sets the InstanceNames field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetInstanceNames(v []*string) *DetachInstancesFromLoadBalancerInput { - s.InstanceNames = v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *DetachInstancesFromLoadBalancerInput) SetLoadBalancerName(v string) *DetachInstancesFromLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type DetachInstancesFromLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachInstancesFromLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachInstancesFromLoadBalancerOutput) SetOperations(v []*Operation) *DetachInstancesFromLoadBalancerOutput { - s.Operations = v - return s -} - -type DetachStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP to detach from the instance. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s DetachStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DetachStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DetachStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *DetachStaticIpInput) SetStaticIpName(v string) *DetachStaticIpInput { - s.StaticIpName = &v - return s -} - -type DetachStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // detach static IP request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s DetachStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DetachStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *DetachStaticIpOutput) SetOperations(v []*Operation) *DetachStaticIpOutput { - s.Operations = v - return s -} - -// Describes a system disk or an block storage disk. -type Disk struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the disk. - Arn *string `locationName:"arn" type:"string"` - - // The resources to which the disk is attached. - AttachedTo *string `locationName:"attachedTo" type:"string"` - - // (Deprecated) The attachment state of the disk. - // - // In releases prior to November 14, 2017, this parameter returned attached - // for system disks in the API response. It is now deprecated, but still included - // in the response. Use isAttached instead. - AttachmentState *string `locationName:"attachmentState" deprecated:"true" type:"string"` - - // The date when the disk was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // (Deprecated) The number of GB in use by the disk. - // - // In releases prior to November 14, 2017, this parameter was not included in - // the API response. It is now deprecated. - GbInUse *int64 `locationName:"gbInUse" deprecated:"true" type:"integer"` - - // The input/output operations per second (IOPS) of the disk. - Iops *int64 `locationName:"iops" type:"integer"` - - // A Boolean value indicating whether the disk is attached. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // A Boolean value indicating whether this disk is a system disk (has an operating - // system loaded on it). - IsSystemDisk *bool `locationName:"isSystemDisk" type:"boolean"` - - // The AWS Region and Availability Zone where the disk is located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The unique name of the disk. - Name *string `locationName:"name" type:"string"` - - // The disk path. - Path *string `locationName:"path" type:"string"` - - // The Lightsail resource type (e.g., Disk). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // Describes the status of the disk. - State *string `locationName:"state" type:"string" enum:"DiskState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s Disk) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Disk) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Disk) SetArn(v string) *Disk { - s.Arn = &v - return s -} - -// SetAttachedTo sets the AttachedTo field's value. -func (s *Disk) SetAttachedTo(v string) *Disk { - s.AttachedTo = &v - return s -} - -// SetAttachmentState sets the AttachmentState field's value. -func (s *Disk) SetAttachmentState(v string) *Disk { - s.AttachmentState = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Disk) SetCreatedAt(v time.Time) *Disk { - s.CreatedAt = &v - return s -} - -// SetGbInUse sets the GbInUse field's value. -func (s *Disk) SetGbInUse(v int64) *Disk { - s.GbInUse = &v - return s -} - -// SetIops sets the Iops field's value. -func (s *Disk) SetIops(v int64) *Disk { - s.Iops = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *Disk) SetIsAttached(v bool) *Disk { - s.IsAttached = &v - return s -} - -// SetIsSystemDisk sets the IsSystemDisk field's value. -func (s *Disk) SetIsSystemDisk(v bool) *Disk { - s.IsSystemDisk = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Disk) SetLocation(v *ResourceLocation) *Disk { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Disk) SetName(v string) *Disk { - s.Name = &v - return s -} - -// SetPath sets the Path field's value. -func (s *Disk) SetPath(v string) *Disk { - s.Path = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Disk) SetResourceType(v string) *Disk { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *Disk) SetSizeInGb(v int64) *Disk { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *Disk) SetState(v string) *Disk { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Disk) SetSupportCode(v string) *Disk { - s.SupportCode = &v - return s -} - -// Describes a block storage disk mapping. -type DiskMap struct { - _ struct{} `type:"structure"` - - // The new disk name (e.g., my-new-disk). - NewDiskName *string `locationName:"newDiskName" type:"string"` - - // The original disk path exposed to the instance (for example, /dev/sdh). - OriginalDiskPath *string `locationName:"originalDiskPath" type:"string"` -} - -// String returns the string representation -func (s DiskMap) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DiskMap) GoString() string { - return s.String() -} - -// SetNewDiskName sets the NewDiskName field's value. -func (s *DiskMap) SetNewDiskName(v string) *DiskMap { - s.NewDiskName = &v - return s -} - -// SetOriginalDiskPath sets the OriginalDiskPath field's value. -func (s *DiskMap) SetOriginalDiskPath(v string) *DiskMap { - s.OriginalDiskPath = &v - return s -} - -// Describes a block storage disk snapshot. -type DiskSnapshot struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the disk snapshot. - Arn *string `locationName:"arn" type:"string"` - - // The date when the disk snapshot was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The Amazon Resource Name (ARN) of the source disk from which you are creating - // the disk snapshot. - FromDiskArn *string `locationName:"fromDiskArn" type:"string"` - - // The unique name of the source disk from which you are creating the disk snapshot. - FromDiskName *string `locationName:"fromDiskName" type:"string"` - - // The AWS Region and Availability Zone where the disk snapshot was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the disk snapshot (e.g., my-disk-snapshot). - Name *string `locationName:"name" type:"string"` - - // The progress of the disk snapshot operation. - Progress *string `locationName:"progress" type:"string"` - - // The Lightsail resource type (e.g., DiskSnapshot). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size of the disk in GB. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // The status of the disk snapshot operation. - State *string `locationName:"state" type:"string" enum:"DiskSnapshotState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s DiskSnapshot) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DiskSnapshot) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *DiskSnapshot) SetArn(v string) *DiskSnapshot { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *DiskSnapshot) SetCreatedAt(v time.Time) *DiskSnapshot { - s.CreatedAt = &v - return s -} - -// SetFromDiskArn sets the FromDiskArn field's value. -func (s *DiskSnapshot) SetFromDiskArn(v string) *DiskSnapshot { - s.FromDiskArn = &v - return s -} - -// SetFromDiskName sets the FromDiskName field's value. -func (s *DiskSnapshot) SetFromDiskName(v string) *DiskSnapshot { - s.FromDiskName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *DiskSnapshot) SetLocation(v *ResourceLocation) *DiskSnapshot { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *DiskSnapshot) SetName(v string) *DiskSnapshot { - s.Name = &v - return s -} - -// SetProgress sets the Progress field's value. -func (s *DiskSnapshot) SetProgress(v string) *DiskSnapshot { - s.Progress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *DiskSnapshot) SetResourceType(v string) *DiskSnapshot { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *DiskSnapshot) SetSizeInGb(v int64) *DiskSnapshot { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *DiskSnapshot) SetState(v string) *DiskSnapshot { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *DiskSnapshot) SetSupportCode(v string) *DiskSnapshot { - s.SupportCode = &v - return s -} - -// Describes a domain where you are storing recordsets in Lightsail. -type Domain struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the domain recordset (e.g., arn:aws:lightsail:global:123456789101:Domain/824cede0-abc7-4f84-8dbc-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The date when the domain recordset was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // An array of key-value pairs containing information about the domain entries. - DomainEntries []*DomainEntry `locationName:"domainEntries" type:"list"` - - // The AWS Region and Availability Zones where the domain recordset was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the domain. - Name *string `locationName:"name" type:"string"` - - // The resource type. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s Domain) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Domain) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Domain) SetArn(v string) *Domain { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Domain) SetCreatedAt(v time.Time) *Domain { - s.CreatedAt = &v - return s -} - -// SetDomainEntries sets the DomainEntries field's value. -func (s *Domain) SetDomainEntries(v []*DomainEntry) *Domain { - s.DomainEntries = v - return s -} - -// SetLocation sets the Location field's value. -func (s *Domain) SetLocation(v *ResourceLocation) *Domain { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Domain) SetName(v string) *Domain { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Domain) SetResourceType(v string) *Domain { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Domain) SetSupportCode(v string) *Domain { - s.SupportCode = &v - return s -} - -// Describes a domain recordset entry. -type DomainEntry struct { - _ struct{} `type:"structure"` - - // The ID of the domain recordset entry. - Id *string `locationName:"id" type:"string"` - - // When true, specifies whether the domain entry is an alias used by the Lightsail - // load balancer. You can include an alias (A type) record in your request, - // which points to a load balancer DNS name and routes traffic to your load - // balancer - IsAlias *bool `locationName:"isAlias" type:"boolean"` - - // The name of the domain. - Name *string `locationName:"name" type:"string"` - - // (Deprecated) The options for the domain entry. - // - // In releases prior to November 29, 2017, this parameter was not included in - // the API response. It is now deprecated. - Options map[string]*string `locationName:"options" deprecated:"true" type:"map"` - - // The target AWS name server (e.g., ns-111.awsdns-22.com.). - // - // For Lightsail load balancers, the value looks like ab1234c56789c6b86aba6fb203d443bc-123456789.us-east-2.elb.amazonaws.com. - // Be sure to also set isAlias to true when setting up an A record for a load - // balancer. - Target *string `locationName:"target" type:"string"` - - // The type of domain entry (e.g., SOA or NS). - Type *string `locationName:"type" type:"string"` -} - -// String returns the string representation -func (s DomainEntry) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DomainEntry) GoString() string { - return s.String() -} - -// SetId sets the Id field's value. -func (s *DomainEntry) SetId(v string) *DomainEntry { - s.Id = &v - return s -} - -// SetIsAlias sets the IsAlias field's value. -func (s *DomainEntry) SetIsAlias(v bool) *DomainEntry { - s.IsAlias = &v - return s -} - -// SetName sets the Name field's value. -func (s *DomainEntry) SetName(v string) *DomainEntry { - s.Name = &v - return s -} - -// SetOptions sets the Options field's value. -func (s *DomainEntry) SetOptions(v map[string]*string) *DomainEntry { - s.Options = v - return s -} - -// SetTarget sets the Target field's value. -func (s *DomainEntry) SetTarget(v string) *DomainEntry { - s.Target = &v - return s -} - -// SetType sets the Type field's value. -func (s *DomainEntry) SetType(v string) *DomainEntry { - s.Type = &v - return s -} - -type DownloadDefaultKeyPairInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DownloadDefaultKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DownloadDefaultKeyPairInput) GoString() string { - return s.String() -} - -type DownloadDefaultKeyPairOutput struct { - _ struct{} `type:"structure"` - - // A base64-encoded RSA private key. - PrivateKeyBase64 *string `locationName:"privateKeyBase64" type:"string"` - - // A base64-encoded public key of the ssh-rsa type. - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string"` -} - -// String returns the string representation -func (s DownloadDefaultKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DownloadDefaultKeyPairOutput) GoString() string { - return s.String() -} - -// SetPrivateKeyBase64 sets the PrivateKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPrivateKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PrivateKeyBase64 = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *DownloadDefaultKeyPairOutput) SetPublicKeyBase64(v string) *DownloadDefaultKeyPairOutput { - s.PublicKeyBase64 = &v - return s -} - -type GetActiveNamesInput struct { - _ struct{} `type:"structure"` - - // A token used for paginating results from your get active names request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetActiveNamesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetActiveNamesInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetActiveNamesInput) SetPageToken(v string) *GetActiveNamesInput { - s.PageToken = &v - return s -} - -type GetActiveNamesOutput struct { - _ struct{} `type:"structure"` - - // The list of active names returned by the get active names request. - ActiveNames []*string `locationName:"activeNames" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetActiveNamesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetActiveNamesOutput) GoString() string { - return s.String() -} - -// SetActiveNames sets the ActiveNames field's value. -func (s *GetActiveNamesOutput) SetActiveNames(v []*string) *GetActiveNamesOutput { - s.ActiveNames = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetActiveNamesOutput) SetNextPageToken(v string) *GetActiveNamesOutput { - s.NextPageToken = &v - return s -} - -type GetBlueprintsInput struct { - _ struct{} `type:"structure"` - - // A Boolean value indicating whether to include inactive results in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - - // A token used for advancing to the next page of results from your get blueprints - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetBlueprintsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBlueprintsInput) GoString() string { - return s.String() -} - -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBlueprintsInput) SetIncludeInactive(v bool) *GetBlueprintsInput { - s.IncludeInactive = &v - return s -} - -// SetPageToken sets the PageToken field's value. -func (s *GetBlueprintsInput) SetPageToken(v string) *GetBlueprintsInput { - s.PageToken = &v - return s -} - -type GetBlueprintsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the available - // blueprints. - Blueprints []*Blueprint `locationName:"blueprints" type:"list"` - - // A token used for advancing to the next page of results from your get blueprints - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetBlueprintsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBlueprintsOutput) GoString() string { - return s.String() -} - -// SetBlueprints sets the Blueprints field's value. -func (s *GetBlueprintsOutput) SetBlueprints(v []*Blueprint) *GetBlueprintsOutput { - s.Blueprints = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetBlueprintsOutput) SetNextPageToken(v string) *GetBlueprintsOutput { - s.NextPageToken = &v - return s -} - -type GetBundlesInput struct { - _ struct{} `type:"structure"` - - // A Boolean value that indicates whether to include inactive bundle results - // in your request. - IncludeInactive *bool `locationName:"includeInactive" type:"boolean"` - - // A token used for advancing to the next page of results from your get bundles - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetBundlesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBundlesInput) GoString() string { - return s.String() -} - -// SetIncludeInactive sets the IncludeInactive field's value. -func (s *GetBundlesInput) SetIncludeInactive(v bool) *GetBundlesInput { - s.IncludeInactive = &v - return s -} - -// SetPageToken sets the PageToken field's value. -func (s *GetBundlesInput) SetPageToken(v string) *GetBundlesInput { - s.PageToken = &v - return s -} - -type GetBundlesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs that contains information about the available - // bundles. - Bundles []*Bundle `locationName:"bundles" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetBundlesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetBundlesOutput) GoString() string { - return s.String() -} - -// SetBundles sets the Bundles field's value. -func (s *GetBundlesOutput) SetBundles(v []*Bundle) *GetBundlesOutput { - s.Bundles = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetBundlesOutput) SetNextPageToken(v string) *GetBundlesOutput { - s.NextPageToken = &v - return s -} - -type GetDiskInput struct { - _ struct{} `type:"structure"` - - // The name of the disk (e.g., my-disk). - // - // DiskName is a required field - DiskName *string `locationName:"diskName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDiskInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskInput"} - if s.DiskName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskName sets the DiskName field's value. -func (s *GetDiskInput) SetDiskName(v string) *GetDiskInput { - s.DiskName = &v - return s -} - -type GetDiskOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the disk. - Disk *Disk `locationName:"disk" type:"structure"` -} - -// String returns the string representation -func (s GetDiskOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskOutput) GoString() string { - return s.String() -} - -// SetDisk sets the Disk field's value. -func (s *GetDiskOutput) SetDisk(v *Disk) *GetDiskOutput { - s.Disk = v - return s -} - -type GetDiskSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the disk snapshot (e.g., my-disk-snapshot). - // - // DiskSnapshotName is a required field - DiskSnapshotName *string `locationName:"diskSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDiskSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDiskSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDiskSnapshotInput"} - if s.DiskSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("DiskSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDiskSnapshotName sets the DiskSnapshotName field's value. -func (s *GetDiskSnapshotInput) SetDiskSnapshotName(v string) *GetDiskSnapshotInput { - s.DiskSnapshotName = &v - return s -} - -type GetDiskSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about the disk snapshot. - DiskSnapshot *DiskSnapshot `locationName:"diskSnapshot" type:"structure"` -} - -// String returns the string representation -func (s GetDiskSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotOutput) GoString() string { - return s.String() -} - -// SetDiskSnapshot sets the DiskSnapshot field's value. -func (s *GetDiskSnapshotOutput) SetDiskSnapshot(v *DiskSnapshot) *GetDiskSnapshotOutput { - s.DiskSnapshot = v - return s -} - -type GetDiskSnapshotsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your GetDiskSnapshots - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDiskSnapshotsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDiskSnapshotsInput) SetPageToken(v string) *GetDiskSnapshotsInput { - s.PageToken = &v - return s -} - -type GetDiskSnapshotsOutput struct { - _ struct{} `type:"structure"` - - // An array of objects containing information about all block storage disk snapshots. - DiskSnapshots []*DiskSnapshot `locationName:"diskSnapshots" type:"list"` - - // A token used for advancing to the next page of results from your GetDiskSnapshots - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDiskSnapshotsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDiskSnapshotsOutput) GoString() string { - return s.String() -} - -// SetDiskSnapshots sets the DiskSnapshots field's value. -func (s *GetDiskSnapshotsOutput) SetDiskSnapshots(v []*DiskSnapshot) *GetDiskSnapshotsOutput { - s.DiskSnapshots = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDiskSnapshotsOutput) SetNextPageToken(v string) *GetDiskSnapshotsOutput { - s.NextPageToken = &v - return s -} - -type GetDisksInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your GetDisks - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDisksInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDisksInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDisksInput) SetPageToken(v string) *GetDisksInput { - s.PageToken = &v - return s -} - -type GetDisksOutput struct { - _ struct{} `type:"structure"` - - // An array of objects containing information about all block storage disks. - Disks []*Disk `locationName:"disks" type:"list"` - - // A token used for advancing to the next page of results from your GetDisks - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDisksOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDisksOutput) GoString() string { - return s.String() -} - -// SetDisks sets the Disks field's value. -func (s *GetDisksOutput) SetDisks(v []*Disk) *GetDisksOutput { - s.Disks = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDisksOutput) SetNextPageToken(v string) *GetDisksOutput { - s.NextPageToken = &v - return s -} - -type GetDomainInput struct { - _ struct{} `type:"structure"` - - // The domain name for which your want to return information about. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetDomainInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetDomainInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetDomainInput"} - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainName sets the DomainName field's value. -func (s *GetDomainInput) SetDomainName(v string) *GetDomainInput { - s.DomainName = &v - return s -} - -type GetDomainOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your get domain - // request. - Domain *Domain `locationName:"domain" type:"structure"` -} - -// String returns the string representation -func (s GetDomainOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainOutput) GoString() string { - return s.String() -} - -// SetDomain sets the Domain field's value. -func (s *GetDomainOutput) SetDomain(v *Domain) *GetDomainOutput { - s.Domain = v - return s -} - -type GetDomainsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get domains - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetDomainsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetDomainsInput) SetPageToken(v string) *GetDomainsInput { - s.PageToken = &v - return s -} - -type GetDomainsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about each of the domain - // entries in the user's account. - Domains []*Domain `locationName:"domains" type:"list"` - - // A token used for advancing to the next page of results from your get active - // names request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetDomainsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetDomainsOutput) GoString() string { - return s.String() -} - -// SetDomains sets the Domains field's value. -func (s *GetDomainsOutput) SetDomains(v []*Domain) *GetDomainsOutput { - s.Domains = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetDomainsOutput) SetNextPageToken(v string) *GetDomainsOutput { - s.NextPageToken = &v - return s -} - -type GetInstanceAccessDetailsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to access. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The protocol to use to connect to your instance. Defaults to ssh. - Protocol *string `locationName:"protocol" type:"string" enum:"InstanceAccessProtocol"` -} - -// String returns the string representation -func (s GetInstanceAccessDetailsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceAccessDetailsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceAccessDetailsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceAccessDetailsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceAccessDetailsInput) SetInstanceName(v string) *GetInstanceAccessDetailsInput { - s.InstanceName = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *GetInstanceAccessDetailsInput) SetProtocol(v string) *GetInstanceAccessDetailsInput { - s.Protocol = &v - return s -} - -type GetInstanceAccessDetailsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about a get instance access - // request. - AccessDetails *InstanceAccessDetails `locationName:"accessDetails" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceAccessDetailsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceAccessDetailsOutput) GoString() string { - return s.String() -} - -// SetAccessDetails sets the AccessDetails field's value. -func (s *GetInstanceAccessDetailsOutput) SetAccessDetails(v *InstanceAccessDetails) *GetInstanceAccessDetailsOutput { - s.AccessDetails = v - return s -} - -type GetInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceInput) SetInstanceName(v string) *GetInstanceInput { - s.InstanceName = &v - return s -} - -type GetInstanceMetricDataInput struct { - _ struct{} `type:"structure"` - - // The end time of the time period. - // - // EndTime is a required field - EndTime *time.Time `locationName:"endTime" type:"timestamp" timestampFormat:"unix" required:"true"` - - // The name of the instance for which you want to get metrics data. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // The metric name to get data about. - // - // MetricName is a required field - MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"InstanceMetricName"` - - // The time period for which you are requesting data. - // - // Period is a required field - Period *int64 `locationName:"period" min:"60" type:"integer" required:"true"` - - // The start time of the time period. - // - // StartTime is a required field - StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"unix" required:"true"` - - // The instance statistics. - // - // Statistics is a required field - Statistics []*string `locationName:"statistics" type:"list" required:"true"` - - // The unit. The list of valid values is below. - // - // Unit is a required field - Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` -} - -// String returns the string representation -func (s GetInstanceMetricDataInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceMetricDataInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceMetricDataInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceMetricDataInput"} - if s.EndTime == nil { - invalidParams.Add(request.NewErrParamRequired("EndTime")) - } - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.MetricName == nil { - invalidParams.Add(request.NewErrParamRequired("MetricName")) - } - if s.Period == nil { - invalidParams.Add(request.NewErrParamRequired("Period")) - } - if s.Period != nil && *s.Period < 60 { - invalidParams.Add(request.NewErrParamMinValue("Period", 60)) - } - if s.StartTime == nil { - invalidParams.Add(request.NewErrParamRequired("StartTime")) - } - if s.Statistics == nil { - invalidParams.Add(request.NewErrParamRequired("Statistics")) - } - if s.Unit == nil { - invalidParams.Add(request.NewErrParamRequired("Unit")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *GetInstanceMetricDataInput) SetEndTime(v time.Time) *GetInstanceMetricDataInput { - s.EndTime = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceMetricDataInput) SetInstanceName(v string) *GetInstanceMetricDataInput { - s.InstanceName = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetInstanceMetricDataInput) SetMetricName(v string) *GetInstanceMetricDataInput { - s.MetricName = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *GetInstanceMetricDataInput) SetPeriod(v int64) *GetInstanceMetricDataInput { - s.Period = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *GetInstanceMetricDataInput) SetStartTime(v time.Time) *GetInstanceMetricDataInput { - s.StartTime = &v - return s -} - -// SetStatistics sets the Statistics field's value. -func (s *GetInstanceMetricDataInput) SetStatistics(v []*string) *GetInstanceMetricDataInput { - s.Statistics = v - return s -} - -// SetUnit sets the Unit field's value. -func (s *GetInstanceMetricDataInput) SetUnit(v string) *GetInstanceMetricDataInput { - s.Unit = &v - return s -} - -type GetInstanceMetricDataOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance metric data request. - MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - - // The metric name to return data for. - MetricName *string `locationName:"metricName" type:"string" enum:"InstanceMetricName"` -} - -// String returns the string representation -func (s GetInstanceMetricDataOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceMetricDataOutput) GoString() string { - return s.String() -} - -// SetMetricData sets the MetricData field's value. -func (s *GetInstanceMetricDataOutput) SetMetricData(v []*MetricDatapoint) *GetInstanceMetricDataOutput { - s.MetricData = v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetInstanceMetricDataOutput) SetMetricName(v string) *GetInstanceMetricDataOutput { - s.MetricName = &v - return s -} - -type GetInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the specified instance. - Instance *Instance `locationName:"instance" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceOutput) GoString() string { - return s.String() -} - -// SetInstance sets the Instance field's value. -func (s *GetInstanceOutput) SetInstance(v *Instance) *GetInstanceOutput { - s.Instance = v - return s -} - -type GetInstancePortStatesInput struct { - _ struct{} `type:"structure"` - - // The name of the instance. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstancePortStatesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancePortStatesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstancePortStatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstancePortStatesInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstancePortStatesInput) SetInstanceName(v string) *GetInstancePortStatesInput { - s.InstanceName = &v - return s -} - -type GetInstancePortStatesOutput struct { - _ struct{} `type:"structure"` - - // Information about the port states resulting from your request. - PortStates []*InstancePortState `locationName:"portStates" type:"list"` -} - -// String returns the string representation -func (s GetInstancePortStatesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancePortStatesOutput) GoString() string { - return s.String() -} - -// SetPortStates sets the PortStates field's value. -func (s *GetInstancePortStatesOutput) SetPortStates(v []*InstancePortState) *GetInstancePortStatesOutput { - s.PortStates = v - return s -} - -type GetInstanceSnapshotInput struct { - _ struct{} `type:"structure"` - - // The name of the snapshot for which you are requesting information. - // - // InstanceSnapshotName is a required field - InstanceSnapshotName *string `locationName:"instanceSnapshotName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceSnapshotInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceSnapshotInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceSnapshotInput"} - if s.InstanceSnapshotName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceSnapshotName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceSnapshotName sets the InstanceSnapshotName field's value. -func (s *GetInstanceSnapshotInput) SetInstanceSnapshotName(v string) *GetInstanceSnapshotInput { - s.InstanceSnapshotName = &v - return s -} - -type GetInstanceSnapshotOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance snapshot request. - InstanceSnapshot *InstanceSnapshot `locationName:"instanceSnapshot" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceSnapshotOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotOutput) GoString() string { - return s.String() -} - -// SetInstanceSnapshot sets the InstanceSnapshot field's value. -func (s *GetInstanceSnapshotOutput) SetInstanceSnapshot(v *InstanceSnapshot) *GetInstanceSnapshotOutput { - s.InstanceSnapshot = v - return s -} - -type GetInstanceSnapshotsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get instance - // snapshots request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstanceSnapshotsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetInstanceSnapshotsInput) SetPageToken(v string) *GetInstanceSnapshotsInput { - s.PageToken = &v - return s -} - -type GetInstanceSnapshotsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get instance snapshots request. - InstanceSnapshots []*InstanceSnapshot `locationName:"instanceSnapshots" type:"list"` - - // A token used for advancing to the next page of results from your get instance - // snapshots request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstanceSnapshotsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceSnapshotsOutput) GoString() string { - return s.String() -} - -// SetInstanceSnapshots sets the InstanceSnapshots field's value. -func (s *GetInstanceSnapshotsOutput) SetInstanceSnapshots(v []*InstanceSnapshot) *GetInstanceSnapshotsOutput { - s.InstanceSnapshots = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetInstanceSnapshotsOutput) SetNextPageToken(v string) *GetInstanceSnapshotsOutput { - s.NextPageToken = &v - return s -} - -type GetInstanceStateInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to get state information about. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetInstanceStateInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceStateInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetInstanceStateInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetInstanceStateInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *GetInstanceStateInput) SetInstanceName(v string) *GetInstanceStateInput { - s.InstanceName = &v - return s -} - -type GetInstanceStateOutput struct { - _ struct{} `type:"structure"` - - // The state of the instance. - State *InstanceState `locationName:"state" type:"structure"` -} - -// String returns the string representation -func (s GetInstanceStateOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstanceStateOutput) GoString() string { - return s.String() -} - -// SetState sets the State field's value. -func (s *GetInstanceStateOutput) SetState(v *InstanceState) *GetInstanceStateOutput { - s.State = v - return s -} - -type GetInstancesInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get instances - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancesInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetInstancesInput) SetPageToken(v string) *GetInstancesInput { - s.PageToken = &v - return s -} - -type GetInstancesOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your instances. - Instances []*Instance `locationName:"instances" type:"list"` - - // A token used for advancing to the next page of results from your get instances - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetInstancesOutput) GoString() string { - return s.String() -} - -// SetInstances sets the Instances field's value. -func (s *GetInstancesOutput) SetInstances(v []*Instance) *GetInstancesOutput { - s.Instances = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetInstancesOutput) SetNextPageToken(v string) *GetInstancesOutput { - s.NextPageToken = &v - return s -} - -type GetKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair for which you are requesting information. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *GetKeyPairInput) SetKeyPairName(v string) *GetKeyPairInput { - s.KeyPairName = &v - return s -} - -type GetKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the key pair. - KeyPair *KeyPair `locationName:"keyPair" type:"structure"` -} - -// String returns the string representation -func (s GetKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairOutput) GoString() string { - return s.String() -} - -// SetKeyPair sets the KeyPair field's value. -func (s *GetKeyPairOutput) SetKeyPair(v *KeyPair) *GetKeyPairOutput { - s.KeyPair = v - return s -} - -type GetKeyPairsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get key - // pairs request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetKeyPairsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetKeyPairsInput) SetPageToken(v string) *GetKeyPairsInput { - s.PageToken = &v - return s -} - -type GetKeyPairsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the key pairs. - KeyPairs []*KeyPair `locationName:"keyPairs" type:"list"` - - // A token used for advancing to the next page of results from your get key - // pairs request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetKeyPairsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetKeyPairsOutput) GoString() string { - return s.String() -} - -// SetKeyPairs sets the KeyPairs field's value. -func (s *GetKeyPairsOutput) SetKeyPairs(v []*KeyPair) *GetKeyPairsOutput { - s.KeyPairs = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetKeyPairsOutput) SetNextPageToken(v string) *GetKeyPairsOutput { - s.NextPageToken = &v - return s -} - -type GetLoadBalancerInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetLoadBalancerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerInput) SetLoadBalancerName(v string) *GetLoadBalancerInput { - s.LoadBalancerName = &v - return s -} - -type GetLoadBalancerMetricDataInput struct { - _ struct{} `type:"structure"` - - // The end time of the period. - // - // EndTime is a required field - EndTime *time.Time `locationName:"endTime" type:"timestamp" timestampFormat:"unix" required:"true"` - - // The name of the load balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` - - // The metric about which you want to return information. Valid values are listed - // below, along with the most useful statistics to include in your request. - // - // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated - // by the client that did not establish a session with the load balancer. - // Possible causes include a mismatch of ciphers or protocols. - // - // Statistics: The most useful statistic is Sum. - // - // * HealthyHostCount - The number of target instances that are considered - // healthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * UnhealthyHostCount - The number of target instances that are considered - // unhealthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that - // originate from the load balancer. Client errors are generated when requests - // are malformed or incomplete. These requests have not been received by - // the target instance. This count does not include any response codes generated - // by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that - // originate from the load balancer. This count does not include any response - // codes generated by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. Note that Minimum, Maximum, and Average all - // return 1. - // - // * HTTPCode_Instance_2XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_3XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_4XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_5XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * InstanceResponseTime - The time elapsed, in seconds, after the request - // leaves the load balancer until a response from the target instance is - // received. - // - // Statistics: The most useful statistic is Average. - // - // * RejectedConnectionCount - The number of connections that were rejected - // because the load balancer had reached its maximum number of connections. - // - // Statistics: The most useful statistic is Sum. - // - // * RequestCount - The number of requests processed over IPv4. This count - // includes only the requests with a response generated by a target instance - // of the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // MetricName is a required field - MetricName *string `locationName:"metricName" type:"string" required:"true" enum:"LoadBalancerMetricName"` - - // The time period duration for your health data request. - // - // Period is a required field - Period *int64 `locationName:"period" min:"60" type:"integer" required:"true"` - - // The start time of the period. - // - // StartTime is a required field - StartTime *time.Time `locationName:"startTime" type:"timestamp" timestampFormat:"unix" required:"true"` - - // An array of statistics that you want to request metrics for. Valid values - // are listed below. - // - // * SampleCount - The count (number) of data points used for the statistical - // calculation. - // - // * Average - The value of Sum / SampleCount during the specified period. - // By comparing this statistic with the Minimum and Maximum, you can determine - // the full scope of a metric and how close the average use is to the Minimum - // and Maximum. This comparison helps you to know when to increase or decrease - // your resources as needed. - // - // * Sum - All values submitted for the matching metric added together. This - // statistic can be useful for determining the total volume of a metric. - // - // * Minimum - The lowest value observed during the specified period. You - // can use this value to determine low volumes of activity for your application. - // - // * Maximum - The highest value observed during the specified period. You - // can use this value to determine high volumes of activity for your application. - // - // Statistics is a required field - Statistics []*string `locationName:"statistics" type:"list" required:"true"` - - // The unit for the time period request. Valid values are listed below. - // - // Unit is a required field - Unit *string `locationName:"unit" type:"string" required:"true" enum:"MetricUnit"` -} - -// String returns the string representation -func (s GetLoadBalancerMetricDataInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerMetricDataInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerMetricDataInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerMetricDataInput"} - if s.EndTime == nil { - invalidParams.Add(request.NewErrParamRequired("EndTime")) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - if s.MetricName == nil { - invalidParams.Add(request.NewErrParamRequired("MetricName")) - } - if s.Period == nil { - invalidParams.Add(request.NewErrParamRequired("Period")) - } - if s.Period != nil && *s.Period < 60 { - invalidParams.Add(request.NewErrParamMinValue("Period", 60)) - } - if s.StartTime == nil { - invalidParams.Add(request.NewErrParamRequired("StartTime")) - } - if s.Statistics == nil { - invalidParams.Add(request.NewErrParamRequired("Statistics")) - } - if s.Unit == nil { - invalidParams.Add(request.NewErrParamRequired("Unit")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEndTime sets the EndTime field's value. -func (s *GetLoadBalancerMetricDataInput) SetEndTime(v time.Time) *GetLoadBalancerMetricDataInput { - s.EndTime = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerMetricDataInput) SetLoadBalancerName(v string) *GetLoadBalancerMetricDataInput { - s.LoadBalancerName = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetLoadBalancerMetricDataInput) SetMetricName(v string) *GetLoadBalancerMetricDataInput { - s.MetricName = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *GetLoadBalancerMetricDataInput) SetPeriod(v int64) *GetLoadBalancerMetricDataInput { - s.Period = &v - return s -} - -// SetStartTime sets the StartTime field's value. -func (s *GetLoadBalancerMetricDataInput) SetStartTime(v time.Time) *GetLoadBalancerMetricDataInput { - s.StartTime = &v - return s -} - -// SetStatistics sets the Statistics field's value. -func (s *GetLoadBalancerMetricDataInput) SetStatistics(v []*string) *GetLoadBalancerMetricDataInput { - s.Statistics = v - return s -} - -// SetUnit sets the Unit field's value. -func (s *GetLoadBalancerMetricDataInput) SetUnit(v string) *GetLoadBalancerMetricDataInput { - s.Unit = &v - return s -} - -type GetLoadBalancerMetricDataOutput struct { - _ struct{} `type:"structure"` - - // An array of metric datapoint objects. - MetricData []*MetricDatapoint `locationName:"metricData" type:"list"` - - // The metric about which you are receiving information. Valid values are listed - // below, along with the most useful statistics to include in your request. - // - // * ClientTLSNegotiationErrorCount - The number of TLS connections initiated - // by the client that did not establish a session with the load balancer. - // Possible causes include a mismatch of ciphers or protocols. - // - // Statistics: The most useful statistic is Sum. - // - // * HealthyHostCount - The number of target instances that are considered - // healthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * UnhealthyHostCount - The number of target instances that are considered - // unhealthy. - // - // Statistics: The most useful statistic are Average, Minimum, and Maximum. - // - // * HTTPCode_LB_4XX_Count - The number of HTTP 4XX client error codes that - // originate from the load balancer. Client errors are generated when requests - // are malformed or incomplete. These requests have not been received by - // the target instance. This count does not include any response codes generated - // by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_LB_5XX_Count - The number of HTTP 5XX server error codes that - // originate from the load balancer. This count does not include any response - // codes generated by the target instances. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. Note that Minimum, Maximum, and Average all - // return 1. - // - // * HTTPCode_Instance_2XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_3XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_4XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * HTTPCode_Instance_5XX_Count - The number of HTTP response codes generated - // by the target instances. This does not include any response codes generated - // by the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - // - // * InstanceResponseTime - The time elapsed, in seconds, after the request - // leaves the load balancer until a response from the target instance is - // received. - // - // Statistics: The most useful statistic is Average. - // - // * RejectedConnectionCount - The number of connections that were rejected - // because the load balancer had reached its maximum number of connections. - // - // Statistics: The most useful statistic is Sum. - // - // * RequestCount - The number of requests processed over IPv4. This count - // includes only the requests with a response generated by a target instance - // of the load balancer. - // - // Statistics: The most useful statistic is Sum. Note that Minimum, Maximum, - // and Average all return 1. - MetricName *string `locationName:"metricName" type:"string" enum:"LoadBalancerMetricName"` -} - -// String returns the string representation -func (s GetLoadBalancerMetricDataOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerMetricDataOutput) GoString() string { - return s.String() -} - -// SetMetricData sets the MetricData field's value. -func (s *GetLoadBalancerMetricDataOutput) SetMetricData(v []*MetricDatapoint) *GetLoadBalancerMetricDataOutput { - s.MetricData = v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *GetLoadBalancerMetricDataOutput) SetMetricName(v string) *GetLoadBalancerMetricDataOutput { - s.MetricName = &v - return s -} - -type GetLoadBalancerOutput struct { - _ struct{} `type:"structure"` - - // An object containing information about your load balancer. - LoadBalancer *LoadBalancer `locationName:"loadBalancer" type:"structure"` -} - -// String returns the string representation -func (s GetLoadBalancerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerOutput) GoString() string { - return s.String() -} - -// SetLoadBalancer sets the LoadBalancer field's value. -func (s *GetLoadBalancerOutput) SetLoadBalancer(v *LoadBalancer) *GetLoadBalancerOutput { - s.LoadBalancer = v - return s -} - -type GetLoadBalancerTlsCertificatesInput struct { - _ struct{} `type:"structure"` - - // The name of the load balancer you associated with your SSL/TLS certificate. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetLoadBalancerTlsCertificatesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerTlsCertificatesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetLoadBalancerTlsCertificatesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetLoadBalancerTlsCertificatesInput"} - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *GetLoadBalancerTlsCertificatesInput) SetLoadBalancerName(v string) *GetLoadBalancerTlsCertificatesInput { - s.LoadBalancerName = &v - return s -} - -type GetLoadBalancerTlsCertificatesOutput struct { - _ struct{} `type:"structure"` - - // An array of LoadBalancerTlsCertificate objects describing your SSL/TLS certificates. - TlsCertificates []*LoadBalancerTlsCertificate `locationName:"tlsCertificates" type:"list"` -} - -// String returns the string representation -func (s GetLoadBalancerTlsCertificatesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancerTlsCertificatesOutput) GoString() string { - return s.String() -} - -// SetTlsCertificates sets the TlsCertificates field's value. -func (s *GetLoadBalancerTlsCertificatesOutput) SetTlsCertificates(v []*LoadBalancerTlsCertificate) *GetLoadBalancerTlsCertificatesOutput { - s.TlsCertificates = v - return s -} - -type GetLoadBalancersInput struct { - _ struct{} `type:"structure"` - - // A token used for paginating the results from your GetLoadBalancers request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetLoadBalancersInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancersInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetLoadBalancersInput) SetPageToken(v string) *GetLoadBalancersInput { - s.PageToken = &v - return s -} - -type GetLoadBalancersOutput struct { - _ struct{} `type:"structure"` - - // An array of LoadBalancer objects describing your load balancers. - LoadBalancers []*LoadBalancer `locationName:"loadBalancers" type:"list"` - - // A token used for advancing to the next page of results from your GetLoadBalancers - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` -} - -// String returns the string representation -func (s GetLoadBalancersOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetLoadBalancersOutput) GoString() string { - return s.String() -} - -// SetLoadBalancers sets the LoadBalancers field's value. -func (s *GetLoadBalancersOutput) SetLoadBalancers(v []*LoadBalancer) *GetLoadBalancersOutput { - s.LoadBalancers = v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetLoadBalancersOutput) SetNextPageToken(v string) *GetLoadBalancersOutput { - s.NextPageToken = &v - return s -} - -type GetOperationInput struct { - _ struct{} `type:"structure"` - - // A GUID used to identify the operation. - // - // OperationId is a required field - OperationId *string `locationName:"operationId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetOperationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetOperationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetOperationInput"} - if s.OperationId == nil { - invalidParams.Add(request.NewErrParamRequired("OperationId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetOperationId sets the OperationId field's value. -func (s *GetOperationInput) SetOperationId(v string) *GetOperationInput { - s.OperationId = &v - return s -} - -type GetOperationOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the results of your - // get operation request. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s GetOperationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *GetOperationOutput) SetOperation(v *Operation) *GetOperationOutput { - s.Operation = v - return s -} - -type GetOperationsForResourceInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // for resource request. - PageToken *string `locationName:"pageToken" type:"string"` - - // The name of the resource for which you are requesting information. - // - // ResourceName is a required field - ResourceName *string `locationName:"resourceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetOperationsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetOperationsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetOperationsForResourceInput"} - if s.ResourceName == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetPageToken sets the PageToken field's value. -func (s *GetOperationsForResourceInput) SetPageToken(v string) *GetOperationsForResourceInput { - s.PageToken = &v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *GetOperationsForResourceInput) SetResourceName(v string) *GetOperationsForResourceInput { - s.ResourceName = &v - return s -} - -type GetOperationsForResourceOutput struct { - _ struct{} `type:"structure"` - - // (Deprecated) Returns the number of pages of results that remain. - // - // In releases prior to June 12, 2017, this parameter returned null by the API. - // It is now deprecated, and the API returns the nextPageToken parameter instead. - NextPageCount *string `locationName:"nextPageCount" deprecated:"true" type:"string"` - - // An identifier that was returned from the previous call to this operation, - // which can be used to return the next set of items in the list. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about the results of your - // get operations for resource request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s GetOperationsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsForResourceOutput) GoString() string { - return s.String() -} - -// SetNextPageCount sets the NextPageCount field's value. -func (s *GetOperationsForResourceOutput) SetNextPageCount(v string) *GetOperationsForResourceOutput { - s.NextPageCount = &v - return s -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetOperationsForResourceOutput) SetNextPageToken(v string) *GetOperationsForResourceOutput { - s.NextPageToken = &v - return s -} - -// SetOperations sets the Operations field's value. -func (s *GetOperationsForResourceOutput) SetOperations(v []*Operation) *GetOperationsForResourceOutput { - s.Operations = v - return s -} - -type GetOperationsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetOperationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetOperationsInput) SetPageToken(v string) *GetOperationsInput { - s.PageToken = &v - return s -} - -type GetOperationsOutput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get operations - // request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about the results of your - // get operations request. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s GetOperationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetOperationsOutput) GoString() string { - return s.String() -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetOperationsOutput) SetNextPageToken(v string) *GetOperationsOutput { - s.NextPageToken = &v - return s -} - -// SetOperations sets the Operations field's value. -func (s *GetOperationsOutput) SetOperations(v []*Operation) *GetOperationsOutput { - s.Operations = v - return s -} - -type GetRegionsInput struct { - _ struct{} `type:"structure"` - - // A Boolean value indicating whether to also include Availability Zones in - // your get regions request. Availability Zones are indicated with a letter: - // e.g., us-east-2a. - IncludeAvailabilityZones *bool `locationName:"includeAvailabilityZones" type:"boolean"` -} - -// String returns the string representation -func (s GetRegionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetRegionsInput) GoString() string { - return s.String() -} - -// SetIncludeAvailabilityZones sets the IncludeAvailabilityZones field's value. -func (s *GetRegionsInput) SetIncludeAvailabilityZones(v bool) *GetRegionsInput { - s.IncludeAvailabilityZones = &v - return s -} - -type GetRegionsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about your get regions - // request. - Regions []*Region `locationName:"regions" type:"list"` -} - -// String returns the string representation -func (s GetRegionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetRegionsOutput) GoString() string { - return s.String() -} - -// SetRegions sets the Regions field's value. -func (s *GetRegionsOutput) SetRegions(v []*Region) *GetRegionsOutput { - s.Regions = v - return s -} - -type GetStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP in Lightsail. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *GetStaticIpInput) SetStaticIpName(v string) *GetStaticIpInput { - s.StaticIpName = &v - return s -} - -type GetStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the requested static - // IP. - StaticIp *StaticIp `locationName:"staticIp" type:"structure"` -} - -// String returns the string representation -func (s GetStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpOutput) GoString() string { - return s.String() -} - -// SetStaticIp sets the StaticIp field's value. -func (s *GetStaticIpOutput) SetStaticIp(v *StaticIp) *GetStaticIpOutput { - s.StaticIp = v - return s -} - -type GetStaticIpsInput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get static - // IPs request. - PageToken *string `locationName:"pageToken" type:"string"` -} - -// String returns the string representation -func (s GetStaticIpsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpsInput) GoString() string { - return s.String() -} - -// SetPageToken sets the PageToken field's value. -func (s *GetStaticIpsInput) SetPageToken(v string) *GetStaticIpsInput { - s.PageToken = &v - return s -} - -type GetStaticIpsOutput struct { - _ struct{} `type:"structure"` - - // A token used for advancing to the next page of results from your get static - // IPs request. - NextPageToken *string `locationName:"nextPageToken" type:"string"` - - // An array of key-value pairs containing information about your get static - // IPs request. - StaticIps []*StaticIp `locationName:"staticIps" type:"list"` -} - -// String returns the string representation -func (s GetStaticIpsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetStaticIpsOutput) GoString() string { - return s.String() -} - -// SetNextPageToken sets the NextPageToken field's value. -func (s *GetStaticIpsOutput) SetNextPageToken(v string) *GetStaticIpsOutput { - s.NextPageToken = &v - return s -} - -// SetStaticIps sets the StaticIps field's value. -func (s *GetStaticIpsOutput) SetStaticIps(v []*StaticIp) *GetStaticIpsOutput { - s.StaticIps = v - return s -} - -type ImportKeyPairInput struct { - _ struct{} `type:"structure"` - - // The name of the key pair for which you want to import the public key. - // - // KeyPairName is a required field - KeyPairName *string `locationName:"keyPairName" type:"string" required:"true"` - - // A base64-encoded public key of the ssh-rsa type. - // - // PublicKeyBase64 is a required field - PublicKeyBase64 *string `locationName:"publicKeyBase64" type:"string" required:"true"` -} - -// String returns the string representation -func (s ImportKeyPairInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ImportKeyPairInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ImportKeyPairInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ImportKeyPairInput"} - if s.KeyPairName == nil { - invalidParams.Add(request.NewErrParamRequired("KeyPairName")) - } - if s.PublicKeyBase64 == nil { - invalidParams.Add(request.NewErrParamRequired("PublicKeyBase64")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *ImportKeyPairInput) SetKeyPairName(v string) *ImportKeyPairInput { - s.KeyPairName = &v - return s -} - -// SetPublicKeyBase64 sets the PublicKeyBase64 field's value. -func (s *ImportKeyPairInput) SetPublicKeyBase64(v string) *ImportKeyPairInput { - s.PublicKeyBase64 = &v - return s -} - -type ImportKeyPairOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s ImportKeyPairOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ImportKeyPairOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *ImportKeyPairOutput) SetOperation(v *Operation) *ImportKeyPairOutput { - s.Operation = v - return s -} - -// Describes an instance (a virtual private server). -type Instance struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the instance (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/244ad76f-8aad-4741-809f-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The blueprint ID (e.g., os_amlinux_2016_03). - BlueprintId *string `locationName:"blueprintId" type:"string"` - - // The friendly name of the blueprint (e.g., Amazon Linux). - BlueprintName *string `locationName:"blueprintName" type:"string"` - - // The bundle for the instance (e.g., micro_1_0). - BundleId *string `locationName:"bundleId" type:"string"` - - // The timestamp when the instance was created (e.g., 1479734909.17). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The size of the vCPU and the amount of RAM for the instance. - Hardware *InstanceHardware `locationName:"hardware" type:"structure"` - - // The IPv6 address of the instance. - Ipv6Address *string `locationName:"ipv6Address" type:"string"` - - // A Boolean value indicating whether this instance has a static IP assigned - // to it. - IsStaticIp *bool `locationName:"isStaticIp" type:"boolean"` - - // The region name and availability zone where the instance is located. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name the user gave the instance (e.g., Amazon_Linux-1GB-Ohio-1). - Name *string `locationName:"name" type:"string"` - - // Information about the public ports and monthly data transfer rates for the - // instance. - Networking *InstanceNetworking `locationName:"networking" type:"structure"` - - // The private IP address of the instance. - PrivateIpAddress *string `locationName:"privateIpAddress" type:"string"` - - // The public IP address of the instance. - PublicIpAddress *string `locationName:"publicIpAddress" type:"string"` - - // The type of resource (usually Instance). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The name of the SSH key being used to connect to the instance (e.g., LightsailDefaultKeyPair). - SshKeyName *string `locationName:"sshKeyName" type:"string"` - - // The status code and the state (e.g., running) for the instance. - State *InstanceState `locationName:"state" type:"structure"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` - - // The user name for connecting to the instance (e.g., ec2-user). - Username *string `locationName:"username" type:"string"` -} - -// String returns the string representation -func (s Instance) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Instance) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *Instance) SetArn(v string) *Instance { - s.Arn = &v - return s -} - -// SetBlueprintId sets the BlueprintId field's value. -func (s *Instance) SetBlueprintId(v string) *Instance { - s.BlueprintId = &v - return s -} - -// SetBlueprintName sets the BlueprintName field's value. -func (s *Instance) SetBlueprintName(v string) *Instance { - s.BlueprintName = &v - return s -} - -// SetBundleId sets the BundleId field's value. -func (s *Instance) SetBundleId(v string) *Instance { - s.BundleId = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Instance) SetCreatedAt(v time.Time) *Instance { - s.CreatedAt = &v - return s -} - -// SetHardware sets the Hardware field's value. -func (s *Instance) SetHardware(v *InstanceHardware) *Instance { - s.Hardware = v - return s -} - -// SetIpv6Address sets the Ipv6Address field's value. -func (s *Instance) SetIpv6Address(v string) *Instance { - s.Ipv6Address = &v - return s -} - -// SetIsStaticIp sets the IsStaticIp field's value. -func (s *Instance) SetIsStaticIp(v bool) *Instance { - s.IsStaticIp = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Instance) SetLocation(v *ResourceLocation) *Instance { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *Instance) SetName(v string) *Instance { - s.Name = &v - return s -} - -// SetNetworking sets the Networking field's value. -func (s *Instance) SetNetworking(v *InstanceNetworking) *Instance { - s.Networking = v - return s -} - -// SetPrivateIpAddress sets the PrivateIpAddress field's value. -func (s *Instance) SetPrivateIpAddress(v string) *Instance { - s.PrivateIpAddress = &v - return s -} - -// SetPublicIpAddress sets the PublicIpAddress field's value. -func (s *Instance) SetPublicIpAddress(v string) *Instance { - s.PublicIpAddress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Instance) SetResourceType(v string) *Instance { - s.ResourceType = &v - return s -} - -// SetSshKeyName sets the SshKeyName field's value. -func (s *Instance) SetSshKeyName(v string) *Instance { - s.SshKeyName = &v - return s -} - -// SetState sets the State field's value. -func (s *Instance) SetState(v *InstanceState) *Instance { - s.State = v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *Instance) SetSupportCode(v string) *Instance { - s.SupportCode = &v - return s -} - -// SetUsername sets the Username field's value. -func (s *Instance) SetUsername(v string) *Instance { - s.Username = &v - return s -} - -// The parameters for gaining temporary access to one of your Amazon Lightsail -// instances. -type InstanceAccessDetails struct { - _ struct{} `type:"structure"` - - // For SSH access, the public key to use when accessing your instance For OpenSSH - // clients (e.g., command line SSH), you should save this value to tempkey-cert.pub. - CertKey *string `locationName:"certKey" type:"string"` - - // For SSH access, the date on which the temporary keys expire. - ExpiresAt *time.Time `locationName:"expiresAt" type:"timestamp" timestampFormat:"unix"` - - // The name of this Amazon Lightsail instance. - InstanceName *string `locationName:"instanceName" type:"string"` - - // The public IP address of the Amazon Lightsail instance. - IpAddress *string `locationName:"ipAddress" type:"string"` - - // For RDP access, the password for your Amazon Lightsail instance. Password - // will be an empty string if the password for your new instance is not ready - // yet. When you create an instance, it can take up to 15 minutes for the instance - // to be ready. - // - // If you create an instance using any key pair other than the default (LightsailDefaultKeyPair), - // password will always be an empty string. - // - // If you change the Administrator password on the instance, Lightsail will - // continue to return the original password value. When accessing the instance - // using RDP, you need to manually enter the Administrator password after changing - // it from the default. - Password *string `locationName:"password" type:"string"` - - // For a Windows Server-based instance, an object with the data you can use - // to retrieve your password. This is only needed if password is empty and the - // instance is not new (and therefore the password is not ready yet). When you - // create an instance, it can take up to 15 minutes for the instance to be ready. - PasswordData *PasswordData `locationName:"passwordData" type:"structure"` - - // For SSH access, the temporary private key. For OpenSSH clients (e.g., command - // line SSH), you should save this value to tempkey). - PrivateKey *string `locationName:"privateKey" type:"string"` - - // The protocol for these Amazon Lightsail instance access details. - Protocol *string `locationName:"protocol" type:"string" enum:"InstanceAccessProtocol"` - - // The user name to use when logging in to the Amazon Lightsail instance. - Username *string `locationName:"username" type:"string"` -} - -// String returns the string representation -func (s InstanceAccessDetails) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceAccessDetails) GoString() string { - return s.String() -} - -// SetCertKey sets the CertKey field's value. -func (s *InstanceAccessDetails) SetCertKey(v string) *InstanceAccessDetails { - s.CertKey = &v - return s -} - -// SetExpiresAt sets the ExpiresAt field's value. -func (s *InstanceAccessDetails) SetExpiresAt(v time.Time) *InstanceAccessDetails { - s.ExpiresAt = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *InstanceAccessDetails) SetInstanceName(v string) *InstanceAccessDetails { - s.InstanceName = &v - return s -} - -// SetIpAddress sets the IpAddress field's value. -func (s *InstanceAccessDetails) SetIpAddress(v string) *InstanceAccessDetails { - s.IpAddress = &v - return s -} - -// SetPassword sets the Password field's value. -func (s *InstanceAccessDetails) SetPassword(v string) *InstanceAccessDetails { - s.Password = &v - return s -} - -// SetPasswordData sets the PasswordData field's value. -func (s *InstanceAccessDetails) SetPasswordData(v *PasswordData) *InstanceAccessDetails { - s.PasswordData = v - return s -} - -// SetPrivateKey sets the PrivateKey field's value. -func (s *InstanceAccessDetails) SetPrivateKey(v string) *InstanceAccessDetails { - s.PrivateKey = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstanceAccessDetails) SetProtocol(v string) *InstanceAccessDetails { - s.Protocol = &v - return s -} - -// SetUsername sets the Username field's value. -func (s *InstanceAccessDetails) SetUsername(v string) *InstanceAccessDetails { - s.Username = &v - return s -} - -// Describes the hardware for the instance. -type InstanceHardware struct { - _ struct{} `type:"structure"` - - // The number of vCPUs the instance has. - CpuCount *int64 `locationName:"cpuCount" type:"integer"` - - // The disks attached to the instance. - Disks []*Disk `locationName:"disks" type:"list"` - - // The amount of RAM in GB on the instance (e.g., 1.0). - RamSizeInGb *float64 `locationName:"ramSizeInGb" type:"float"` -} - -// String returns the string representation -func (s InstanceHardware) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceHardware) GoString() string { - return s.String() -} - -// SetCpuCount sets the CpuCount field's value. -func (s *InstanceHardware) SetCpuCount(v int64) *InstanceHardware { - s.CpuCount = &v - return s -} - -// SetDisks sets the Disks field's value. -func (s *InstanceHardware) SetDisks(v []*Disk) *InstanceHardware { - s.Disks = v - return s -} - -// SetRamSizeInGb sets the RamSizeInGb field's value. -func (s *InstanceHardware) SetRamSizeInGb(v float64) *InstanceHardware { - s.RamSizeInGb = &v - return s -} - -// Describes information about the health of the instance. -type InstanceHealthSummary struct { - _ struct{} `type:"structure"` - - // Describes the overall instance health. Valid values are below. - InstanceHealth *string `locationName:"instanceHealth" type:"string" enum:"InstanceHealthState"` - - // More information about the instance health. If the instanceHealth is healthy, - // then an instanceHealthReason value is not provided. - // - // If instanceHealth is initial, the instanceHealthReason value can be one of - // the following: - // - // * Lb.RegistrationInProgress - The target instance is in the process of - // being registered with the load balancer. - // - // * Lb.InitialHealthChecking - The Lightsail load balancer is still sending - // the target instance the minimum number of health checks required to determine - // its health status. - // - // If instanceHealth is unhealthy, the instanceHealthReason value can be one - // of the following: - // - // * Instance.ResponseCodeMismatch - The health checks did not return an - // expected HTTP code. - // - // * Instance.Timeout - The health check requests timed out. - // - // * Instance.FailedHealthChecks - The health checks failed because the connection - // to the target instance timed out, the target instance response was malformed, - // or the target instance failed the health check for an unknown reason. - // - // * Lb.InternalError - The health checks failed due to an internal error. - // - // If instanceHealth is unused, the instanceHealthReason value can be one of - // the following: - // - // * Instance.NotRegistered - The target instance is not registered with - // the target group. - // - // * Instance.NotInUse - The target group is not used by any load balancer, - // or the target instance is in an Availability Zone that is not enabled - // for its load balancer. - // - // * Instance.IpUnusable - The target IP address is reserved for use by a - // Lightsail load balancer. - // - // * Instance.InvalidState - The target is in the stopped or terminated state. - // - // If instanceHealth is draining, the instanceHealthReason value can be one - // of the following: - // - // * Instance.DeregistrationInProgress - The target instance is in the process - // of being deregistered and the deregistration delay period has not expired. - InstanceHealthReason *string `locationName:"instanceHealthReason" type:"string" enum:"InstanceHealthReason"` - - // The name of the Lightsail instance for which you are requesting health check - // data. - InstanceName *string `locationName:"instanceName" type:"string"` -} - -// String returns the string representation -func (s InstanceHealthSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceHealthSummary) GoString() string { - return s.String() -} - -// SetInstanceHealth sets the InstanceHealth field's value. -func (s *InstanceHealthSummary) SetInstanceHealth(v string) *InstanceHealthSummary { - s.InstanceHealth = &v - return s -} - -// SetInstanceHealthReason sets the InstanceHealthReason field's value. -func (s *InstanceHealthSummary) SetInstanceHealthReason(v string) *InstanceHealthSummary { - s.InstanceHealthReason = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *InstanceHealthSummary) SetInstanceName(v string) *InstanceHealthSummary { - s.InstanceName = &v - return s -} - -// Describes monthly data transfer rates and port information for an instance. -type InstanceNetworking struct { - _ struct{} `type:"structure"` - - // The amount of data in GB allocated for monthly data transfers. - MonthlyTransfer *MonthlyTransfer `locationName:"monthlyTransfer" type:"structure"` - - // An array of key-value pairs containing information about the ports on the - // instance. - Ports []*InstancePortInfo `locationName:"ports" type:"list"` -} - -// String returns the string representation -func (s InstanceNetworking) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceNetworking) GoString() string { - return s.String() -} - -// SetMonthlyTransfer sets the MonthlyTransfer field's value. -func (s *InstanceNetworking) SetMonthlyTransfer(v *MonthlyTransfer) *InstanceNetworking { - s.MonthlyTransfer = v - return s -} - -// SetPorts sets the Ports field's value. -func (s *InstanceNetworking) SetPorts(v []*InstancePortInfo) *InstanceNetworking { - s.Ports = v - return s -} - -// Describes information about the instance ports. -type InstancePortInfo struct { - _ struct{} `type:"structure"` - - // The access direction (inbound or outbound). - AccessDirection *string `locationName:"accessDirection" type:"string" enum:"AccessDirection"` - - // The location from which access is allowed (e.g., Anywhere (0.0.0.0/0)). - AccessFrom *string `locationName:"accessFrom" type:"string"` - - // The type of access (Public or Private). - AccessType *string `locationName:"accessType" type:"string" enum:"PortAccessType"` - - // The common name. - CommonName *string `locationName:"commonName" type:"string"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol being used. Can be one of the following. - // - // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, - // and error-checked delivery of streamed data between applications running - // on hosts communicating by an IP network. If you have an application that - // doesn't require reliable data stream service, use UDP instead. - // - // * all - All transport layer protocol types. For more general information, - // see Transport layer (https://en.wikipedia.org/wiki/Transport_layer) on - // Wikipedia. - // - // * udp - With User Datagram Protocol (UDP), computer applications can send - // messages (or datagrams) to other hosts on an Internet Protocol (IP) network. - // Prior communications are not required to set up transmission channels - // or data paths. Applications that don't require reliable data stream service - // can use UDP, which provides a connectionless datagram service that emphasizes - // reduced latency over reliability. If you do require reliable data stream - // service, use TCP instead. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s InstancePortInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstancePortInfo) GoString() string { - return s.String() -} - -// SetAccessDirection sets the AccessDirection field's value. -func (s *InstancePortInfo) SetAccessDirection(v string) *InstancePortInfo { - s.AccessDirection = &v - return s -} - -// SetAccessFrom sets the AccessFrom field's value. -func (s *InstancePortInfo) SetAccessFrom(v string) *InstancePortInfo { - s.AccessFrom = &v - return s -} - -// SetAccessType sets the AccessType field's value. -func (s *InstancePortInfo) SetAccessType(v string) *InstancePortInfo { - s.AccessType = &v - return s -} - -// SetCommonName sets the CommonName field's value. -func (s *InstancePortInfo) SetCommonName(v string) *InstancePortInfo { - s.CommonName = &v - return s -} - -// SetFromPort sets the FromPort field's value. -func (s *InstancePortInfo) SetFromPort(v int64) *InstancePortInfo { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstancePortInfo) SetProtocol(v string) *InstancePortInfo { - s.Protocol = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *InstancePortInfo) SetToPort(v int64) *InstancePortInfo { - s.ToPort = &v - return s -} - -// Describes the port state. -type InstancePortState struct { - _ struct{} `type:"structure"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol being used. Can be one of the following. - // - // * tcp - Transmission Control Protocol (TCP) provides reliable, ordered, - // and error-checked delivery of streamed data between applications running - // on hosts communicating by an IP network. If you have an application that - // doesn't require reliable data stream service, use UDP instead. - // - // * all - All transport layer protocol types. For more general information, - // see Transport layer (https://en.wikipedia.org/wiki/Transport_layer) on - // Wikipedia. - // - // * udp - With User Datagram Protocol (UDP), computer applications can send - // messages (or datagrams) to other hosts on an Internet Protocol (IP) network. - // Prior communications are not required to set up transmission channels - // or data paths. Applications that don't require reliable data stream service - // can use UDP, which provides a connectionless datagram service that emphasizes - // reduced latency over reliability. If you do require reliable data stream - // service, use TCP instead. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // Specifies whether the instance port is open or closed. - State *string `locationName:"state" type:"string" enum:"PortState"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s InstancePortState) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstancePortState) GoString() string { - return s.String() -} - -// SetFromPort sets the FromPort field's value. -func (s *InstancePortState) SetFromPort(v int64) *InstancePortState { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *InstancePortState) SetProtocol(v string) *InstancePortState { - s.Protocol = &v - return s -} - -// SetState sets the State field's value. -func (s *InstancePortState) SetState(v string) *InstancePortState { - s.State = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *InstancePortState) SetToPort(v int64) *InstancePortState { - s.ToPort = &v - return s -} - -// Describes the snapshot of the virtual private server, or instance. -type InstanceSnapshot struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the snapshot (e.g., arn:aws:lightsail:us-east-2:123456789101:InstanceSnapshot/d23b5706-3322-4d83-81e5-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The timestamp when the snapshot was created (e.g., 1479907467.024). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // An array of disk objects containing information about all block storage disks. - FromAttachedDisks []*Disk `locationName:"fromAttachedDisks" type:"list"` - - // The blueprint ID from which you created the snapshot (e.g., os_debian_8_3). - // A blueprint is a virtual private server (or instance) image used to create - // instances quickly. - FromBlueprintId *string `locationName:"fromBlueprintId" type:"string"` - - // The bundle ID from which you created the snapshot (e.g., micro_1_0). - FromBundleId *string `locationName:"fromBundleId" type:"string"` - - // The Amazon Resource Name (ARN) of the instance from which the snapshot was - // created (e.g., arn:aws:lightsail:us-east-2:123456789101:Instance/64b8404c-ccb1-430b-8daf-12345EXAMPLE). - FromInstanceArn *string `locationName:"fromInstanceArn" type:"string"` - - // The instance from which the snapshot was created. - FromInstanceName *string `locationName:"fromInstanceName" type:"string"` - - // The region name and availability zone where you created the snapshot. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the snapshot. - Name *string `locationName:"name" type:"string"` - - // The progress of the snapshot. - Progress *string `locationName:"progress" type:"string"` - - // The type of resource (usually InstanceSnapshot). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The size in GB of the SSD. - SizeInGb *int64 `locationName:"sizeInGb" type:"integer"` - - // The state the snapshot is in. - State *string `locationName:"state" type:"string" enum:"InstanceSnapshotState"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s InstanceSnapshot) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceSnapshot) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *InstanceSnapshot) SetArn(v string) *InstanceSnapshot { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *InstanceSnapshot) SetCreatedAt(v time.Time) *InstanceSnapshot { - s.CreatedAt = &v - return s -} - -// SetFromAttachedDisks sets the FromAttachedDisks field's value. -func (s *InstanceSnapshot) SetFromAttachedDisks(v []*Disk) *InstanceSnapshot { - s.FromAttachedDisks = v - return s -} - -// SetFromBlueprintId sets the FromBlueprintId field's value. -func (s *InstanceSnapshot) SetFromBlueprintId(v string) *InstanceSnapshot { - s.FromBlueprintId = &v - return s -} - -// SetFromBundleId sets the FromBundleId field's value. -func (s *InstanceSnapshot) SetFromBundleId(v string) *InstanceSnapshot { - s.FromBundleId = &v - return s -} - -// SetFromInstanceArn sets the FromInstanceArn field's value. -func (s *InstanceSnapshot) SetFromInstanceArn(v string) *InstanceSnapshot { - s.FromInstanceArn = &v - return s -} - -// SetFromInstanceName sets the FromInstanceName field's value. -func (s *InstanceSnapshot) SetFromInstanceName(v string) *InstanceSnapshot { - s.FromInstanceName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *InstanceSnapshot) SetLocation(v *ResourceLocation) *InstanceSnapshot { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *InstanceSnapshot) SetName(v string) *InstanceSnapshot { - s.Name = &v - return s -} - -// SetProgress sets the Progress field's value. -func (s *InstanceSnapshot) SetProgress(v string) *InstanceSnapshot { - s.Progress = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *InstanceSnapshot) SetResourceType(v string) *InstanceSnapshot { - s.ResourceType = &v - return s -} - -// SetSizeInGb sets the SizeInGb field's value. -func (s *InstanceSnapshot) SetSizeInGb(v int64) *InstanceSnapshot { - s.SizeInGb = &v - return s -} - -// SetState sets the State field's value. -func (s *InstanceSnapshot) SetState(v string) *InstanceSnapshot { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *InstanceSnapshot) SetSupportCode(v string) *InstanceSnapshot { - s.SupportCode = &v - return s -} - -// Describes the virtual private server (or instance) status. -type InstanceState struct { - _ struct{} `type:"structure"` - - // The status code for the instance. - Code *int64 `locationName:"code" type:"integer"` - - // The state of the instance (e.g., running or pending). - Name *string `locationName:"name" type:"string"` -} - -// String returns the string representation -func (s InstanceState) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s InstanceState) GoString() string { - return s.String() -} - -// SetCode sets the Code field's value. -func (s *InstanceState) SetCode(v int64) *InstanceState { - s.Code = &v - return s -} - -// SetName sets the Name field's value. -func (s *InstanceState) SetName(v string) *InstanceState { - s.Name = &v - return s -} - -type IsVpcPeeredInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s IsVpcPeeredInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s IsVpcPeeredInput) GoString() string { - return s.String() -} - -type IsVpcPeeredOutput struct { - _ struct{} `type:"structure"` - - // Returns true if the Lightsail VPC is peered; otherwise, false. - IsPeered *bool `locationName:"isPeered" type:"boolean"` -} - -// String returns the string representation -func (s IsVpcPeeredOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s IsVpcPeeredOutput) GoString() string { - return s.String() -} - -// SetIsPeered sets the IsPeered field's value. -func (s *IsVpcPeeredOutput) SetIsPeered(v bool) *IsVpcPeeredOutput { - s.IsPeered = &v - return s -} - -// Describes the SSH key pair. -type KeyPair struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the key pair (e.g., arn:aws:lightsail:us-east-2:123456789101:KeyPair/05859e3d-331d-48ba-9034-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The timestamp when the key pair was created (e.g., 1479816991.349). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The RSA fingerprint of the key pair. - Fingerprint *string `locationName:"fingerprint" type:"string"` - - // The region name and Availability Zone where the key pair was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The friendly name of the SSH key pair. - Name *string `locationName:"name" type:"string"` - - // The resource type (usually KeyPair). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s KeyPair) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s KeyPair) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *KeyPair) SetArn(v string) *KeyPair { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *KeyPair) SetCreatedAt(v time.Time) *KeyPair { - s.CreatedAt = &v - return s -} - -// SetFingerprint sets the Fingerprint field's value. -func (s *KeyPair) SetFingerprint(v string) *KeyPair { - s.Fingerprint = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *KeyPair) SetLocation(v *ResourceLocation) *KeyPair { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *KeyPair) SetName(v string) *KeyPair { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *KeyPair) SetResourceType(v string) *KeyPair { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *KeyPair) SetSupportCode(v string) *KeyPair { - s.SupportCode = &v - return s -} - -// Describes the Lightsail load balancer. -type LoadBalancer struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the load balancer. - Arn *string `locationName:"arn" type:"string"` - - // A string to string map of the configuration options for your load balancer. - // Valid values are listed below. - ConfigurationOptions map[string]*string `locationName:"configurationOptions" type:"map"` - - // The date when your load balancer was created. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The DNS name of your Lightsail load balancer. - DnsName *string `locationName:"dnsName" type:"string"` - - // The path you specified to perform your health checks. If no path is specified, - // the load balancer tries to make a request to the default (root) page. - HealthCheckPath *string `locationName:"healthCheckPath" type:"string"` - - // An array of InstanceHealthSummary objects describing the health of the load - // balancer. - InstanceHealthSummary []*InstanceHealthSummary `locationName:"instanceHealthSummary" type:"list"` - - // The port where the load balancer will direct traffic to your Lightsail instances. - // For HTTP traffic, it's port 80. For HTTPS traffic, it's port 443. - InstancePort *int64 `locationName:"instancePort" type:"integer"` - - // The AWS Region where your load balancer was created (e.g., us-east-2a). Lightsail - // automatically creates your load balancer across Availability Zones. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the load balancer (e.g., my-load-balancer). - Name *string `locationName:"name" type:"string"` - - // The protocol you have enabled for your load balancer. Valid values are below. - // - // You can't just have HTTP_HTTPS, but you can have just HTTP. - Protocol *string `locationName:"protocol" type:"string" enum:"LoadBalancerProtocol"` - - // An array of public port settings for your load balancer. For HTTP, use port - // 80. For HTTPS, use port 443. - PublicPorts []*int64 `locationName:"publicPorts" type:"list"` - - // The resource type (e.g., LoadBalancer. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The status of your load balancer. Valid values are below. - State *string `locationName:"state" type:"string" enum:"LoadBalancerState"` - - // The support code. Include this code in your email to support when you have - // questions about your Lightsail load balancer. This code enables our support - // team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` - - // An array of LoadBalancerTlsCertificateSummary objects that provide additional - // information about the SSL/TLS certificates. For example, if true, the certificate - // is attached to the load balancer. - TlsCertificateSummaries []*LoadBalancerTlsCertificateSummary `locationName:"tlsCertificateSummaries" type:"list"` -} - -// String returns the string representation -func (s LoadBalancer) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancer) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LoadBalancer) SetArn(v string) *LoadBalancer { - s.Arn = &v - return s -} - -// SetConfigurationOptions sets the ConfigurationOptions field's value. -func (s *LoadBalancer) SetConfigurationOptions(v map[string]*string) *LoadBalancer { - s.ConfigurationOptions = v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *LoadBalancer) SetCreatedAt(v time.Time) *LoadBalancer { - s.CreatedAt = &v - return s -} - -// SetDnsName sets the DnsName field's value. -func (s *LoadBalancer) SetDnsName(v string) *LoadBalancer { - s.DnsName = &v - return s -} - -// SetHealthCheckPath sets the HealthCheckPath field's value. -func (s *LoadBalancer) SetHealthCheckPath(v string) *LoadBalancer { - s.HealthCheckPath = &v - return s -} - -// SetInstanceHealthSummary sets the InstanceHealthSummary field's value. -func (s *LoadBalancer) SetInstanceHealthSummary(v []*InstanceHealthSummary) *LoadBalancer { - s.InstanceHealthSummary = v - return s -} - -// SetInstancePort sets the InstancePort field's value. -func (s *LoadBalancer) SetInstancePort(v int64) *LoadBalancer { - s.InstancePort = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *LoadBalancer) SetLocation(v *ResourceLocation) *LoadBalancer { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancer) SetName(v string) *LoadBalancer { - s.Name = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *LoadBalancer) SetProtocol(v string) *LoadBalancer { - s.Protocol = &v - return s -} - -// SetPublicPorts sets the PublicPorts field's value. -func (s *LoadBalancer) SetPublicPorts(v []*int64) *LoadBalancer { - s.PublicPorts = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *LoadBalancer) SetResourceType(v string) *LoadBalancer { - s.ResourceType = &v - return s -} - -// SetState sets the State field's value. -func (s *LoadBalancer) SetState(v string) *LoadBalancer { - s.State = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *LoadBalancer) SetSupportCode(v string) *LoadBalancer { - s.SupportCode = &v - return s -} - -// SetTlsCertificateSummaries sets the TlsCertificateSummaries field's value. -func (s *LoadBalancer) SetTlsCertificateSummaries(v []*LoadBalancerTlsCertificateSummary) *LoadBalancer { - s.TlsCertificateSummaries = v - return s -} - -// Describes a load balancer SSL/TLS certificate. -// -// TLS is just an updated, more secure version of Secure Socket Layer (SSL). -type LoadBalancerTlsCertificate struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the SSL/TLS certificate. - Arn *string `locationName:"arn" type:"string"` - - // The time when you created your SSL/TLS certificate. - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The domain name for your SSL/TLS certificate. - DomainName *string `locationName:"domainName" type:"string"` - - // An array of LoadBalancerTlsCertificateDomainValidationRecord objects describing - // the records. - DomainValidationRecords []*LoadBalancerTlsCertificateDomainValidationRecord `locationName:"domainValidationRecords" type:"list"` - - // The reason for the SSL/TLS certificate validation failure. - FailureReason *string `locationName:"failureReason" type:"string" enum:"LoadBalancerTlsCertificateFailureReason"` - - // When true, the SSL/TLS certificate is attached to the Lightsail load balancer. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The time when the SSL/TLS certificate was issued. - IssuedAt *time.Time `locationName:"issuedAt" type:"timestamp" timestampFormat:"unix"` - - // The issuer of the certificate. - Issuer *string `locationName:"issuer" type:"string"` - - // The algorithm that was used to generate the key pair (the public and private - // key). - KeyAlgorithm *string `locationName:"keyAlgorithm" type:"string"` - - // The load balancer name where your SSL/TLS certificate is attached. - LoadBalancerName *string `locationName:"loadBalancerName" type:"string"` - - // The AWS Region and Availability Zone where you created your certificate. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the SSL/TLS certificate (e.g., my-certificate). - Name *string `locationName:"name" type:"string"` - - // The timestamp when the SSL/TLS certificate expires. - NotAfter *time.Time `locationName:"notAfter" type:"timestamp" timestampFormat:"unix"` - - // The timestamp when the SSL/TLS certificate is first valid. - NotBefore *time.Time `locationName:"notBefore" type:"timestamp" timestampFormat:"unix"` - - // An object containing information about the status of Lightsail's managed - // renewal for the certificate. - RenewalSummary *LoadBalancerTlsCertificateRenewalSummary `locationName:"renewalSummary" type:"structure"` - - // The resource type (e.g., LoadBalancerTlsCertificate). - // - // * Instance - A Lightsail instance (a virtual private server) - // - // * StaticIp - A static IP address - // - // * KeyPair - The key pair used to connect to a Lightsail instance - // - // * InstanceSnapshot - A Lightsail instance snapshot - // - // * Domain - A DNS zone - // - // * PeeredVpc - A peered VPC - // - // * LoadBalancer - A Lightsail load balancer - // - // * LoadBalancerTlsCertificate - An SSL/TLS certificate associated with - // a Lightsail load balancer - // - // * Disk - A Lightsail block storage disk - // - // * DiskSnapshot - A block storage disk snapshot - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The reason the certificate was revoked. Valid values are below. - RevocationReason *string `locationName:"revocationReason" type:"string" enum:"LoadBalancerTlsCertificateRevocationReason"` - - // The timestamp when the SSL/TLS certificate was revoked. - RevokedAt *time.Time `locationName:"revokedAt" type:"timestamp" timestampFormat:"unix"` - - // The serial number of the certificate. - Serial *string `locationName:"serial" type:"string"` - - // The algorithm that was used to sign the certificate. - SignatureAlgorithm *string `locationName:"signatureAlgorithm" type:"string"` - - // The status of the SSL/TLS certificate. Valid values are below. - Status *string `locationName:"status" type:"string" enum:"LoadBalancerTlsCertificateStatus"` - - // The name of the entity that is associated with the public key contained in - // the certificate. - Subject *string `locationName:"subject" type:"string"` - - // One or more domains or subdomains included in the certificate. This list - // contains the domain names that are bound to the public key that is contained - // in the certificate. The subject alternative names include the canonical domain - // name (CNAME) of the certificate and additional domain names that can be used - // to connect to the website, such as example.com, www.example.com, or m.example.com. - SubjectAlternativeNames []*string `locationName:"subjectAlternativeNames" type:"list"` - - // The support code. Include this code in your email to support when you have - // questions about your Lightsail load balancer or SSL/TLS certificate. This - // code enables our support team to look up your Lightsail information more - // easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificate) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificate) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *LoadBalancerTlsCertificate) SetArn(v string) *LoadBalancerTlsCertificate { - s.Arn = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *LoadBalancerTlsCertificate) SetCreatedAt(v time.Time) *LoadBalancerTlsCertificate { - s.CreatedAt = &v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificate) SetDomainName(v string) *LoadBalancerTlsCertificate { - s.DomainName = &v - return s -} - -// SetDomainValidationRecords sets the DomainValidationRecords field's value. -func (s *LoadBalancerTlsCertificate) SetDomainValidationRecords(v []*LoadBalancerTlsCertificateDomainValidationRecord) *LoadBalancerTlsCertificate { - s.DomainValidationRecords = v - return s -} - -// SetFailureReason sets the FailureReason field's value. -func (s *LoadBalancerTlsCertificate) SetFailureReason(v string) *LoadBalancerTlsCertificate { - s.FailureReason = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *LoadBalancerTlsCertificate) SetIsAttached(v bool) *LoadBalancerTlsCertificate { - s.IsAttached = &v - return s -} - -// SetIssuedAt sets the IssuedAt field's value. -func (s *LoadBalancerTlsCertificate) SetIssuedAt(v time.Time) *LoadBalancerTlsCertificate { - s.IssuedAt = &v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *LoadBalancerTlsCertificate) SetIssuer(v string) *LoadBalancerTlsCertificate { - s.Issuer = &v - return s -} - -// SetKeyAlgorithm sets the KeyAlgorithm field's value. -func (s *LoadBalancerTlsCertificate) SetKeyAlgorithm(v string) *LoadBalancerTlsCertificate { - s.KeyAlgorithm = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *LoadBalancerTlsCertificate) SetLoadBalancerName(v string) *LoadBalancerTlsCertificate { - s.LoadBalancerName = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *LoadBalancerTlsCertificate) SetLocation(v *ResourceLocation) *LoadBalancerTlsCertificate { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificate) SetName(v string) *LoadBalancerTlsCertificate { - s.Name = &v - return s -} - -// SetNotAfter sets the NotAfter field's value. -func (s *LoadBalancerTlsCertificate) SetNotAfter(v time.Time) *LoadBalancerTlsCertificate { - s.NotAfter = &v - return s -} - -// SetNotBefore sets the NotBefore field's value. -func (s *LoadBalancerTlsCertificate) SetNotBefore(v time.Time) *LoadBalancerTlsCertificate { - s.NotBefore = &v - return s -} - -// SetRenewalSummary sets the RenewalSummary field's value. -func (s *LoadBalancerTlsCertificate) SetRenewalSummary(v *LoadBalancerTlsCertificateRenewalSummary) *LoadBalancerTlsCertificate { - s.RenewalSummary = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *LoadBalancerTlsCertificate) SetResourceType(v string) *LoadBalancerTlsCertificate { - s.ResourceType = &v - return s -} - -// SetRevocationReason sets the RevocationReason field's value. -func (s *LoadBalancerTlsCertificate) SetRevocationReason(v string) *LoadBalancerTlsCertificate { - s.RevocationReason = &v - return s -} - -// SetRevokedAt sets the RevokedAt field's value. -func (s *LoadBalancerTlsCertificate) SetRevokedAt(v time.Time) *LoadBalancerTlsCertificate { - s.RevokedAt = &v - return s -} - -// SetSerial sets the Serial field's value. -func (s *LoadBalancerTlsCertificate) SetSerial(v string) *LoadBalancerTlsCertificate { - s.Serial = &v - return s -} - -// SetSignatureAlgorithm sets the SignatureAlgorithm field's value. -func (s *LoadBalancerTlsCertificate) SetSignatureAlgorithm(v string) *LoadBalancerTlsCertificate { - s.SignatureAlgorithm = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *LoadBalancerTlsCertificate) SetStatus(v string) *LoadBalancerTlsCertificate { - s.Status = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *LoadBalancerTlsCertificate) SetSubject(v string) *LoadBalancerTlsCertificate { - s.Subject = &v - return s -} - -// SetSubjectAlternativeNames sets the SubjectAlternativeNames field's value. -func (s *LoadBalancerTlsCertificate) SetSubjectAlternativeNames(v []*string) *LoadBalancerTlsCertificate { - s.SubjectAlternativeNames = v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *LoadBalancerTlsCertificate) SetSupportCode(v string) *LoadBalancerTlsCertificate { - s.SupportCode = &v - return s -} - -// Contains information about the domain names on an SSL/TLS certificate that -// you will use to validate domain ownership. -type LoadBalancerTlsCertificateDomainValidationOption struct { - _ struct{} `type:"structure"` - - // The fully qualified domain name in the certificate request. - DomainName *string `locationName:"domainName" type:"string"` - - // The status of the domain validation. Valid values are listed below. - ValidationStatus *string `locationName:"validationStatus" type:"string" enum:"LoadBalancerTlsCertificateDomainStatus"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationOption) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationOption) GoString() string { - return s.String() -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificateDomainValidationOption) SetDomainName(v string) *LoadBalancerTlsCertificateDomainValidationOption { - s.DomainName = &v - return s -} - -// SetValidationStatus sets the ValidationStatus field's value. -func (s *LoadBalancerTlsCertificateDomainValidationOption) SetValidationStatus(v string) *LoadBalancerTlsCertificateDomainValidationOption { - s.ValidationStatus = &v - return s -} - -// Describes the validation record of each domain name in the SSL/TLS certificate. -type LoadBalancerTlsCertificateDomainValidationRecord struct { - _ struct{} `type:"structure"` - - // The domain name against which your SSL/TLS certificate was validated. - DomainName *string `locationName:"domainName" type:"string"` - - // A fully qualified domain name in the certificate. For example, example.com. - Name *string `locationName:"name" type:"string"` - - // The type of validation record. For example, CNAME for domain validation. - Type *string `locationName:"type" type:"string"` - - // The validation status. Valid values are listed below. - ValidationStatus *string `locationName:"validationStatus" type:"string" enum:"LoadBalancerTlsCertificateDomainStatus"` - - // The value for that type. - Value *string `locationName:"value" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationRecord) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateDomainValidationRecord) GoString() string { - return s.String() -} - -// SetDomainName sets the DomainName field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetDomainName(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.DomainName = &v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetName(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Name = &v - return s -} - -// SetType sets the Type field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetType(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Type = &v - return s -} - -// SetValidationStatus sets the ValidationStatus field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetValidationStatus(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.ValidationStatus = &v - return s -} - -// SetValue sets the Value field's value. -func (s *LoadBalancerTlsCertificateDomainValidationRecord) SetValue(v string) *LoadBalancerTlsCertificateDomainValidationRecord { - s.Value = &v - return s -} - -// Contains information about the status of Lightsail's managed renewal for -// the certificate. -type LoadBalancerTlsCertificateRenewalSummary struct { - _ struct{} `type:"structure"` - - // Contains information about the validation of each domain name in the certificate, - // as it pertains to Lightsail's managed renewal. This is different from the - // initial validation that occurs as a result of the RequestCertificate request. - DomainValidationOptions []*LoadBalancerTlsCertificateDomainValidationOption `locationName:"domainValidationOptions" type:"list"` - - // The status of Lightsail's managed renewal of the certificate. Valid values - // are listed below. - RenewalStatus *string `locationName:"renewalStatus" type:"string" enum:"LoadBalancerTlsCertificateRenewalStatus"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateRenewalSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateRenewalSummary) GoString() string { - return s.String() -} - -// SetDomainValidationOptions sets the DomainValidationOptions field's value. -func (s *LoadBalancerTlsCertificateRenewalSummary) SetDomainValidationOptions(v []*LoadBalancerTlsCertificateDomainValidationOption) *LoadBalancerTlsCertificateRenewalSummary { - s.DomainValidationOptions = v - return s -} - -// SetRenewalStatus sets the RenewalStatus field's value. -func (s *LoadBalancerTlsCertificateRenewalSummary) SetRenewalStatus(v string) *LoadBalancerTlsCertificateRenewalSummary { - s.RenewalStatus = &v - return s -} - -// Provides a summary of SSL/TLS certificate metadata. -type LoadBalancerTlsCertificateSummary struct { - _ struct{} `type:"structure"` - - // When true, the SSL/TLS certificate is attached to the Lightsail load balancer. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The name of the SSL/TLS certificate. - Name *string `locationName:"name" type:"string"` -} - -// String returns the string representation -func (s LoadBalancerTlsCertificateSummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LoadBalancerTlsCertificateSummary) GoString() string { - return s.String() -} - -// SetIsAttached sets the IsAttached field's value. -func (s *LoadBalancerTlsCertificateSummary) SetIsAttached(v bool) *LoadBalancerTlsCertificateSummary { - s.IsAttached = &v - return s -} - -// SetName sets the Name field's value. -func (s *LoadBalancerTlsCertificateSummary) SetName(v string) *LoadBalancerTlsCertificateSummary { - s.Name = &v - return s -} - -// Describes the metric data point. -type MetricDatapoint struct { - _ struct{} `type:"structure"` - - // The average. - Average *float64 `locationName:"average" type:"double"` - - // The maximum. - Maximum *float64 `locationName:"maximum" type:"double"` - - // The minimum. - Minimum *float64 `locationName:"minimum" type:"double"` - - // The sample count. - SampleCount *float64 `locationName:"sampleCount" type:"double"` - - // The sum. - Sum *float64 `locationName:"sum" type:"double"` - - // The timestamp (e.g., 1479816991.349). - Timestamp *time.Time `locationName:"timestamp" type:"timestamp" timestampFormat:"unix"` - - // The unit. - Unit *string `locationName:"unit" type:"string" enum:"MetricUnit"` -} - -// String returns the string representation -func (s MetricDatapoint) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MetricDatapoint) GoString() string { - return s.String() -} - -// SetAverage sets the Average field's value. -func (s *MetricDatapoint) SetAverage(v float64) *MetricDatapoint { - s.Average = &v - return s -} - -// SetMaximum sets the Maximum field's value. -func (s *MetricDatapoint) SetMaximum(v float64) *MetricDatapoint { - s.Maximum = &v - return s -} - -// SetMinimum sets the Minimum field's value. -func (s *MetricDatapoint) SetMinimum(v float64) *MetricDatapoint { - s.Minimum = &v - return s -} - -// SetSampleCount sets the SampleCount field's value. -func (s *MetricDatapoint) SetSampleCount(v float64) *MetricDatapoint { - s.SampleCount = &v - return s -} - -// SetSum sets the Sum field's value. -func (s *MetricDatapoint) SetSum(v float64) *MetricDatapoint { - s.Sum = &v - return s -} - -// SetTimestamp sets the Timestamp field's value. -func (s *MetricDatapoint) SetTimestamp(v time.Time) *MetricDatapoint { - s.Timestamp = &v - return s -} - -// SetUnit sets the Unit field's value. -func (s *MetricDatapoint) SetUnit(v string) *MetricDatapoint { - s.Unit = &v - return s -} - -// Describes the monthly data transfer in and out of your virtual private server -// (or instance). -type MonthlyTransfer struct { - _ struct{} `type:"structure"` - - // The amount allocated per month (in GB). - GbPerMonthAllocated *int64 `locationName:"gbPerMonthAllocated" type:"integer"` -} - -// String returns the string representation -func (s MonthlyTransfer) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s MonthlyTransfer) GoString() string { - return s.String() -} - -// SetGbPerMonthAllocated sets the GbPerMonthAllocated field's value. -func (s *MonthlyTransfer) SetGbPerMonthAllocated(v int64) *MonthlyTransfer { - s.GbPerMonthAllocated = &v - return s -} - -type OpenInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The name of the instance for which you want to open the public ports. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // An array of key-value pairs containing information about the port mappings. - // - // PortInfo is a required field - PortInfo *PortInfo `locationName:"portInfo" type:"structure" required:"true"` -} - -// String returns the string representation -func (s OpenInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OpenInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *OpenInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "OpenInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfo == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfo")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *OpenInstancePublicPortsInput) SetInstanceName(v string) *OpenInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfo sets the PortInfo field's value. -func (s *OpenInstancePublicPortsInput) SetPortInfo(v *PortInfo) *OpenInstancePublicPortsInput { - s.PortInfo = v - return s -} - -type OpenInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s OpenInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s OpenInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *OpenInstancePublicPortsOutput) SetOperation(v *Operation) *OpenInstancePublicPortsOutput { - s.Operation = v - return s -} - -// Describes the API operation. -type Operation struct { - _ struct{} `type:"structure"` - - // The timestamp when the operation was initialized (e.g., 1479816991.349). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The error code. - ErrorCode *string `locationName:"errorCode" type:"string"` - - // The error details. - ErrorDetails *string `locationName:"errorDetails" type:"string"` - - // The ID of the operation. - Id *string `locationName:"id" type:"string"` - - // A Boolean value indicating whether the operation is terminal. - IsTerminal *bool `locationName:"isTerminal" type:"boolean"` - - // The region and Availability Zone. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // Details about the operation (e.g., Debian-1GB-Ohio-1). - OperationDetails *string `locationName:"operationDetails" type:"string"` - - // The type of operation. - OperationType *string `locationName:"operationType" type:"string" enum:"OperationType"` - - // The resource name. - ResourceName *string `locationName:"resourceName" type:"string"` - - // The resource type. - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The status of the operation. - Status *string `locationName:"status" type:"string" enum:"OperationStatus"` - - // The timestamp when the status was changed (e.g., 1479816991.349). - StatusChangedAt *time.Time `locationName:"statusChangedAt" type:"timestamp" timestampFormat:"unix"` -} - -// String returns the string representation -func (s Operation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Operation) GoString() string { - return s.String() -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *Operation) SetCreatedAt(v time.Time) *Operation { - s.CreatedAt = &v - return s -} - -// SetErrorCode sets the ErrorCode field's value. -func (s *Operation) SetErrorCode(v string) *Operation { - s.ErrorCode = &v - return s -} - -// SetErrorDetails sets the ErrorDetails field's value. -func (s *Operation) SetErrorDetails(v string) *Operation { - s.ErrorDetails = &v - return s -} - -// SetId sets the Id field's value. -func (s *Operation) SetId(v string) *Operation { - s.Id = &v - return s -} - -// SetIsTerminal sets the IsTerminal field's value. -func (s *Operation) SetIsTerminal(v bool) *Operation { - s.IsTerminal = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *Operation) SetLocation(v *ResourceLocation) *Operation { - s.Location = v - return s -} - -// SetOperationDetails sets the OperationDetails field's value. -func (s *Operation) SetOperationDetails(v string) *Operation { - s.OperationDetails = &v - return s -} - -// SetOperationType sets the OperationType field's value. -func (s *Operation) SetOperationType(v string) *Operation { - s.OperationType = &v - return s -} - -// SetResourceName sets the ResourceName field's value. -func (s *Operation) SetResourceName(v string) *Operation { - s.ResourceName = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *Operation) SetResourceType(v string) *Operation { - s.ResourceType = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *Operation) SetStatus(v string) *Operation { - s.Status = &v - return s -} - -// SetStatusChangedAt sets the StatusChangedAt field's value. -func (s *Operation) SetStatusChangedAt(v time.Time) *Operation { - s.StatusChangedAt = &v - return s -} - -// The password data for the Windows Server-based instance, including the ciphertext -// and the key pair name. -type PasswordData struct { - _ struct{} `type:"structure"` - - // The encrypted password. Ciphertext will be an empty string if access to your - // new instance is not ready yet. When you create an instance, it can take up - // to 15 minutes for the instance to be ready. - // - // If you use the default key pair (LightsailDefaultKeyPair), the decrypted - // password will be available in the password field. - // - // If you are using a custom key pair, you need to use your own means of decryption. - // - // If you change the Administrator password on the instance, Lightsail will - // continue to return the original ciphertext value. When accessing the instance - // using RDP, you need to manually enter the Administrator password after changing - // it from the default. - Ciphertext *string `locationName:"ciphertext" type:"string"` - - // The name of the key pair that you used when creating your instance. If no - // key pair name was specified when creating the instance, Lightsail uses the - // default key pair (LightsailDefaultKeyPair). - // - // If you are using a custom key pair, you need to use your own means of decrypting - // your password using the ciphertext. Lightsail creates the ciphertext by encrypting - // your password with the public key part of this key pair. - KeyPairName *string `locationName:"keyPairName" type:"string"` -} - -// String returns the string representation -func (s PasswordData) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PasswordData) GoString() string { - return s.String() -} - -// SetCiphertext sets the Ciphertext field's value. -func (s *PasswordData) SetCiphertext(v string) *PasswordData { - s.Ciphertext = &v - return s -} - -// SetKeyPairName sets the KeyPairName field's value. -func (s *PasswordData) SetKeyPairName(v string) *PasswordData { - s.KeyPairName = &v - return s -} - -type PeerVpcInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s PeerVpcInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PeerVpcInput) GoString() string { - return s.String() -} - -type PeerVpcOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s PeerVpcOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PeerVpcOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *PeerVpcOutput) SetOperation(v *Operation) *PeerVpcOutput { - s.Operation = v - return s -} - -// Describes information about the ports on your virtual private server (or -// instance). -type PortInfo struct { - _ struct{} `type:"structure"` - - // The first port in the range. - FromPort *int64 `locationName:"fromPort" type:"integer"` - - // The protocol. - Protocol *string `locationName:"protocol" type:"string" enum:"NetworkProtocol"` - - // The last port in the range. - ToPort *int64 `locationName:"toPort" type:"integer"` -} - -// String returns the string representation -func (s PortInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PortInfo) GoString() string { - return s.String() -} - -// SetFromPort sets the FromPort field's value. -func (s *PortInfo) SetFromPort(v int64) *PortInfo { - s.FromPort = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *PortInfo) SetProtocol(v string) *PortInfo { - s.Protocol = &v - return s -} - -// SetToPort sets the ToPort field's value. -func (s *PortInfo) SetToPort(v int64) *PortInfo { - s.ToPort = &v - return s -} - -type PutInstancePublicPortsInput struct { - _ struct{} `type:"structure"` - - // The Lightsail instance name of the public port(s) you are setting. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` - - // Specifies information about the public port(s). - // - // PortInfos is a required field - PortInfos []*PortInfo `locationName:"portInfos" type:"list" required:"true"` -} - -// String returns the string representation -func (s PutInstancePublicPortsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutInstancePublicPortsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *PutInstancePublicPortsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "PutInstancePublicPortsInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - if s.PortInfos == nil { - invalidParams.Add(request.NewErrParamRequired("PortInfos")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *PutInstancePublicPortsInput) SetInstanceName(v string) *PutInstancePublicPortsInput { - s.InstanceName = &v - return s -} - -// SetPortInfos sets the PortInfos field's value. -func (s *PutInstancePublicPortsInput) SetPortInfos(v []*PortInfo) *PutInstancePublicPortsInput { - s.PortInfos = v - return s -} - -type PutInstancePublicPortsOutput struct { - _ struct{} `type:"structure"` - - // Describes metadata about the operation you just executed. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s PutInstancePublicPortsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s PutInstancePublicPortsOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *PutInstancePublicPortsOutput) SetOperation(v *Operation) *PutInstancePublicPortsOutput { - s.Operation = v - return s -} - -type RebootInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance to reboot. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s RebootInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RebootInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *RebootInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "RebootInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *RebootInstanceInput) SetInstanceName(v string) *RebootInstanceInput { - s.InstanceName = &v - return s -} - -type RebootInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s RebootInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s RebootInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *RebootInstanceOutput) SetOperations(v []*Operation) *RebootInstanceOutput { - s.Operations = v - return s -} - -// Describes the AWS Region. -type Region struct { - _ struct{} `type:"structure"` - - // The Availability Zones. Follows the format us-east-2a (case-sensitive). - AvailabilityZones []*AvailabilityZone `locationName:"availabilityZones" type:"list"` - - // The continent code (e.g., NA, meaning North America). - ContinentCode *string `locationName:"continentCode" type:"string"` - - // The description of the AWS Region (e.g., This region is recommended to serve - // users in the eastern United States and eastern Canada). - Description *string `locationName:"description" type:"string"` - - // The display name (e.g., Ohio). - DisplayName *string `locationName:"displayName" type:"string"` - - // The region name (e.g., us-east-2). - Name *string `locationName:"name" type:"string" enum:"RegionName"` -} - -// String returns the string representation -func (s Region) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Region) GoString() string { - return s.String() -} - -// SetAvailabilityZones sets the AvailabilityZones field's value. -func (s *Region) SetAvailabilityZones(v []*AvailabilityZone) *Region { - s.AvailabilityZones = v - return s -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *Region) SetContinentCode(v string) *Region { - s.ContinentCode = &v - return s -} - -// SetDescription sets the Description field's value. -func (s *Region) SetDescription(v string) *Region { - s.Description = &v - return s -} - -// SetDisplayName sets the DisplayName field's value. -func (s *Region) SetDisplayName(v string) *Region { - s.DisplayName = &v - return s -} - -// SetName sets the Name field's value. -func (s *Region) SetName(v string) *Region { - s.Name = &v - return s -} - -type ReleaseStaticIpInput struct { - _ struct{} `type:"structure"` - - // The name of the static IP to delete. - // - // StaticIpName is a required field - StaticIpName *string `locationName:"staticIpName" type:"string" required:"true"` -} - -// String returns the string representation -func (s ReleaseStaticIpInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReleaseStaticIpInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ReleaseStaticIpInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ReleaseStaticIpInput"} - if s.StaticIpName == nil { - invalidParams.Add(request.NewErrParamRequired("StaticIpName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetStaticIpName sets the StaticIpName field's value. -func (s *ReleaseStaticIpInput) SetStaticIpName(v string) *ReleaseStaticIpInput { - s.StaticIpName = &v - return s -} - -type ReleaseStaticIpOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s ReleaseStaticIpOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReleaseStaticIpOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *ReleaseStaticIpOutput) SetOperations(v []*Operation) *ReleaseStaticIpOutput { - s.Operations = v - return s -} - -// Describes the resource location. -type ResourceLocation struct { - _ struct{} `type:"structure"` - - // The Availability Zone. Follows the format us-east-2a (case-sensitive). - AvailabilityZone *string `locationName:"availabilityZone" type:"string"` - - // The AWS Region name. - RegionName *string `locationName:"regionName" type:"string" enum:"RegionName"` -} - -// String returns the string representation -func (s ResourceLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceLocation) GoString() string { - return s.String() -} - -// SetAvailabilityZone sets the AvailabilityZone field's value. -func (s *ResourceLocation) SetAvailabilityZone(v string) *ResourceLocation { - s.AvailabilityZone = &v - return s -} - -// SetRegionName sets the RegionName field's value. -func (s *ResourceLocation) SetRegionName(v string) *ResourceLocation { - s.RegionName = &v - return s -} - -type StartInstanceInput struct { - _ struct{} `type:"structure"` - - // The name of the instance (a virtual private server) to start. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s StartInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StartInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StartInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StartInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetInstanceName sets the InstanceName field's value. -func (s *StartInstanceInput) SetInstanceName(v string) *StartInstanceInput { - s.InstanceName = &v - return s -} - -type StartInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s StartInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StartInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *StartInstanceOutput) SetOperations(v []*Operation) *StartInstanceOutput { - s.Operations = v - return s -} - -// Describes the static IP. -type StaticIp struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the static IP (e.g., arn:aws:lightsail:us-east-2:123456789101:StaticIp/9cbb4a9e-f8e3-4dfe-b57e-12345EXAMPLE). - Arn *string `locationName:"arn" type:"string"` - - // The instance where the static IP is attached (e.g., Amazon_Linux-1GB-Ohio-1). - AttachedTo *string `locationName:"attachedTo" type:"string"` - - // The timestamp when the static IP was created (e.g., 1479735304.222). - CreatedAt *time.Time `locationName:"createdAt" type:"timestamp" timestampFormat:"unix"` - - // The static IP address. - IpAddress *string `locationName:"ipAddress" type:"string"` - - // A Boolean value indicating whether the static IP is attached. - IsAttached *bool `locationName:"isAttached" type:"boolean"` - - // The region and Availability Zone where the static IP was created. - Location *ResourceLocation `locationName:"location" type:"structure"` - - // The name of the static IP (e.g., StaticIP-Ohio-EXAMPLE). - Name *string `locationName:"name" type:"string"` - - // The resource type (usually StaticIp). - ResourceType *string `locationName:"resourceType" type:"string" enum:"ResourceType"` - - // The support code. Include this code in your email to support when you have - // questions about an instance or another resource in Lightsail. This code enables - // our support team to look up your Lightsail information more easily. - SupportCode *string `locationName:"supportCode" type:"string"` -} - -// String returns the string representation -func (s StaticIp) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StaticIp) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *StaticIp) SetArn(v string) *StaticIp { - s.Arn = &v - return s -} - -// SetAttachedTo sets the AttachedTo field's value. -func (s *StaticIp) SetAttachedTo(v string) *StaticIp { - s.AttachedTo = &v - return s -} - -// SetCreatedAt sets the CreatedAt field's value. -func (s *StaticIp) SetCreatedAt(v time.Time) *StaticIp { - s.CreatedAt = &v - return s -} - -// SetIpAddress sets the IpAddress field's value. -func (s *StaticIp) SetIpAddress(v string) *StaticIp { - s.IpAddress = &v - return s -} - -// SetIsAttached sets the IsAttached field's value. -func (s *StaticIp) SetIsAttached(v bool) *StaticIp { - s.IsAttached = &v - return s -} - -// SetLocation sets the Location field's value. -func (s *StaticIp) SetLocation(v *ResourceLocation) *StaticIp { - s.Location = v - return s -} - -// SetName sets the Name field's value. -func (s *StaticIp) SetName(v string) *StaticIp { - s.Name = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *StaticIp) SetResourceType(v string) *StaticIp { - s.ResourceType = &v - return s -} - -// SetSupportCode sets the SupportCode field's value. -func (s *StaticIp) SetSupportCode(v string) *StaticIp { - s.SupportCode = &v - return s -} - -type StopInstanceInput struct { - _ struct{} `type:"structure"` - - // When set to True, forces a Lightsail instance that is stuck in a stopping - // state to stop. - // - // Only use the force parameter if your instance is stuck in the stopping state. - // In any other state, your instance should stop normally without adding this - // parameter to your API request. - Force *bool `locationName:"force" type:"boolean"` - - // The name of the instance (a virtual private server) to stop. - // - // InstanceName is a required field - InstanceName *string `locationName:"instanceName" type:"string" required:"true"` -} - -// String returns the string representation -func (s StopInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StopInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *StopInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "StopInstanceInput"} - if s.InstanceName == nil { - invalidParams.Add(request.NewErrParamRequired("InstanceName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetForce sets the Force field's value. -func (s *StopInstanceInput) SetForce(v bool) *StopInstanceInput { - s.Force = &v - return s -} - -// SetInstanceName sets the InstanceName field's value. -func (s *StopInstanceInput) SetInstanceName(v string) *StopInstanceInput { - s.InstanceName = &v - return s -} - -type StopInstanceOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s StopInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StopInstanceOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *StopInstanceOutput) SetOperations(v []*Operation) *StopInstanceOutput { - s.Operations = v - return s -} - -type UnpeerVpcInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s UnpeerVpcInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UnpeerVpcInput) GoString() string { - return s.String() -} - -type UnpeerVpcOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operation *Operation `locationName:"operation" type:"structure"` -} - -// String returns the string representation -func (s UnpeerVpcOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UnpeerVpcOutput) GoString() string { - return s.String() -} - -// SetOperation sets the Operation field's value. -func (s *UnpeerVpcOutput) SetOperation(v *Operation) *UnpeerVpcOutput { - s.Operation = v - return s -} - -type UpdateDomainEntryInput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the domain entry. - // - // DomainEntry is a required field - DomainEntry *DomainEntry `locationName:"domainEntry" type:"structure" required:"true"` - - // The name of the domain recordset to update. - // - // DomainName is a required field - DomainName *string `locationName:"domainName" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateDomainEntryInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateDomainEntryInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateDomainEntryInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateDomainEntryInput"} - if s.DomainEntry == nil { - invalidParams.Add(request.NewErrParamRequired("DomainEntry")) - } - if s.DomainName == nil { - invalidParams.Add(request.NewErrParamRequired("DomainName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDomainEntry sets the DomainEntry field's value. -func (s *UpdateDomainEntryInput) SetDomainEntry(v *DomainEntry) *UpdateDomainEntryInput { - s.DomainEntry = v - return s -} - -// SetDomainName sets the DomainName field's value. -func (s *UpdateDomainEntryInput) SetDomainName(v string) *UpdateDomainEntryInput { - s.DomainName = &v - return s -} - -type UpdateDomainEntryOutput struct { - _ struct{} `type:"structure"` - - // An array of key-value pairs containing information about the request operation. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s UpdateDomainEntryOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateDomainEntryOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *UpdateDomainEntryOutput) SetOperations(v []*Operation) *UpdateDomainEntryOutput { - s.Operations = v - return s -} - -type UpdateLoadBalancerAttributeInput struct { - _ struct{} `type:"structure"` - - // The name of the attribute you want to update. Valid values are below. - // - // AttributeName is a required field - AttributeName *string `locationName:"attributeName" type:"string" required:"true" enum:"LoadBalancerAttributeName"` - - // The value that you want to specify for the attribute name. - // - // AttributeValue is a required field - AttributeValue *string `locationName:"attributeValue" min:"1" type:"string" required:"true"` - - // The name of the load balancer that you want to modify (e.g., my-load-balancer. - // - // LoadBalancerName is a required field - LoadBalancerName *string `locationName:"loadBalancerName" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateLoadBalancerAttributeInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateLoadBalancerAttributeInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateLoadBalancerAttributeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateLoadBalancerAttributeInput"} - if s.AttributeName == nil { - invalidParams.Add(request.NewErrParamRequired("AttributeName")) - } - if s.AttributeValue == nil { - invalidParams.Add(request.NewErrParamRequired("AttributeValue")) - } - if s.AttributeValue != nil && len(*s.AttributeValue) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AttributeValue", 1)) - } - if s.LoadBalancerName == nil { - invalidParams.Add(request.NewErrParamRequired("LoadBalancerName")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAttributeName sets the AttributeName field's value. -func (s *UpdateLoadBalancerAttributeInput) SetAttributeName(v string) *UpdateLoadBalancerAttributeInput { - s.AttributeName = &v - return s -} - -// SetAttributeValue sets the AttributeValue field's value. -func (s *UpdateLoadBalancerAttributeInput) SetAttributeValue(v string) *UpdateLoadBalancerAttributeInput { - s.AttributeValue = &v - return s -} - -// SetLoadBalancerName sets the LoadBalancerName field's value. -func (s *UpdateLoadBalancerAttributeInput) SetLoadBalancerName(v string) *UpdateLoadBalancerAttributeInput { - s.LoadBalancerName = &v - return s -} - -type UpdateLoadBalancerAttributeOutput struct { - _ struct{} `type:"structure"` - - // An object describing the API operations. - Operations []*Operation `locationName:"operations" type:"list"` -} - -// String returns the string representation -func (s UpdateLoadBalancerAttributeOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateLoadBalancerAttributeOutput) GoString() string { - return s.String() -} - -// SetOperations sets the Operations field's value. -func (s *UpdateLoadBalancerAttributeOutput) SetOperations(v []*Operation) *UpdateLoadBalancerAttributeOutput { - s.Operations = v - return s -} - -const ( - // AccessDirectionInbound is a AccessDirection enum value - AccessDirectionInbound = "inbound" - - // AccessDirectionOutbound is a AccessDirection enum value - AccessDirectionOutbound = "outbound" -) - -const ( - // BlueprintTypeOs is a BlueprintType enum value - BlueprintTypeOs = "os" - - // BlueprintTypeApp is a BlueprintType enum value - BlueprintTypeApp = "app" -) - -const ( - // DiskSnapshotStatePending is a DiskSnapshotState enum value - DiskSnapshotStatePending = "pending" - - // DiskSnapshotStateCompleted is a DiskSnapshotState enum value - DiskSnapshotStateCompleted = "completed" - - // DiskSnapshotStateError is a DiskSnapshotState enum value - DiskSnapshotStateError = "error" - - // DiskSnapshotStateUnknown is a DiskSnapshotState enum value - DiskSnapshotStateUnknown = "unknown" -) - -const ( - // DiskStatePending is a DiskState enum value - DiskStatePending = "pending" - - // DiskStateError is a DiskState enum value - DiskStateError = "error" - - // DiskStateAvailable is a DiskState enum value - DiskStateAvailable = "available" - - // DiskStateInUse is a DiskState enum value - DiskStateInUse = "in-use" - - // DiskStateUnknown is a DiskState enum value - DiskStateUnknown = "unknown" -) - -const ( - // InstanceAccessProtocolSsh is a InstanceAccessProtocol enum value - InstanceAccessProtocolSsh = "ssh" - - // InstanceAccessProtocolRdp is a InstanceAccessProtocol enum value - InstanceAccessProtocolRdp = "rdp" -) - -const ( - // InstanceHealthReasonLbRegistrationInProgress is a InstanceHealthReason enum value - InstanceHealthReasonLbRegistrationInProgress = "Lb.RegistrationInProgress" - - // InstanceHealthReasonLbInitialHealthChecking is a InstanceHealthReason enum value - InstanceHealthReasonLbInitialHealthChecking = "Lb.InitialHealthChecking" - - // InstanceHealthReasonLbInternalError is a InstanceHealthReason enum value - InstanceHealthReasonLbInternalError = "Lb.InternalError" - - // InstanceHealthReasonInstanceResponseCodeMismatch is a InstanceHealthReason enum value - InstanceHealthReasonInstanceResponseCodeMismatch = "Instance.ResponseCodeMismatch" - - // InstanceHealthReasonInstanceTimeout is a InstanceHealthReason enum value - InstanceHealthReasonInstanceTimeout = "Instance.Timeout" - - // InstanceHealthReasonInstanceFailedHealthChecks is a InstanceHealthReason enum value - InstanceHealthReasonInstanceFailedHealthChecks = "Instance.FailedHealthChecks" - - // InstanceHealthReasonInstanceNotRegistered is a InstanceHealthReason enum value - InstanceHealthReasonInstanceNotRegistered = "Instance.NotRegistered" - - // InstanceHealthReasonInstanceNotInUse is a InstanceHealthReason enum value - InstanceHealthReasonInstanceNotInUse = "Instance.NotInUse" - - // InstanceHealthReasonInstanceDeregistrationInProgress is a InstanceHealthReason enum value - InstanceHealthReasonInstanceDeregistrationInProgress = "Instance.DeregistrationInProgress" - - // InstanceHealthReasonInstanceInvalidState is a InstanceHealthReason enum value - InstanceHealthReasonInstanceInvalidState = "Instance.InvalidState" - - // InstanceHealthReasonInstanceIpUnusable is a InstanceHealthReason enum value - InstanceHealthReasonInstanceIpUnusable = "Instance.IpUnusable" -) - -const ( - // InstanceHealthStateInitial is a InstanceHealthState enum value - InstanceHealthStateInitial = "initial" - - // InstanceHealthStateHealthy is a InstanceHealthState enum value - InstanceHealthStateHealthy = "healthy" - - // InstanceHealthStateUnhealthy is a InstanceHealthState enum value - InstanceHealthStateUnhealthy = "unhealthy" - - // InstanceHealthStateUnused is a InstanceHealthState enum value - InstanceHealthStateUnused = "unused" - - // InstanceHealthStateDraining is a InstanceHealthState enum value - InstanceHealthStateDraining = "draining" - - // InstanceHealthStateUnavailable is a InstanceHealthState enum value - InstanceHealthStateUnavailable = "unavailable" -) - -const ( - // InstanceMetricNameCpuutilization is a InstanceMetricName enum value - InstanceMetricNameCpuutilization = "CPUUtilization" - - // InstanceMetricNameNetworkIn is a InstanceMetricName enum value - InstanceMetricNameNetworkIn = "NetworkIn" - - // InstanceMetricNameNetworkOut is a InstanceMetricName enum value - InstanceMetricNameNetworkOut = "NetworkOut" - - // InstanceMetricNameStatusCheckFailed is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailed = "StatusCheckFailed" - - // InstanceMetricNameStatusCheckFailedInstance is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailedInstance = "StatusCheckFailed_Instance" - - // InstanceMetricNameStatusCheckFailedSystem is a InstanceMetricName enum value - InstanceMetricNameStatusCheckFailedSystem = "StatusCheckFailed_System" -) - -const ( - // InstancePlatformLinuxUnix is a InstancePlatform enum value - InstancePlatformLinuxUnix = "LINUX_UNIX" - - // InstancePlatformWindows is a InstancePlatform enum value - InstancePlatformWindows = "WINDOWS" -) - -const ( - // InstanceSnapshotStatePending is a InstanceSnapshotState enum value - InstanceSnapshotStatePending = "pending" - - // InstanceSnapshotStateError is a InstanceSnapshotState enum value - InstanceSnapshotStateError = "error" - - // InstanceSnapshotStateAvailable is a InstanceSnapshotState enum value - InstanceSnapshotStateAvailable = "available" -) - -const ( - // LoadBalancerAttributeNameHealthCheckPath is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameHealthCheckPath = "HealthCheckPath" - - // LoadBalancerAttributeNameSessionStickinessEnabled is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameSessionStickinessEnabled = "SessionStickinessEnabled" - - // LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds is a LoadBalancerAttributeName enum value - LoadBalancerAttributeNameSessionStickinessLbCookieDurationSeconds = "SessionStickiness_LB_CookieDurationSeconds" -) - -const ( - // LoadBalancerMetricNameClientTlsnegotiationErrorCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameClientTlsnegotiationErrorCount = "ClientTLSNegotiationErrorCount" - - // LoadBalancerMetricNameHealthyHostCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHealthyHostCount = "HealthyHostCount" - - // LoadBalancerMetricNameUnhealthyHostCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameUnhealthyHostCount = "UnhealthyHostCount" - - // LoadBalancerMetricNameHttpcodeLb4xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeLb4xxCount = "HTTPCode_LB_4XX_Count" - - // LoadBalancerMetricNameHttpcodeLb5xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeLb5xxCount = "HTTPCode_LB_5XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance2xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance2xxCount = "HTTPCode_Instance_2XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance3xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance3xxCount = "HTTPCode_Instance_3XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance4xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance4xxCount = "HTTPCode_Instance_4XX_Count" - - // LoadBalancerMetricNameHttpcodeInstance5xxCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameHttpcodeInstance5xxCount = "HTTPCode_Instance_5XX_Count" - - // LoadBalancerMetricNameInstanceResponseTime is a LoadBalancerMetricName enum value - LoadBalancerMetricNameInstanceResponseTime = "InstanceResponseTime" - - // LoadBalancerMetricNameRejectedConnectionCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameRejectedConnectionCount = "RejectedConnectionCount" - - // LoadBalancerMetricNameRequestCount is a LoadBalancerMetricName enum value - LoadBalancerMetricNameRequestCount = "RequestCount" -) - -const ( - // LoadBalancerProtocolHttpHttps is a LoadBalancerProtocol enum value - LoadBalancerProtocolHttpHttps = "HTTP_HTTPS" - - // LoadBalancerProtocolHttp is a LoadBalancerProtocol enum value - LoadBalancerProtocolHttp = "HTTP" -) - -const ( - // LoadBalancerStateActive is a LoadBalancerState enum value - LoadBalancerStateActive = "active" - - // LoadBalancerStateProvisioning is a LoadBalancerState enum value - LoadBalancerStateProvisioning = "provisioning" - - // LoadBalancerStateActiveImpaired is a LoadBalancerState enum value - LoadBalancerStateActiveImpaired = "active_impaired" - - // LoadBalancerStateFailed is a LoadBalancerState enum value - LoadBalancerStateFailed = "failed" - - // LoadBalancerStateUnknown is a LoadBalancerState enum value - LoadBalancerStateUnknown = "unknown" -) - -const ( - // LoadBalancerTlsCertificateDomainStatusPendingValidation is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateDomainStatusFailed is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusFailed = "FAILED" - - // LoadBalancerTlsCertificateDomainStatusSuccess is a LoadBalancerTlsCertificateDomainStatus enum value - LoadBalancerTlsCertificateDomainStatusSuccess = "SUCCESS" -) - -const ( - // LoadBalancerTlsCertificateFailureReasonNoAvailableContacts is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonNoAvailableContacts = "NO_AVAILABLE_CONTACTS" - - // LoadBalancerTlsCertificateFailureReasonAdditionalVerificationRequired is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonAdditionalVerificationRequired = "ADDITIONAL_VERIFICATION_REQUIRED" - - // LoadBalancerTlsCertificateFailureReasonDomainNotAllowed is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonDomainNotAllowed = "DOMAIN_NOT_ALLOWED" - - // LoadBalancerTlsCertificateFailureReasonInvalidPublicDomain is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonInvalidPublicDomain = "INVALID_PUBLIC_DOMAIN" - - // LoadBalancerTlsCertificateFailureReasonOther is a LoadBalancerTlsCertificateFailureReason enum value - LoadBalancerTlsCertificateFailureReasonOther = "OTHER" -) - -const ( - // LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusPendingAutoRenewal = "PENDING_AUTO_RENEWAL" - - // LoadBalancerTlsCertificateRenewalStatusPendingValidation is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateRenewalStatusSuccess is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusSuccess = "SUCCESS" - - // LoadBalancerTlsCertificateRenewalStatusFailed is a LoadBalancerTlsCertificateRenewalStatus enum value - LoadBalancerTlsCertificateRenewalStatusFailed = "FAILED" -) - -const ( - // LoadBalancerTlsCertificateRevocationReasonUnspecified is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonUnspecified = "UNSPECIFIED" - - // LoadBalancerTlsCertificateRevocationReasonKeyCompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonKeyCompromise = "KEY_COMPROMISE" - - // LoadBalancerTlsCertificateRevocationReasonCaCompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCaCompromise = "CA_COMPROMISE" - - // LoadBalancerTlsCertificateRevocationReasonAffiliationChanged is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonAffiliationChanged = "AFFILIATION_CHANGED" - - // LoadBalancerTlsCertificateRevocationReasonSuperceded is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonSuperceded = "SUPERCEDED" - - // LoadBalancerTlsCertificateRevocationReasonCessationOfOperation is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCessationOfOperation = "CESSATION_OF_OPERATION" - - // LoadBalancerTlsCertificateRevocationReasonCertificateHold is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonCertificateHold = "CERTIFICATE_HOLD" - - // LoadBalancerTlsCertificateRevocationReasonRemoveFromCrl is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonRemoveFromCrl = "REMOVE_FROM_CRL" - - // LoadBalancerTlsCertificateRevocationReasonPrivilegeWithdrawn is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonPrivilegeWithdrawn = "PRIVILEGE_WITHDRAWN" - - // LoadBalancerTlsCertificateRevocationReasonAACompromise is a LoadBalancerTlsCertificateRevocationReason enum value - LoadBalancerTlsCertificateRevocationReasonAACompromise = "A_A_COMPROMISE" -) - -const ( - // LoadBalancerTlsCertificateStatusPendingValidation is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusPendingValidation = "PENDING_VALIDATION" - - // LoadBalancerTlsCertificateStatusIssued is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusIssued = "ISSUED" - - // LoadBalancerTlsCertificateStatusInactive is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusInactive = "INACTIVE" - - // LoadBalancerTlsCertificateStatusExpired is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusExpired = "EXPIRED" - - // LoadBalancerTlsCertificateStatusValidationTimedOut is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusValidationTimedOut = "VALIDATION_TIMED_OUT" - - // LoadBalancerTlsCertificateStatusRevoked is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusRevoked = "REVOKED" - - // LoadBalancerTlsCertificateStatusFailed is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusFailed = "FAILED" - - // LoadBalancerTlsCertificateStatusUnknown is a LoadBalancerTlsCertificateStatus enum value - LoadBalancerTlsCertificateStatusUnknown = "UNKNOWN" -) - -const ( - // MetricStatisticMinimum is a MetricStatistic enum value - MetricStatisticMinimum = "Minimum" - - // MetricStatisticMaximum is a MetricStatistic enum value - MetricStatisticMaximum = "Maximum" - - // MetricStatisticSum is a MetricStatistic enum value - MetricStatisticSum = "Sum" - - // MetricStatisticAverage is a MetricStatistic enum value - MetricStatisticAverage = "Average" - - // MetricStatisticSampleCount is a MetricStatistic enum value - MetricStatisticSampleCount = "SampleCount" -) - -const ( - // MetricUnitSeconds is a MetricUnit enum value - MetricUnitSeconds = "Seconds" - - // MetricUnitMicroseconds is a MetricUnit enum value - MetricUnitMicroseconds = "Microseconds" - - // MetricUnitMilliseconds is a MetricUnit enum value - MetricUnitMilliseconds = "Milliseconds" - - // MetricUnitBytes is a MetricUnit enum value - MetricUnitBytes = "Bytes" - - // MetricUnitKilobytes is a MetricUnit enum value - MetricUnitKilobytes = "Kilobytes" - - // MetricUnitMegabytes is a MetricUnit enum value - MetricUnitMegabytes = "Megabytes" - - // MetricUnitGigabytes is a MetricUnit enum value - MetricUnitGigabytes = "Gigabytes" - - // MetricUnitTerabytes is a MetricUnit enum value - MetricUnitTerabytes = "Terabytes" - - // MetricUnitBits is a MetricUnit enum value - MetricUnitBits = "Bits" - - // MetricUnitKilobits is a MetricUnit enum value - MetricUnitKilobits = "Kilobits" - - // MetricUnitMegabits is a MetricUnit enum value - MetricUnitMegabits = "Megabits" - - // MetricUnitGigabits is a MetricUnit enum value - MetricUnitGigabits = "Gigabits" - - // MetricUnitTerabits is a MetricUnit enum value - MetricUnitTerabits = "Terabits" - - // MetricUnitPercent is a MetricUnit enum value - MetricUnitPercent = "Percent" - - // MetricUnitCount is a MetricUnit enum value - MetricUnitCount = "Count" - - // MetricUnitBytesSecond is a MetricUnit enum value - MetricUnitBytesSecond = "Bytes/Second" - - // MetricUnitKilobytesSecond is a MetricUnit enum value - MetricUnitKilobytesSecond = "Kilobytes/Second" - - // MetricUnitMegabytesSecond is a MetricUnit enum value - MetricUnitMegabytesSecond = "Megabytes/Second" - - // MetricUnitGigabytesSecond is a MetricUnit enum value - MetricUnitGigabytesSecond = "Gigabytes/Second" - - // MetricUnitTerabytesSecond is a MetricUnit enum value - MetricUnitTerabytesSecond = "Terabytes/Second" - - // MetricUnitBitsSecond is a MetricUnit enum value - MetricUnitBitsSecond = "Bits/Second" - - // MetricUnitKilobitsSecond is a MetricUnit enum value - MetricUnitKilobitsSecond = "Kilobits/Second" - - // MetricUnitMegabitsSecond is a MetricUnit enum value - MetricUnitMegabitsSecond = "Megabits/Second" - - // MetricUnitGigabitsSecond is a MetricUnit enum value - MetricUnitGigabitsSecond = "Gigabits/Second" - - // MetricUnitTerabitsSecond is a MetricUnit enum value - MetricUnitTerabitsSecond = "Terabits/Second" - - // MetricUnitCountSecond is a MetricUnit enum value - MetricUnitCountSecond = "Count/Second" - - // MetricUnitNone is a MetricUnit enum value - MetricUnitNone = "None" -) - -const ( - // NetworkProtocolTcp is a NetworkProtocol enum value - NetworkProtocolTcp = "tcp" - - // NetworkProtocolAll is a NetworkProtocol enum value - NetworkProtocolAll = "all" - - // NetworkProtocolUdp is a NetworkProtocol enum value - NetworkProtocolUdp = "udp" -) - -const ( - // OperationStatusNotStarted is a OperationStatus enum value - OperationStatusNotStarted = "NotStarted" - - // OperationStatusStarted is a OperationStatus enum value - OperationStatusStarted = "Started" - - // OperationStatusFailed is a OperationStatus enum value - OperationStatusFailed = "Failed" - - // OperationStatusCompleted is a OperationStatus enum value - OperationStatusCompleted = "Completed" - - // OperationStatusSucceeded is a OperationStatus enum value - OperationStatusSucceeded = "Succeeded" -) - -const ( - // OperationTypeDeleteInstance is a OperationType enum value - OperationTypeDeleteInstance = "DeleteInstance" - - // OperationTypeCreateInstance is a OperationType enum value - OperationTypeCreateInstance = "CreateInstance" - - // OperationTypeStopInstance is a OperationType enum value - OperationTypeStopInstance = "StopInstance" - - // OperationTypeStartInstance is a OperationType enum value - OperationTypeStartInstance = "StartInstance" - - // OperationTypeRebootInstance is a OperationType enum value - OperationTypeRebootInstance = "RebootInstance" - - // OperationTypeOpenInstancePublicPorts is a OperationType enum value - OperationTypeOpenInstancePublicPorts = "OpenInstancePublicPorts" - - // OperationTypePutInstancePublicPorts is a OperationType enum value - OperationTypePutInstancePublicPorts = "PutInstancePublicPorts" - - // OperationTypeCloseInstancePublicPorts is a OperationType enum value - OperationTypeCloseInstancePublicPorts = "CloseInstancePublicPorts" - - // OperationTypeAllocateStaticIp is a OperationType enum value - OperationTypeAllocateStaticIp = "AllocateStaticIp" - - // OperationTypeReleaseStaticIp is a OperationType enum value - OperationTypeReleaseStaticIp = "ReleaseStaticIp" - - // OperationTypeAttachStaticIp is a OperationType enum value - OperationTypeAttachStaticIp = "AttachStaticIp" - - // OperationTypeDetachStaticIp is a OperationType enum value - OperationTypeDetachStaticIp = "DetachStaticIp" - - // OperationTypeUpdateDomainEntry is a OperationType enum value - OperationTypeUpdateDomainEntry = "UpdateDomainEntry" - - // OperationTypeDeleteDomainEntry is a OperationType enum value - OperationTypeDeleteDomainEntry = "DeleteDomainEntry" - - // OperationTypeCreateDomain is a OperationType enum value - OperationTypeCreateDomain = "CreateDomain" - - // OperationTypeDeleteDomain is a OperationType enum value - OperationTypeDeleteDomain = "DeleteDomain" - - // OperationTypeCreateInstanceSnapshot is a OperationType enum value - OperationTypeCreateInstanceSnapshot = "CreateInstanceSnapshot" - - // OperationTypeDeleteInstanceSnapshot is a OperationType enum value - OperationTypeDeleteInstanceSnapshot = "DeleteInstanceSnapshot" - - // OperationTypeCreateInstancesFromSnapshot is a OperationType enum value - OperationTypeCreateInstancesFromSnapshot = "CreateInstancesFromSnapshot" - - // OperationTypeCreateLoadBalancer is a OperationType enum value - OperationTypeCreateLoadBalancer = "CreateLoadBalancer" - - // OperationTypeDeleteLoadBalancer is a OperationType enum value - OperationTypeDeleteLoadBalancer = "DeleteLoadBalancer" - - // OperationTypeAttachInstancesToLoadBalancer is a OperationType enum value - OperationTypeAttachInstancesToLoadBalancer = "AttachInstancesToLoadBalancer" - - // OperationTypeDetachInstancesFromLoadBalancer is a OperationType enum value - OperationTypeDetachInstancesFromLoadBalancer = "DetachInstancesFromLoadBalancer" - - // OperationTypeUpdateLoadBalancerAttribute is a OperationType enum value - OperationTypeUpdateLoadBalancerAttribute = "UpdateLoadBalancerAttribute" - - // OperationTypeCreateLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeCreateLoadBalancerTlsCertificate = "CreateLoadBalancerTlsCertificate" - - // OperationTypeDeleteLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeDeleteLoadBalancerTlsCertificate = "DeleteLoadBalancerTlsCertificate" - - // OperationTypeAttachLoadBalancerTlsCertificate is a OperationType enum value - OperationTypeAttachLoadBalancerTlsCertificate = "AttachLoadBalancerTlsCertificate" - - // OperationTypeCreateDisk is a OperationType enum value - OperationTypeCreateDisk = "CreateDisk" - - // OperationTypeDeleteDisk is a OperationType enum value - OperationTypeDeleteDisk = "DeleteDisk" - - // OperationTypeAttachDisk is a OperationType enum value - OperationTypeAttachDisk = "AttachDisk" - - // OperationTypeDetachDisk is a OperationType enum value - OperationTypeDetachDisk = "DetachDisk" - - // OperationTypeCreateDiskSnapshot is a OperationType enum value - OperationTypeCreateDiskSnapshot = "CreateDiskSnapshot" - - // OperationTypeDeleteDiskSnapshot is a OperationType enum value - OperationTypeDeleteDiskSnapshot = "DeleteDiskSnapshot" - - // OperationTypeCreateDiskFromSnapshot is a OperationType enum value - OperationTypeCreateDiskFromSnapshot = "CreateDiskFromSnapshot" -) - -const ( - // PortAccessTypePublic is a PortAccessType enum value - PortAccessTypePublic = "Public" - - // PortAccessTypePrivate is a PortAccessType enum value - PortAccessTypePrivate = "Private" -) - -const ( - // PortStateOpen is a PortState enum value - PortStateOpen = "open" - - // PortStateClosed is a PortState enum value - PortStateClosed = "closed" -) - -const ( - // RegionNameUsEast1 is a RegionName enum value - RegionNameUsEast1 = "us-east-1" - - // RegionNameUsEast2 is a RegionName enum value - RegionNameUsEast2 = "us-east-2" - - // RegionNameUsWest1 is a RegionName enum value - RegionNameUsWest1 = "us-west-1" - - // RegionNameUsWest2 is a RegionName enum value - RegionNameUsWest2 = "us-west-2" - - // RegionNameEuCentral1 is a RegionName enum value - RegionNameEuCentral1 = "eu-central-1" - - // RegionNameEuWest1 is a RegionName enum value - RegionNameEuWest1 = "eu-west-1" - - // RegionNameEuWest2 is a RegionName enum value - RegionNameEuWest2 = "eu-west-2" - - // RegionNameApSouth1 is a RegionName enum value - RegionNameApSouth1 = "ap-south-1" - - // RegionNameApSoutheast1 is a RegionName enum value - RegionNameApSoutheast1 = "ap-southeast-1" - - // RegionNameApSoutheast2 is a RegionName enum value - RegionNameApSoutheast2 = "ap-southeast-2" - - // RegionNameApNortheast1 is a RegionName enum value - RegionNameApNortheast1 = "ap-northeast-1" - - // RegionNameApNortheast2 is a RegionName enum value - RegionNameApNortheast2 = "ap-northeast-2" -) - -const ( - // ResourceTypeInstance is a ResourceType enum value - ResourceTypeInstance = "Instance" - - // ResourceTypeStaticIp is a ResourceType enum value - ResourceTypeStaticIp = "StaticIp" - - // ResourceTypeKeyPair is a ResourceType enum value - ResourceTypeKeyPair = "KeyPair" - - // ResourceTypeInstanceSnapshot is a ResourceType enum value - ResourceTypeInstanceSnapshot = "InstanceSnapshot" - - // ResourceTypeDomain is a ResourceType enum value - ResourceTypeDomain = "Domain" - - // ResourceTypePeeredVpc is a ResourceType enum value - ResourceTypePeeredVpc = "PeeredVpc" - - // ResourceTypeLoadBalancer is a ResourceType enum value - ResourceTypeLoadBalancer = "LoadBalancer" - - // ResourceTypeLoadBalancerTlsCertificate is a ResourceType enum value - ResourceTypeLoadBalancerTlsCertificate = "LoadBalancerTlsCertificate" - - // ResourceTypeDisk is a ResourceType enum value - ResourceTypeDisk = "Disk" - - // ResourceTypeDiskSnapshot is a ResourceType enum value - ResourceTypeDiskSnapshot = "DiskSnapshot" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go deleted file mode 100644 index 9c52815bb..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/doc.go +++ /dev/null @@ -1,40 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package lightsail provides the client and types for making API -// requests to Amazon Lightsail. -// -// Amazon Lightsail is the easiest way to get started with AWS for developers -// who just need virtual private servers. Lightsail includes everything you -// need to launch your project quickly - a virtual machine, SSD-based storage, -// data transfer, DNS management, and a static IP - for a low, predictable price. -// You manage those Lightsail servers through the Lightsail console or by using -// the API or command-line interface (CLI). -// -// For more information about Lightsail concepts and tasks, see the Lightsail -// Dev Guide (https://lightsail.aws.amazon.com/ls/docs/all). -// -// To use the Lightsail API or the CLI, you will need to use AWS Identity and -// Access Management (IAM) to generate access keys. For details about how to -// set this up, see the Lightsail Dev Guide (http://lightsail.aws.amazon.com/ls/docs/how-to/article/lightsail-how-to-set-up-access-keys-to-use-sdk-api-cli). -// -// See https://docs.aws.amazon.com/goto/WebAPI/lightsail-2016-11-28 for more information on this service. -// -// See lightsail package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/ -// -// Using the Client -// -// To contact Amazon Lightsail with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon Lightsail client Lightsail for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/lightsail/#New -package lightsail diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go deleted file mode 100644 index bda8b8a66..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/errors.go +++ /dev/null @@ -1,55 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -const ( - - // ErrCodeAccessDeniedException for service response error code - // "AccessDeniedException". - // - // Lightsail throws this exception when the user cannot be authenticated or - // uses invalid credentials to access a resource. - ErrCodeAccessDeniedException = "AccessDeniedException" - - // ErrCodeAccountSetupInProgressException for service response error code - // "AccountSetupInProgressException". - // - // Lightsail throws this exception when an account is still in the setup in - // progress state. - ErrCodeAccountSetupInProgressException = "AccountSetupInProgressException" - - // ErrCodeInvalidInputException for service response error code - // "InvalidInputException". - // - // Lightsail throws this exception when user input does not conform to the validation - // rules of an input field. - // - // Domain-related APIs are only available in the N. Virginia (us-east-1) Region. - // Please set your AWS Region configuration to us-east-1 to create, view, or - // edit these resources. - ErrCodeInvalidInputException = "InvalidInputException" - - // ErrCodeNotFoundException for service response error code - // "NotFoundException". - // - // Lightsail throws this exception when it cannot find a resource. - ErrCodeNotFoundException = "NotFoundException" - - // ErrCodeOperationFailureException for service response error code - // "OperationFailureException". - // - // Lightsail throws this exception when an operation fails to execute. - ErrCodeOperationFailureException = "OperationFailureException" - - // ErrCodeServiceException for service response error code - // "ServiceException". - // - // A general service exception. - ErrCodeServiceException = "ServiceException" - - // ErrCodeUnauthenticatedException for service response error code - // "UnauthenticatedException". - // - // Lightsail throws this exception when the user has not been authenticated. - ErrCodeUnauthenticatedException = "UnauthenticatedException" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go b/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go deleted file mode 100644 index a76cf79e0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/lightsail/service.go +++ /dev/null @@ -1,95 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package lightsail - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/jsonrpc" -) - -// Lightsail provides the API operation methods for making requests to -// Amazon Lightsail. See this package's package overview docs -// for details on the service. -// -// Lightsail methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type Lightsail struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "lightsail" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. -) - -// New creates a new instance of the Lightsail client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a Lightsail client from just a session. -// svc := lightsail.New(mySession) -// -// // Create a Lightsail client with additional configuration -// svc := lightsail.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *Lightsail { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Lightsail { - svc := &Lightsail{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2016-11-28", - JSONVersion: "1.1", - TargetPrefix: "Lightsail_20161128", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(jsonrpc.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(jsonrpc.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(jsonrpc.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(jsonrpc.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a Lightsail operation and runs any -// custom request initialization. -func (c *Lightsail) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/api.go b/vendor/github.com/aws/aws-sdk-go/service/route53/api.go deleted file mode 100644 index 5357821e8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/api.go +++ /dev/null @@ -1,14969 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "fmt" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssociateVPCWithHostedZone = "AssociateVPCWithHostedZone" - -// AssociateVPCWithHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the AssociateVPCWithHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssociateVPCWithHostedZone for more information on using the AssociateVPCWithHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssociateVPCWithHostedZoneRequest method. -// req, resp := client.AssociateVPCWithHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/AssociateVPCWithHostedZone -func (c *Route53) AssociateVPCWithHostedZoneRequest(input *AssociateVPCWithHostedZoneInput) (req *request.Request, output *AssociateVPCWithHostedZoneOutput) { - op := &request.Operation{ - Name: opAssociateVPCWithHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/associatevpc", - } - - if input == nil { - input = &AssociateVPCWithHostedZoneInput{} - } - - output = &AssociateVPCWithHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssociateVPCWithHostedZone API operation for Amazon Route 53. -// -// Associates an Amazon VPC with a private hosted zone. -// -// To perform the association, the VPC and the private hosted zone must already -// exist. You can't convert a public hosted zone into a private hosted zone. -// -// If you want to associate a VPC that was created by using one AWS account -// with a private hosted zone that was created by using a different account, -// the AWS account that created the private hosted zone must first submit a -// CreateVPCAssociationAuthorization request. Then the account that created -// the VPC must submit an AssociateVPCWithHostedZone request. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation AssociateVPCWithHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNotAuthorizedException "NotAuthorizedException" -// Associating the specified VPC with the specified hosted zone has not been -// authorized. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePublicZoneVPCAssociation "PublicZoneVPCAssociation" -// You're trying to associate a VPC with a public hosted zone. Amazon Route -// 53 doesn't support associating a VPC with a public hosted zone. -// -// * ErrCodeConflictingDomainExists "ConflictingDomainExists" -// The cause of this error depends on whether you're trying to create a public -// or a private hosted zone: -// -// * Public hosted zone: Two hosted zones that have the same name or that -// have a parent/child relationship (example.com and test.example.com) can't -// have any common name servers. You tried to create a hosted zone that has -// the same name as an existing hosted zone or that's the parent or child -// of an existing hosted zone, and you specified a delegation set that shares -// one or more name servers with the existing hosted zone. For more information, -// see CreateReusableDelegationSet. -// -// * Private hosted zone: You specified an Amazon VPC that you're already -// using for another hosted zone, and the domain that you specified for one -// of the hosted zones is a subdomain of the domain that you specified for -// the other hosted zone. For example, you can't use the same Amazon VPC -// for the hosted zones for example.com and test.example.com. -// -// * ErrCodeLimitsExceeded "LimitsExceeded" -// This operation can't be completed either because the current account has -// reached the limit on reusable delegation sets that it can create or because -// you've reached the limit on the number of Amazon VPCs that you can associate -// with a private hosted zone. To get the current limit on the number of reusable -// delegation sets, see GetAccountLimit. To get the current limit on the number -// of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/AssociateVPCWithHostedZone -func (c *Route53) AssociateVPCWithHostedZone(input *AssociateVPCWithHostedZoneInput) (*AssociateVPCWithHostedZoneOutput, error) { - req, out := c.AssociateVPCWithHostedZoneRequest(input) - return out, req.Send() -} - -// AssociateVPCWithHostedZoneWithContext is the same as AssociateVPCWithHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See AssociateVPCWithHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) AssociateVPCWithHostedZoneWithContext(ctx aws.Context, input *AssociateVPCWithHostedZoneInput, opts ...request.Option) (*AssociateVPCWithHostedZoneOutput, error) { - req, out := c.AssociateVPCWithHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opChangeResourceRecordSets = "ChangeResourceRecordSets" - -// ChangeResourceRecordSetsRequest generates a "aws/request.Request" representing the -// client's request for the ChangeResourceRecordSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ChangeResourceRecordSets for more information on using the ChangeResourceRecordSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ChangeResourceRecordSetsRequest method. -// req, resp := client.ChangeResourceRecordSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeResourceRecordSets -func (c *Route53) ChangeResourceRecordSetsRequest(input *ChangeResourceRecordSetsInput) (req *request.Request, output *ChangeResourceRecordSetsOutput) { - op := &request.Operation{ - Name: opChangeResourceRecordSets, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/rrset/", - } - - if input == nil { - input = &ChangeResourceRecordSetsInput{} - } - - output = &ChangeResourceRecordSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ChangeResourceRecordSets API operation for Amazon Route 53. -// -// Creates, changes, or deletes a resource record set, which contains authoritative -// DNS information for a specified domain name or subdomain name. For example, -// you can use ChangeResourceRecordSets to create a resource record set that -// routes traffic for test.example.com to a web server that has an IP address -// of 192.0.2.44. -// -// Change Batches and Transactional Changes -// -// The request body must include a document with a ChangeResourceRecordSetsRequest -// element. The request body contains a list of change items, known as a change -// batch. Change batches are considered transactional changes. When using the -// Amazon Route 53 API to change resource record sets, Amazon Route 53 either -// makes all or none of the changes in a change batch request. This ensures -// that Amazon Route 53 never partially implements the intended changes to the -// resource record sets in a hosted zone. -// -// For example, a change batch request that deletes the CNAME record for www.example.com -// and creates an alias resource record set for www.example.com. Amazon Route -// 53 deletes the first resource record set and creates the second resource -// record set in a single operation. If either the DELETE or the CREATE action -// fails, then both changes (plus any other changes in the batch) fail, and -// the original CNAME record continues to exist. -// -// Due to the nature of transactional changes, you can't delete the same resource -// record set more than once in a single change batch. If you attempt to delete -// the same change batch more than once, Amazon Route 53 returns an InvalidChangeBatch -// error. -// -// Traffic Flow -// -// To create resource record sets for complex routing configurations, use either -// the traffic flow visual editor in the Amazon Route 53 console or the API -// actions for traffic policies and traffic policy instances. Save the configuration -// as a traffic policy, then associate the traffic policy with one or more domain -// names (such as example.com) or subdomain names (such as www.example.com), -// in the same hosted zone or in multiple hosted zones. You can roll back the -// updates if the new configuration isn't performing as expected. For more information, -// see Using Traffic Flow to Route DNS Traffic (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/traffic-flow.html) -// in the Amazon Route 53 Developer Guide. -// -// Create, Delete, and Upsert -// -// Use ChangeResourceRecordsSetsRequest to perform the following actions: -// -// * CREATE: Creates a resource record set that has the specified values. -// -// * DELETE: Deletes an existing resource record set that has the specified -// values. -// -// * UPSERT: If a resource record set does not already exist, AWS creates -// it. If a resource set does exist, Amazon Route 53 updates it with the -// values in the request. -// -// Syntaxes for Creating, Updating, and Deleting Resource Record Sets -// -// The syntax for a request depends on the type of resource record set that -// you want to create, delete, or update, such as weighted, alias, or failover. -// The XML elements in your request must appear in the order listed in the syntax. -// -// For an example for each type of resource record set, see "Examples." -// -// Don't refer to the syntax in the "Parameter Syntax" section, which includes -// all of the elements for every kind of resource record set that you can create, -// delete, or update by using ChangeResourceRecordSets. -// -// Change Propagation to Amazon Route 53 DNS Servers -// -// When you submit a ChangeResourceRecordSets request, Amazon Route 53 propagates -// your changes to all of the Amazon Route 53 authoritative DNS servers. While -// your changes are propagating, GetChange returns a status of PENDING. When -// propagation is complete, GetChange returns a status of INSYNC. Changes generally -// propagate to all Amazon Route 53 name servers within 60 seconds. For more -// information, see GetChange. -// -// Limits on ChangeResourceRecordSets Requests -// -// For information about the limits on a ChangeResourceRecordSets request, see -// Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ChangeResourceRecordSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidChangeBatch "InvalidChangeBatch" -// This exception contains a list of messages that might contain one or more -// error messages. Each error message indicates one error in the change batch. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeResourceRecordSets -func (c *Route53) ChangeResourceRecordSets(input *ChangeResourceRecordSetsInput) (*ChangeResourceRecordSetsOutput, error) { - req, out := c.ChangeResourceRecordSetsRequest(input) - return out, req.Send() -} - -// ChangeResourceRecordSetsWithContext is the same as ChangeResourceRecordSets with the addition of -// the ability to pass a context and additional request options. -// -// See ChangeResourceRecordSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ChangeResourceRecordSetsWithContext(ctx aws.Context, input *ChangeResourceRecordSetsInput, opts ...request.Option) (*ChangeResourceRecordSetsOutput, error) { - req, out := c.ChangeResourceRecordSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opChangeTagsForResource = "ChangeTagsForResource" - -// ChangeTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ChangeTagsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ChangeTagsForResource for more information on using the ChangeTagsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ChangeTagsForResourceRequest method. -// req, resp := client.ChangeTagsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeTagsForResource -func (c *Route53) ChangeTagsForResourceRequest(input *ChangeTagsForResourceInput) (req *request.Request, output *ChangeTagsForResourceOutput) { - op := &request.Operation{ - Name: opChangeTagsForResource, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/tags/{ResourceType}/{ResourceId}", - } - - if input == nil { - input = &ChangeTagsForResourceInput{} - } - - output = &ChangeTagsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// ChangeTagsForResource API operation for Amazon Route 53. -// -// Adds, edits, or deletes tags for a health check or a hosted zone. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ChangeTagsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ChangeTagsForResource -func (c *Route53) ChangeTagsForResource(input *ChangeTagsForResourceInput) (*ChangeTagsForResourceOutput, error) { - req, out := c.ChangeTagsForResourceRequest(input) - return out, req.Send() -} - -// ChangeTagsForResourceWithContext is the same as ChangeTagsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See ChangeTagsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ChangeTagsForResourceWithContext(ctx aws.Context, input *ChangeTagsForResourceInput, opts ...request.Option) (*ChangeTagsForResourceOutput, error) { - req, out := c.ChangeTagsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateHealthCheck = "CreateHealthCheck" - -// CreateHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the CreateHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateHealthCheck for more information on using the CreateHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateHealthCheckRequest method. -// req, resp := client.CreateHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHealthCheck -func (c *Route53) CreateHealthCheckRequest(input *CreateHealthCheckInput) (req *request.Request, output *CreateHealthCheckOutput) { - op := &request.Operation{ - Name: opCreateHealthCheck, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/healthcheck", - } - - if input == nil { - input = &CreateHealthCheckInput{} - } - - output = &CreateHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateHealthCheck API operation for Amazon Route 53. -// -// Creates a new health check. -// -// For information about adding health checks to resource record sets, see ResourceRecordSet$HealthCheckId -// in ChangeResourceRecordSets. -// -// ELB Load Balancers -// -// If you're registering EC2 instances with an Elastic Load Balancing (ELB) -// load balancer, do not create Amazon Route 53 health checks for the EC2 instances. -// When you register an EC2 instance with a load balancer, you configure settings -// for an ELB health check, which performs a similar function to an Amazon Route -// 53 health check. -// -// Private Hosted Zones -// -// You can associate health checks with failover resource record sets in a private -// hosted zone. Note the following: -// -// * Amazon Route 53 health checkers are outside the VPC. To check the health -// of an endpoint within a VPC by IP address, you must assign a public IP -// address to the instance in the VPC. -// -// * You can configure a health checker to check the health of an external -// resource that the instance relies on, such as a database server. -// -// * You can create a CloudWatch metric, associate an alarm with the metric, -// and then create a health check that is based on the state of the alarm. -// For example, you might create a CloudWatch metric that checks the status -// of the Amazon EC2 StatusCheckFailed metric, add an alarm to the metric, -// and then create a health check that is based on the state of the alarm. -// For information about creating CloudWatch metrics and alarms by using -// the CloudWatch console, see the Amazon CloudWatch User Guide (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/WhatIsCloudWatch.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeTooManyHealthChecks "TooManyHealthChecks" -// This health check can't be created because the current account has reached -// the limit on the number of active health checks. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// For information about how to get the current limit for an account, see GetAccountLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// You have reached the maximum number of active health checks for an AWS account. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeHealthCheckAlreadyExists "HealthCheckAlreadyExists" -// The health check you're attempting to create already exists. Amazon Route -// 53 returns this error when you submit a request that has the following values: -// -// * The same value for CallerReference as an existing health check, and -// one or more values that differ from the existing health check that has -// the same caller reference. -// -// * The same value for CallerReference as a health check that you created -// and later deleted, regardless of the other settings in the request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHealthCheck -func (c *Route53) CreateHealthCheck(input *CreateHealthCheckInput) (*CreateHealthCheckOutput, error) { - req, out := c.CreateHealthCheckRequest(input) - return out, req.Send() -} - -// CreateHealthCheckWithContext is the same as CreateHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See CreateHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateHealthCheckWithContext(ctx aws.Context, input *CreateHealthCheckInput, opts ...request.Option) (*CreateHealthCheckOutput, error) { - req, out := c.CreateHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateHostedZone = "CreateHostedZone" - -// CreateHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the CreateHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateHostedZone for more information on using the CreateHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateHostedZoneRequest method. -// req, resp := client.CreateHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZone -func (c *Route53) CreateHostedZoneRequest(input *CreateHostedZoneInput) (req *request.Request, output *CreateHostedZoneOutput) { - op := &request.Operation{ - Name: opCreateHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone", - } - - if input == nil { - input = &CreateHostedZoneInput{} - } - - output = &CreateHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateHostedZone API operation for Amazon Route 53. -// -// Creates a new public hosted zone, which you use to specify how the Domain -// Name System (DNS) routes traffic on the Internet for a domain, such as example.com, -// and its subdomains. -// -// You can't convert a public hosted zones to a private hosted zone or vice -// versa. Instead, you must create a new hosted zone with the same name and -// create new resource record sets. -// -// For more information about charges for hosted zones, see Amazon Route 53 -// Pricing (http://aws.amazon.com/route53/pricing/). -// -// Note the following: -// -// * You can't create a hosted zone for a top-level domain (TLD). -// -// * Amazon Route 53 automatically creates a default SOA record and four -// NS records for the zone. For more information about SOA and NS records, -// see NS and SOA Records that Amazon Route 53 Creates for a Hosted Zone -// (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/SOA-NSrecords.html) -// in the Amazon Route 53 Developer Guide. -// -// If you want to use the same name servers for multiple hosted zones, you can -// optionally associate a reusable delegation set with the hosted zone. See -// the DelegationSetId element. -// -// * If your domain is registered with a registrar other than Amazon Route -// 53, you must update the name servers with your registrar to make Amazon -// Route 53 your DNS service. For more information, see Configuring Amazon -// Route 53 as your DNS Service (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/creating-migrating.html) -// in the Amazon Route 53 Developer Guide. -// -// When you submit a CreateHostedZone request, the initial status of the hosted -// zone is PENDING. This means that the NS and SOA records are not yet available -// on all Amazon Route 53 DNS servers. When the NS and SOA records are available, -// the status of the zone changes to INSYNC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// * ErrCodeHostedZoneAlreadyExists "HostedZoneAlreadyExists" -// The hosted zone you're trying to create already exists. Amazon Route 53 returns -// this error when a hosted zone has already been created with the specified -// CallerReference. -// -// * ErrCodeTooManyHostedZones "TooManyHostedZones" -// This operation can't be completed either because the current account has -// reached the limit on the number of hosted zones or because you've reached -// the limit on the number of hosted zones that can be associated with a reusable -// delegation set. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// To get the current limit on hosted zones that can be created by an account, -// see GetAccountLimit. -// -// To get the current limit on hosted zones that can be associated with a reusable -// delegation set, see GetReusableDelegationSetLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeDelegationSetNotAvailable "DelegationSetNotAvailable" -// You can create a hosted zone that has the same name as an existing hosted -// zone (example.com is common), but there is a limit to the number of hosted -// zones that have the same name. If you get this error, Amazon Route 53 has -// reached that limit. If you own the domain name and Amazon Route 53 generates -// this error, contact Customer Support. -// -// * ErrCodeConflictingDomainExists "ConflictingDomainExists" -// The cause of this error depends on whether you're trying to create a public -// or a private hosted zone: -// -// * Public hosted zone: Two hosted zones that have the same name or that -// have a parent/child relationship (example.com and test.example.com) can't -// have any common name servers. You tried to create a hosted zone that has -// the same name as an existing hosted zone or that's the parent or child -// of an existing hosted zone, and you specified a delegation set that shares -// one or more name servers with the existing hosted zone. For more information, -// see CreateReusableDelegationSet. -// -// * Private hosted zone: You specified an Amazon VPC that you're already -// using for another hosted zone, and the domain that you specified for one -// of the hosted zones is a subdomain of the domain that you specified for -// the other hosted zone. For example, you can't use the same Amazon VPC -// for the hosted zones for example.com and test.example.com. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateHostedZone -func (c *Route53) CreateHostedZone(input *CreateHostedZoneInput) (*CreateHostedZoneOutput, error) { - req, out := c.CreateHostedZoneRequest(input) - return out, req.Send() -} - -// CreateHostedZoneWithContext is the same as CreateHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See CreateHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateHostedZoneWithContext(ctx aws.Context, input *CreateHostedZoneInput, opts ...request.Option) (*CreateHostedZoneOutput, error) { - req, out := c.CreateHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateQueryLoggingConfig = "CreateQueryLoggingConfig" - -// CreateQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the CreateQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateQueryLoggingConfig for more information on using the CreateQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateQueryLoggingConfigRequest method. -// req, resp := client.CreateQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateQueryLoggingConfig -func (c *Route53) CreateQueryLoggingConfigRequest(input *CreateQueryLoggingConfigInput) (req *request.Request, output *CreateQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opCreateQueryLoggingConfig, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/queryloggingconfig", - } - - if input == nil { - input = &CreateQueryLoggingConfigInput{} - } - - output = &CreateQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateQueryLoggingConfig API operation for Amazon Route 53. -// -// Creates a configuration for DNS query logging. After you create a query logging -// configuration, Amazon Route 53 begins to publish log data to an Amazon CloudWatch -// Logs log group. -// -// DNS query logs contain information about the queries that Amazon Route 53 -// receives for a specified public hosted zone, such as the following: -// -// * Amazon Route 53 edge location that responded to the DNS query -// -// * Domain or subdomain that was requested -// -// * DNS record type, such as A or AAAA -// -// * DNS response code, such as NoError or ServFail -// -// Log Group and Resource PolicyBefore you create a query logging configuration, -// perform the following operations. -// -// If you create a query logging configuration using the Amazon Route 53 console, -// Amazon Route 53 performs these operations automatically. -// -// Create a CloudWatch Logs log group, and make note of the ARN, which you specify -// when you create a query logging configuration. Note the following: -// -// You must create the log group in the us-east-1 region. -// -// You must use the same AWS account to create the log group and the hosted -// zone that you want to configure query logging for. -// -// When you create log groups for query logging, we recommend that you use a -// consistent prefix, for example: -// -// /aws/route53/hosted zone name -// -// In the next step, you'll create a resource policy, which controls access -// to one or more log groups and the associated AWS resources, such as Amazon -// Route 53 hosted zones. There's a limit on the number of resource policies -// that you can create, so we recommend that you use a consistent prefix so -// you can use the same resource policy for all the log groups that you create -// for query logging. -// -// Create a CloudWatch Logs resource policy, and give it the permissions that -// Amazon Route 53 needs to create log streams and to send query logs to log -// streams. For the value of Resource, specify the ARN for the log group that -// you created in the previous step. To use the same resource policy for all -// the CloudWatch Logs log groups that you created for query logging configurations, -// replace the hosted zone name with *, for example: -// -// arn:aws:logs:us-east-1:123412341234:log-group:/aws/route53/* -// -// You can't use the CloudWatch console to create or edit a resource policy. -// You must use the CloudWatch API, one of the AWS SDKs, or the AWS CLI. -// -// Log Streams and Edge LocationsWhen Amazon Route 53 finishes creating the -// configuration for DNS query logging, it does the following: -// -// Creates a log stream for an edge location the first time that the edge location -// responds to DNS queries for the specified hosted zone. That log stream is -// used to log all queries that Amazon Route 53 responds to for that edge location. -// -// Begins to send query logs to the applicable log stream. -// -// The name of each log stream is in the following format: -// -// hosted zone ID/edge location code -// -// The edge location code is a three-letter code and an arbitrarily assigned -// number, for example, DFW3. The three-letter code typically corresponds with -// the International Air Transport Association airport code for an airport near -// the edge location. (These abbreviations might change in the future.) For -// a list of edge locations, see "The Amazon Route 53 Global Network" on the -// Amazon Route 53 Product Details (http://aws.amazon.com/route53/details/) -// page. -// -// Queries That Are LoggedQuery logs contain only the queries that DNS resolvers -// forward to Amazon Route 53. If a DNS resolver has already cached the response -// to a query (such as the IP address for a load balancer for example.com), -// the resolver will continue to return the cached response. It doesn't forward -// another query to Amazon Route 53 until the TTL for the corresponding resource -// record set expires. Depending on how many DNS queries are submitted for a -// resource record set, and depending on the TTL for that resource record set, -// query logs might contain information about only one query out of every several -// thousand queries that are submitted to DNS. For more information about how -// DNS works, see Routing Internet Traffic to Your Website or Web Application -// (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/welcome-dns-service.html) -// in the Amazon Route 53 Developer Guide. -// -// Log File FormatFor a list of the values in each query log and the format -// of each value, see Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html) -// in the Amazon Route 53 Developer Guide. -// -// PricingFor information about charges for query logs, see Amazon CloudWatch -// Pricing (http://aws.amazon.com/cloudwatch/pricing/). -// -// How to Stop LoggingIf you want Amazon Route 53 to stop sending query logs -// to CloudWatch Logs, delete the query logging configuration. For more information, -// see DeleteQueryLoggingConfig. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeNoSuchCloudWatchLogsLogGroup "NoSuchCloudWatchLogsLogGroup" -// There is no CloudWatch Logs log group with the specified ARN. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeQueryLoggingConfigAlreadyExists "QueryLoggingConfigAlreadyExists" -// You can create only one query logging configuration for a hosted zone, and -// a query logging configuration already exists for this hosted zone. -// -// * ErrCodeInsufficientCloudWatchLogsResourcePolicy "InsufficientCloudWatchLogsResourcePolicy" -// Amazon Route 53 doesn't have the permissions required to create log streams -// and send query logs to log streams. Possible causes include the following: -// -// * There is no resource policy that specifies the log group ARN in the -// value for Resource. -// -// * The resource policy that includes the log group ARN in the value for -// Resource doesn't have the necessary permissions. -// -// * The resource policy hasn't finished propagating yet. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateQueryLoggingConfig -func (c *Route53) CreateQueryLoggingConfig(input *CreateQueryLoggingConfigInput) (*CreateQueryLoggingConfigOutput, error) { - req, out := c.CreateQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// CreateQueryLoggingConfigWithContext is the same as CreateQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See CreateQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateQueryLoggingConfigWithContext(ctx aws.Context, input *CreateQueryLoggingConfigInput, opts ...request.Option) (*CreateQueryLoggingConfigOutput, error) { - req, out := c.CreateQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateReusableDelegationSet = "CreateReusableDelegationSet" - -// CreateReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the CreateReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateReusableDelegationSet for more information on using the CreateReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateReusableDelegationSetRequest method. -// req, resp := client.CreateReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateReusableDelegationSet -func (c *Route53) CreateReusableDelegationSetRequest(input *CreateReusableDelegationSetInput) (req *request.Request, output *CreateReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opCreateReusableDelegationSet, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/delegationset", - } - - if input == nil { - input = &CreateReusableDelegationSetInput{} - } - - output = &CreateReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateReusableDelegationSet API operation for Amazon Route 53. -// -// Creates a delegation set (a group of four name servers) that can be reused -// by multiple hosted zones. If a hosted zoned ID is specified, CreateReusableDelegationSet -// marks the delegation set associated with that zone as reusable. -// -// You can't associate a reusable delegation set with a private hosted zone. -// -// For information about using a reusable delegation set to configure white -// label name servers, see Configuring White Label Name Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/white-label-name-servers.html). -// -// The process for migrating existing hosted zones to use a reusable delegation -// set is comparable to the process for configuring white label name servers. -// You need to perform the following steps: -// -// Create a reusable delegation set. -// -// Recreate hosted zones, and reduce the TTL to 60 seconds or less. -// -// Recreate resource record sets in the new hosted zones. -// -// Change the registrar's name servers to use the name servers for the new hosted -// zones. -// -// Monitor traffic for the website or application. -// -// Change TTLs back to their original values. -// -// If you want to migrate existing hosted zones to use a reusable delegation -// set, the existing hosted zones can't use any of the name servers that are -// assigned to the reusable delegation set. If one or more hosted zones do use -// one or more name servers that are assigned to the reusable delegation set, -// you can do one of the following: -// -// * For small numbers of hosted zones—up to a few hundred—it's relatively -// easy to create reusable delegation sets until you get one that has four -// name servers that don't overlap with any of the name servers in your hosted -// zones. -// -// * For larger numbers of hosted zones, the easiest solution is to use more -// than one reusable delegation set. -// -// * For larger numbers of hosted zones, you can also migrate hosted zones -// that have overlapping name servers to hosted zones that don't have overlapping -// name servers, then migrate the hosted zones again to use the reusable -// delegation set. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeDelegationSetAlreadyCreated "DelegationSetAlreadyCreated" -// A delegation set with the same owner and caller reference combination has -// already been created. -// -// * ErrCodeLimitsExceeded "LimitsExceeded" -// This operation can't be completed either because the current account has -// reached the limit on reusable delegation sets that it can create or because -// you've reached the limit on the number of Amazon VPCs that you can associate -// with a private hosted zone. To get the current limit on the number of reusable -// delegation sets, see GetAccountLimit. To get the current limit on the number -// of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeHostedZoneNotFound "HostedZoneNotFound" -// The specified HostedZone can't be found. -// -// * ErrCodeInvalidArgument "InvalidArgument" -// Parameter name is invalid. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeDelegationSetNotAvailable "DelegationSetNotAvailable" -// You can create a hosted zone that has the same name as an existing hosted -// zone (example.com is common), but there is a limit to the number of hosted -// zones that have the same name. If you get this error, Amazon Route 53 has -// reached that limit. If you own the domain name and Amazon Route 53 generates -// this error, contact Customer Support. -// -// * ErrCodeDelegationSetAlreadyReusable "DelegationSetAlreadyReusable" -// The specified delegation set has already been marked as reusable. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateReusableDelegationSet -func (c *Route53) CreateReusableDelegationSet(input *CreateReusableDelegationSetInput) (*CreateReusableDelegationSetOutput, error) { - req, out := c.CreateReusableDelegationSetRequest(input) - return out, req.Send() -} - -// CreateReusableDelegationSetWithContext is the same as CreateReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See CreateReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateReusableDelegationSetWithContext(ctx aws.Context, input *CreateReusableDelegationSetInput, opts ...request.Option) (*CreateReusableDelegationSetOutput, error) { - req, out := c.CreateReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicy = "CreateTrafficPolicy" - -// CreateTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicy for more information on using the CreateTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyRequest method. -// req, resp := client.CreateTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicy -func (c *Route53) CreateTrafficPolicyRequest(input *CreateTrafficPolicyInput) (req *request.Request, output *CreateTrafficPolicyOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicy, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy", - } - - if input == nil { - input = &CreateTrafficPolicyInput{} - } - - output = &CreateTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicy API operation for Amazon Route 53. -// -// Creates a traffic policy, which you use to create multiple DNS resource record -// sets for one domain name (such as example.com) or one subdomain name (such -// as www.example.com). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicies "TooManyTrafficPolicies" -// This traffic policy can't be created because the current account has reached -// the limit on the number of traffic policies. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// To get the current limit for an account, see GetAccountLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeTrafficPolicyAlreadyExists "TrafficPolicyAlreadyExists" -// A traffic policy that has the same value for Name already exists. -// -// * ErrCodeInvalidTrafficPolicyDocument "InvalidTrafficPolicyDocument" -// The format of the traffic policy document that you specified in the Document -// element is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicy -func (c *Route53) CreateTrafficPolicy(input *CreateTrafficPolicyInput) (*CreateTrafficPolicyOutput, error) { - req, out := c.CreateTrafficPolicyRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyWithContext is the same as CreateTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyWithContext(ctx aws.Context, input *CreateTrafficPolicyInput, opts ...request.Option) (*CreateTrafficPolicyOutput, error) { - req, out := c.CreateTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicyInstance = "CreateTrafficPolicyInstance" - -// CreateTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicyInstance for more information on using the CreateTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyInstanceRequest method. -// req, resp := client.CreateTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyInstance -func (c *Route53) CreateTrafficPolicyInstanceRequest(input *CreateTrafficPolicyInstanceInput) (req *request.Request, output *CreateTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicyInstance, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicyinstance", - } - - if input == nil { - input = &CreateTrafficPolicyInstanceInput{} - } - - output = &CreateTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicyInstance API operation for Amazon Route 53. -// -// Creates resource record sets in a specified hosted zone based on the settings -// in a specified traffic policy version. In addition, CreateTrafficPolicyInstance -// associates the resource record sets with a specified domain name (such as -// example.com) or subdomain name (such as www.example.com). Amazon Route 53 -// responds to DNS queries for the domain or subdomain name by using the resource -// record sets that CreateTrafficPolicyInstance created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicyInstances "TooManyTrafficPolicyInstances" -// This traffic policy instance can't be created because the current account -// has reached the limit on the number of traffic policy instances. -// -// For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. -// -// For information about how to get the current limit for an account, see GetAccountLimit. -// -// To request a higher limit, create a case (http://aws.amazon.com/route53-request) -// with the AWS Support Center. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeTrafficPolicyInstanceAlreadyExists "TrafficPolicyInstanceAlreadyExists" -// There is already a traffic policy instance with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyInstance -func (c *Route53) CreateTrafficPolicyInstance(input *CreateTrafficPolicyInstanceInput) (*CreateTrafficPolicyInstanceOutput, error) { - req, out := c.CreateTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyInstanceWithContext is the same as CreateTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyInstanceWithContext(ctx aws.Context, input *CreateTrafficPolicyInstanceInput, opts ...request.Option) (*CreateTrafficPolicyInstanceOutput, error) { - req, out := c.CreateTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateTrafficPolicyVersion = "CreateTrafficPolicyVersion" - -// CreateTrafficPolicyVersionRequest generates a "aws/request.Request" representing the -// client's request for the CreateTrafficPolicyVersion operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateTrafficPolicyVersion for more information on using the CreateTrafficPolicyVersion -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateTrafficPolicyVersionRequest method. -// req, resp := client.CreateTrafficPolicyVersionRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersion -func (c *Route53) CreateTrafficPolicyVersionRequest(input *CreateTrafficPolicyVersionInput) (req *request.Request, output *CreateTrafficPolicyVersionOutput) { - op := &request.Operation{ - Name: opCreateTrafficPolicyVersion, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}", - } - - if input == nil { - input = &CreateTrafficPolicyVersionInput{} - } - - output = &CreateTrafficPolicyVersionOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateTrafficPolicyVersion API operation for Amazon Route 53. -// -// Creates a new version of an existing traffic policy. When you create a new -// version of a traffic policy, you specify the ID of the traffic policy that -// you want to update and a JSON-formatted document that describes the new version. -// You use traffic policies to create multiple DNS resource record sets for -// one domain name (such as example.com) or one subdomain name (such as www.example.com). -// You can create a maximum of 1000 versions of a traffic policy. If you reach -// the limit and need to create another version, you'll need to start a new -// traffic policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateTrafficPolicyVersion for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy "TooManyTrafficPolicyVersionsForCurrentPolicy" -// This traffic policy version can't be created because you've reached the limit -// of 1000 on the number of versions that you can create for the current traffic -// policy. -// -// To create more traffic policy versions, you can use GetTrafficPolicy to get -// the traffic policy document for a specified traffic policy version, and then -// use CreateTrafficPolicy to create a new traffic policy using the traffic -// policy document. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeInvalidTrafficPolicyDocument "InvalidTrafficPolicyDocument" -// The format of the traffic policy document that you specified in the Document -// element is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateTrafficPolicyVersion -func (c *Route53) CreateTrafficPolicyVersion(input *CreateTrafficPolicyVersionInput) (*CreateTrafficPolicyVersionOutput, error) { - req, out := c.CreateTrafficPolicyVersionRequest(input) - return out, req.Send() -} - -// CreateTrafficPolicyVersionWithContext is the same as CreateTrafficPolicyVersion with the addition of -// the ability to pass a context and additional request options. -// -// See CreateTrafficPolicyVersion for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateTrafficPolicyVersionWithContext(ctx aws.Context, input *CreateTrafficPolicyVersionInput, opts ...request.Option) (*CreateTrafficPolicyVersionOutput, error) { - req, out := c.CreateTrafficPolicyVersionRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opCreateVPCAssociationAuthorization = "CreateVPCAssociationAuthorization" - -// CreateVPCAssociationAuthorizationRequest generates a "aws/request.Request" representing the -// client's request for the CreateVPCAssociationAuthorization operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See CreateVPCAssociationAuthorization for more information on using the CreateVPCAssociationAuthorization -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the CreateVPCAssociationAuthorizationRequest method. -// req, resp := client.CreateVPCAssociationAuthorizationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateVPCAssociationAuthorization -func (c *Route53) CreateVPCAssociationAuthorizationRequest(input *CreateVPCAssociationAuthorizationInput) (req *request.Request, output *CreateVPCAssociationAuthorizationOutput) { - op := &request.Operation{ - Name: opCreateVPCAssociationAuthorization, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/authorizevpcassociation", - } - - if input == nil { - input = &CreateVPCAssociationAuthorizationInput{} - } - - output = &CreateVPCAssociationAuthorizationOutput{} - req = c.newRequest(op, input, output) - return -} - -// CreateVPCAssociationAuthorization API operation for Amazon Route 53. -// -// Authorizes the AWS account that created a specified VPC to submit an AssociateVPCWithHostedZone -// request to associate the VPC with a specified hosted zone that was created -// by a different account. To submit a CreateVPCAssociationAuthorization request, -// you must use the account that created the hosted zone. After you authorize -// the association, use the account that created the VPC to submit an AssociateVPCWithHostedZone -// request. -// -// If you want to associate multiple VPCs that you created by using one account -// with a hosted zone that you created by using a different account, you must -// submit one authorization request for each VPC. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation CreateVPCAssociationAuthorization for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeTooManyVPCAssociationAuthorizations "TooManyVPCAssociationAuthorizations" -// You've created the maximum number of authorizations that can be created for -// the specified hosted zone. To authorize another VPC to be associated with -// the hosted zone, submit a DeleteVPCAssociationAuthorization request to remove -// an existing authorization. To get a list of existing authorizations, submit -// a ListVPCAssociationAuthorizations request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/CreateVPCAssociationAuthorization -func (c *Route53) CreateVPCAssociationAuthorization(input *CreateVPCAssociationAuthorizationInput) (*CreateVPCAssociationAuthorizationOutput, error) { - req, out := c.CreateVPCAssociationAuthorizationRequest(input) - return out, req.Send() -} - -// CreateVPCAssociationAuthorizationWithContext is the same as CreateVPCAssociationAuthorization with the addition of -// the ability to pass a context and additional request options. -// -// See CreateVPCAssociationAuthorization for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) CreateVPCAssociationAuthorizationWithContext(ctx aws.Context, input *CreateVPCAssociationAuthorizationInput, opts ...request.Option) (*CreateVPCAssociationAuthorizationOutput, error) { - req, out := c.CreateVPCAssociationAuthorizationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteHealthCheck = "DeleteHealthCheck" - -// DeleteHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the DeleteHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteHealthCheck for more information on using the DeleteHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteHealthCheckRequest method. -// req, resp := client.DeleteHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheck -func (c *Route53) DeleteHealthCheckRequest(input *DeleteHealthCheckInput) (req *request.Request, output *DeleteHealthCheckOutput) { - op := &request.Operation{ - Name: opDeleteHealthCheck, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &DeleteHealthCheckInput{} - } - - output = &DeleteHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteHealthCheck API operation for Amazon Route 53. -// -// Deletes a health check. -// -// Amazon Route 53 does not prevent you from deleting a health check even if -// the health check is associated with one or more resource record sets. If -// you delete a health check and you don't update the associated resource record -// sets, the future status of the health check can't be predicted and may change. -// This will affect the routing of DNS queries for your DNS failover configuration. -// For more information, see Replacing and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html#health-checks-deleting.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeHealthCheckInUse "HealthCheckInUse" -// This error code is not in use. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHealthCheck -func (c *Route53) DeleteHealthCheck(input *DeleteHealthCheckInput) (*DeleteHealthCheckOutput, error) { - req, out := c.DeleteHealthCheckRequest(input) - return out, req.Send() -} - -// DeleteHealthCheckWithContext is the same as DeleteHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteHealthCheckWithContext(ctx aws.Context, input *DeleteHealthCheckInput, opts ...request.Option) (*DeleteHealthCheckOutput, error) { - req, out := c.DeleteHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteHostedZone = "DeleteHostedZone" - -// DeleteHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the DeleteHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteHostedZone for more information on using the DeleteHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteHostedZoneRequest method. -// req, resp := client.DeleteHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZone -func (c *Route53) DeleteHostedZoneRequest(input *DeleteHostedZoneInput) (req *request.Request, output *DeleteHostedZoneOutput) { - op := &request.Operation{ - Name: opDeleteHostedZone, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &DeleteHostedZoneInput{} - } - - output = &DeleteHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteHostedZone API operation for Amazon Route 53. -// -// Deletes a hosted zone. -// -// If the name servers for the hosted zone are associated with a domain and -// if you want to make the domain unavailable on the Internet, we recommend -// that you delete the name servers from the domain to prevent future DNS queries -// from possibly being misrouted. If the domain is registered with Amazon Route -// 53, see UpdateDomainNameservers. If the domain is registered with another -// registrar, use the method provided by the registrar to delete name servers -// for the domain. -// -// Some domain registries don't allow you to remove all of the name servers -// for a domain. If the registry for your domain requires one or more name servers, -// we recommend that you delete the hosted zone only if you transfer DNS service -// to another service provider, and you replace the name servers for the domain -// with name servers from the new provider. -// -// You can delete a hosted zone only if it contains only the default SOA record -// and NS resource record sets. If the hosted zone contains other resource record -// sets, you must delete them before you can delete the hosted zone. If you -// try to delete a hosted zone that contains other resource record sets, the -// request fails, and Amazon Route 53 returns a HostedZoneNotEmpty error. For -// information about deleting records from your hosted zone, see ChangeResourceRecordSets. -// -// To verify that the hosted zone has been deleted, do one of the following: -// -// * Use the GetHostedZone action to request information about the hosted -// zone. -// -// * Use the ListHostedZones action to get a list of the hosted zones associated -// with the current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeHostedZoneNotEmpty "HostedZoneNotEmpty" -// The hosted zone contains resource records that are not SOA or NS records. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteHostedZone -func (c *Route53) DeleteHostedZone(input *DeleteHostedZoneInput) (*DeleteHostedZoneOutput, error) { - req, out := c.DeleteHostedZoneRequest(input) - return out, req.Send() -} - -// DeleteHostedZoneWithContext is the same as DeleteHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteHostedZoneWithContext(ctx aws.Context, input *DeleteHostedZoneInput, opts ...request.Option) (*DeleteHostedZoneOutput, error) { - req, out := c.DeleteHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteQueryLoggingConfig = "DeleteQueryLoggingConfig" - -// DeleteQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the DeleteQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteQueryLoggingConfig for more information on using the DeleteQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteQueryLoggingConfigRequest method. -// req, resp := client.DeleteQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteQueryLoggingConfig -func (c *Route53) DeleteQueryLoggingConfigRequest(input *DeleteQueryLoggingConfigInput) (req *request.Request, output *DeleteQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opDeleteQueryLoggingConfig, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/queryloggingconfig/{Id}", - } - - if input == nil { - input = &DeleteQueryLoggingConfigInput{} - } - - output = &DeleteQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteQueryLoggingConfig API operation for Amazon Route 53. -// -// Deletes a configuration for DNS query logging. If you delete a configuration, -// Amazon Route 53 stops sending query logs to CloudWatch Logs. Amazon Route -// 53 doesn't delete any logs that are already in CloudWatch Logs. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeNoSuchQueryLoggingConfig "NoSuchQueryLoggingConfig" -// There is no DNS query logging configuration with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteQueryLoggingConfig -func (c *Route53) DeleteQueryLoggingConfig(input *DeleteQueryLoggingConfigInput) (*DeleteQueryLoggingConfigOutput, error) { - req, out := c.DeleteQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// DeleteQueryLoggingConfigWithContext is the same as DeleteQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteQueryLoggingConfigWithContext(ctx aws.Context, input *DeleteQueryLoggingConfigInput, opts ...request.Option) (*DeleteQueryLoggingConfigOutput, error) { - req, out := c.DeleteQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteReusableDelegationSet = "DeleteReusableDelegationSet" - -// DeleteReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the DeleteReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteReusableDelegationSet for more information on using the DeleteReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteReusableDelegationSetRequest method. -// req, resp := client.DeleteReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSet -func (c *Route53) DeleteReusableDelegationSetRequest(input *DeleteReusableDelegationSetInput) (req *request.Request, output *DeleteReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opDeleteReusableDelegationSet, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/delegationset/{Id}", - } - - if input == nil { - input = &DeleteReusableDelegationSetInput{} - } - - output = &DeleteReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteReusableDelegationSet API operation for Amazon Route 53. -// -// Deletes a reusable delegation set. -// -// You can delete a reusable delegation set only if it isn't associated with -// any hosted zones. -// -// To verify that the reusable delegation set is not associated with any hosted -// zones, submit a GetReusableDelegationSet request and specify the ID of the -// reusable delegation set that you want to delete. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetInUse "DelegationSetInUse" -// The specified delegation contains associated hosted zones which must be deleted -// before the reusable delegation set can be deleted. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteReusableDelegationSet -func (c *Route53) DeleteReusableDelegationSet(input *DeleteReusableDelegationSetInput) (*DeleteReusableDelegationSetOutput, error) { - req, out := c.DeleteReusableDelegationSetRequest(input) - return out, req.Send() -} - -// DeleteReusableDelegationSetWithContext is the same as DeleteReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteReusableDelegationSetWithContext(ctx aws.Context, input *DeleteReusableDelegationSetInput, opts ...request.Option) (*DeleteReusableDelegationSetOutput, error) { - req, out := c.DeleteReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteTrafficPolicy = "DeleteTrafficPolicy" - -// DeleteTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteTrafficPolicy for more information on using the DeleteTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteTrafficPolicyRequest method. -// req, resp := client.DeleteTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicy -func (c *Route53) DeleteTrafficPolicyRequest(input *DeleteTrafficPolicyInput) (req *request.Request, output *DeleteTrafficPolicyOutput) { - op := &request.Operation{ - Name: opDeleteTrafficPolicy, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &DeleteTrafficPolicyInput{} - } - - output = &DeleteTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteTrafficPolicy API operation for Amazon Route 53. -// -// Deletes a traffic policy. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeTrafficPolicyInUse "TrafficPolicyInUse" -// One or more traffic policy instances were created by using the specified -// traffic policy. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicy -func (c *Route53) DeleteTrafficPolicy(input *DeleteTrafficPolicyInput) (*DeleteTrafficPolicyOutput, error) { - req, out := c.DeleteTrafficPolicyRequest(input) - return out, req.Send() -} - -// DeleteTrafficPolicyWithContext is the same as DeleteTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteTrafficPolicyWithContext(ctx aws.Context, input *DeleteTrafficPolicyInput, opts ...request.Option) (*DeleteTrafficPolicyOutput, error) { - req, out := c.DeleteTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteTrafficPolicyInstance = "DeleteTrafficPolicyInstance" - -// DeleteTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the DeleteTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteTrafficPolicyInstance for more information on using the DeleteTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteTrafficPolicyInstanceRequest method. -// req, resp := client.DeleteTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstance -func (c *Route53) DeleteTrafficPolicyInstanceRequest(input *DeleteTrafficPolicyInstanceInput) (req *request.Request, output *DeleteTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opDeleteTrafficPolicyInstance, - HTTPMethod: "DELETE", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &DeleteTrafficPolicyInstanceInput{} - } - - output = &DeleteTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteTrafficPolicyInstance API operation for Amazon Route 53. -// -// Deletes a traffic policy instance and all of the resource record sets that -// Amazon Route 53 created when you created the instance. -// -// In the Amazon Route 53 console, traffic policy instances are known as policy -// records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteTrafficPolicyInstance -func (c *Route53) DeleteTrafficPolicyInstance(input *DeleteTrafficPolicyInstanceInput) (*DeleteTrafficPolicyInstanceOutput, error) { - req, out := c.DeleteTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// DeleteTrafficPolicyInstanceWithContext is the same as DeleteTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteTrafficPolicyInstanceWithContext(ctx aws.Context, input *DeleteTrafficPolicyInstanceInput, opts ...request.Option) (*DeleteTrafficPolicyInstanceOutput, error) { - req, out := c.DeleteTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDeleteVPCAssociationAuthorization = "DeleteVPCAssociationAuthorization" - -// DeleteVPCAssociationAuthorizationRequest generates a "aws/request.Request" representing the -// client's request for the DeleteVPCAssociationAuthorization operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DeleteVPCAssociationAuthorization for more information on using the DeleteVPCAssociationAuthorization -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DeleteVPCAssociationAuthorizationRequest method. -// req, resp := client.DeleteVPCAssociationAuthorizationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteVPCAssociationAuthorization -func (c *Route53) DeleteVPCAssociationAuthorizationRequest(input *DeleteVPCAssociationAuthorizationInput) (req *request.Request, output *DeleteVPCAssociationAuthorizationOutput) { - op := &request.Operation{ - Name: opDeleteVPCAssociationAuthorization, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/deauthorizevpcassociation", - } - - if input == nil { - input = &DeleteVPCAssociationAuthorizationInput{} - } - - output = &DeleteVPCAssociationAuthorizationOutput{} - req = c.newRequest(op, input, output) - return -} - -// DeleteVPCAssociationAuthorization API operation for Amazon Route 53. -// -// Removes authorization to submit an AssociateVPCWithHostedZone request to -// associate a specified VPC with a hosted zone that was created by a different -// account. You must use the account that created the hosted zone to submit -// a DeleteVPCAssociationAuthorization request. -// -// Sending this request only prevents the AWS account that created the VPC from -// associating the VPC with the Amazon Route 53 hosted zone in the future. If -// the VPC is already associated with the hosted zone, DeleteVPCAssociationAuthorization -// won't disassociate the VPC from the hosted zone. If you want to delete an -// existing association, use DisassociateVPCFromHostedZone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DeleteVPCAssociationAuthorization for usage and error information. -// -// Returned Error Codes: -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// * ErrCodeVPCAssociationAuthorizationNotFound "VPCAssociationAuthorizationNotFound" -// The VPC that you specified is not authorized to be associated with the hosted -// zone. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DeleteVPCAssociationAuthorization -func (c *Route53) DeleteVPCAssociationAuthorization(input *DeleteVPCAssociationAuthorizationInput) (*DeleteVPCAssociationAuthorizationOutput, error) { - req, out := c.DeleteVPCAssociationAuthorizationRequest(input) - return out, req.Send() -} - -// DeleteVPCAssociationAuthorizationWithContext is the same as DeleteVPCAssociationAuthorization with the addition of -// the ability to pass a context and additional request options. -// -// See DeleteVPCAssociationAuthorization for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DeleteVPCAssociationAuthorizationWithContext(ctx aws.Context, input *DeleteVPCAssociationAuthorizationInput, opts ...request.Option) (*DeleteVPCAssociationAuthorizationOutput, error) { - req, out := c.DeleteVPCAssociationAuthorizationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDisassociateVPCFromHostedZone = "DisassociateVPCFromHostedZone" - -// DisassociateVPCFromHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the DisassociateVPCFromHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DisassociateVPCFromHostedZone for more information on using the DisassociateVPCFromHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DisassociateVPCFromHostedZoneRequest method. -// req, resp := client.DisassociateVPCFromHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DisassociateVPCFromHostedZone -func (c *Route53) DisassociateVPCFromHostedZoneRequest(input *DisassociateVPCFromHostedZoneInput) (req *request.Request, output *DisassociateVPCFromHostedZoneOutput) { - op := &request.Operation{ - Name: opDisassociateVPCFromHostedZone, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}/disassociatevpc", - } - - if input == nil { - input = &DisassociateVPCFromHostedZoneInput{} - } - - output = &DisassociateVPCFromHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// DisassociateVPCFromHostedZone API operation for Amazon Route 53. -// -// Disassociates a VPC from a Amazon Route 53 private hosted zone. -// -// You can't disassociate the last VPC from a private hosted zone. -// -// You can't disassociate a VPC from a private hosted zone when only one VPC -// is associated with the hosted zone. You also can't convert a private hosted -// zone into a public hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation DisassociateVPCFromHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidVPCId "InvalidVPCId" -// The VPC ID that you specified either isn't a valid ID or the current account -// is not authorized to access this VPC. -// -// * ErrCodeVPCAssociationNotFound "VPCAssociationNotFound" -// The specified VPC and hosted zone are not currently associated. -// -// * ErrCodeLastVPCAssociation "LastVPCAssociation" -// The VPC that you're trying to disassociate from the private hosted zone is -// the last VPC that is associated with the hosted zone. Amazon Route 53 doesn't -// support disassociating the last VPC from a hosted zone. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/DisassociateVPCFromHostedZone -func (c *Route53) DisassociateVPCFromHostedZone(input *DisassociateVPCFromHostedZoneInput) (*DisassociateVPCFromHostedZoneOutput, error) { - req, out := c.DisassociateVPCFromHostedZoneRequest(input) - return out, req.Send() -} - -// DisassociateVPCFromHostedZoneWithContext is the same as DisassociateVPCFromHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See DisassociateVPCFromHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) DisassociateVPCFromHostedZoneWithContext(ctx aws.Context, input *DisassociateVPCFromHostedZoneInput, opts ...request.Option) (*DisassociateVPCFromHostedZoneOutput, error) { - req, out := c.DisassociateVPCFromHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetAccountLimit = "GetAccountLimit" - -// GetAccountLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetAccountLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetAccountLimit for more information on using the GetAccountLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetAccountLimitRequest method. -// req, resp := client.GetAccountLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetAccountLimit -func (c *Route53) GetAccountLimitRequest(input *GetAccountLimitInput) (req *request.Request, output *GetAccountLimitOutput) { - op := &request.Operation{ - Name: opGetAccountLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/accountlimit/{Type}", - } - - if input == nil { - input = &GetAccountLimitInput{} - } - - output = &GetAccountLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetAccountLimit API operation for Amazon Route 53. -// -// Gets the specified limit for the current account, for example, the maximum -// number of health checks that you can create using the account. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetAccountLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetAccountLimit -func (c *Route53) GetAccountLimit(input *GetAccountLimitInput) (*GetAccountLimitOutput, error) { - req, out := c.GetAccountLimitRequest(input) - return out, req.Send() -} - -// GetAccountLimitWithContext is the same as GetAccountLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetAccountLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetAccountLimitWithContext(ctx aws.Context, input *GetAccountLimitInput, opts ...request.Option) (*GetAccountLimitOutput, error) { - req, out := c.GetAccountLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetChange = "GetChange" - -// GetChangeRequest generates a "aws/request.Request" representing the -// client's request for the GetChange operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetChange for more information on using the GetChange -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetChangeRequest method. -// req, resp := client.GetChangeRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetChange -func (c *Route53) GetChangeRequest(input *GetChangeInput) (req *request.Request, output *GetChangeOutput) { - op := &request.Operation{ - Name: opGetChange, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/change/{Id}", - } - - if input == nil { - input = &GetChangeInput{} - } - - output = &GetChangeOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetChange API operation for Amazon Route 53. -// -// Returns the current status of a change batch request. The status is one of -// the following values: -// -// * PENDING indicates that the changes in this request have not propagated -// to all Amazon Route 53 DNS servers. This is the initial status of all -// change batch requests. -// -// * INSYNC indicates that the changes have propagated to all Amazon Route -// 53 DNS servers. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetChange for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchChange "NoSuchChange" -// A change with the specified change ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetChange -func (c *Route53) GetChange(input *GetChangeInput) (*GetChangeOutput, error) { - req, out := c.GetChangeRequest(input) - return out, req.Send() -} - -// GetChangeWithContext is the same as GetChange with the addition of -// the ability to pass a context and additional request options. -// -// See GetChange for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetChangeWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.Option) (*GetChangeOutput, error) { - req, out := c.GetChangeRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCheckerIpRanges = "GetCheckerIpRanges" - -// GetCheckerIpRangesRequest generates a "aws/request.Request" representing the -// client's request for the GetCheckerIpRanges operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetCheckerIpRanges for more information on using the GetCheckerIpRanges -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetCheckerIpRangesRequest method. -// req, resp := client.GetCheckerIpRangesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetCheckerIpRanges -func (c *Route53) GetCheckerIpRangesRequest(input *GetCheckerIpRangesInput) (req *request.Request, output *GetCheckerIpRangesOutput) { - op := &request.Operation{ - Name: opGetCheckerIpRanges, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/checkeripranges", - } - - if input == nil { - input = &GetCheckerIpRangesInput{} - } - - output = &GetCheckerIpRangesOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCheckerIpRanges API operation for Amazon Route 53. -// -// GetCheckerIpRanges still works, but we recommend that you download ip-ranges.json, -// which includes IP address ranges for all AWS services. For more information, -// see IP Address Ranges of Amazon Route 53 Servers (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-ip-addresses.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetCheckerIpRanges for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetCheckerIpRanges -func (c *Route53) GetCheckerIpRanges(input *GetCheckerIpRangesInput) (*GetCheckerIpRangesOutput, error) { - req, out := c.GetCheckerIpRangesRequest(input) - return out, req.Send() -} - -// GetCheckerIpRangesWithContext is the same as GetCheckerIpRanges with the addition of -// the ability to pass a context and additional request options. -// -// See GetCheckerIpRanges for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetCheckerIpRangesWithContext(ctx aws.Context, input *GetCheckerIpRangesInput, opts ...request.Option) (*GetCheckerIpRangesOutput, error) { - req, out := c.GetCheckerIpRangesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetGeoLocation = "GetGeoLocation" - -// GetGeoLocationRequest generates a "aws/request.Request" representing the -// client's request for the GetGeoLocation operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetGeoLocation for more information on using the GetGeoLocation -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetGeoLocationRequest method. -// req, resp := client.GetGeoLocationRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocation -func (c *Route53) GetGeoLocationRequest(input *GetGeoLocationInput) (req *request.Request, output *GetGeoLocationOutput) { - op := &request.Operation{ - Name: opGetGeoLocation, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/geolocation", - } - - if input == nil { - input = &GetGeoLocationInput{} - } - - output = &GetGeoLocationOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetGeoLocation API operation for Amazon Route 53. -// -// Gets information about whether a specified geographic location is supported -// for Amazon Route 53 geolocation resource record sets. -// -// Use the following syntax to determine whether a continent is supported for -// geolocation: -// -// GET /2013-04-01/geolocation?ContinentCode=two-letter abbreviation for a continent -// -// Use the following syntax to determine whether a country is supported for -// geolocation: -// -// GET /2013-04-01/geolocation?CountryCode=two-character country code -// -// Use the following syntax to determine whether a subdivision of a country -// is supported for geolocation: -// -// GET /2013-04-01/geolocation?CountryCode=two-character country code&SubdivisionCode=subdivision -// code -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetGeoLocation for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchGeoLocation "NoSuchGeoLocation" -// Amazon Route 53 doesn't support the specified geolocation. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetGeoLocation -func (c *Route53) GetGeoLocation(input *GetGeoLocationInput) (*GetGeoLocationOutput, error) { - req, out := c.GetGeoLocationRequest(input) - return out, req.Send() -} - -// GetGeoLocationWithContext is the same as GetGeoLocation with the addition of -// the ability to pass a context and additional request options. -// -// See GetGeoLocation for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetGeoLocationWithContext(ctx aws.Context, input *GetGeoLocationInput, opts ...request.Option) (*GetGeoLocationOutput, error) { - req, out := c.GetGeoLocationRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheck = "GetHealthCheck" - -// GetHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheck for more information on using the GetHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckRequest method. -// req, resp := client.GetHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheck -func (c *Route53) GetHealthCheckRequest(input *GetHealthCheckInput) (req *request.Request, output *GetHealthCheckOutput) { - op := &request.Operation{ - Name: opGetHealthCheck, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &GetHealthCheckInput{} - } - - output = &GetHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheck API operation for Amazon Route 53. -// -// Gets information about a specified health check. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeIncompatibleVersion "IncompatibleVersion" -// The resource you're trying to access is unsupported on this Amazon Route -// 53 endpoint. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheck -func (c *Route53) GetHealthCheck(input *GetHealthCheckInput) (*GetHealthCheckOutput, error) { - req, out := c.GetHealthCheckRequest(input) - return out, req.Send() -} - -// GetHealthCheckWithContext is the same as GetHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckWithContext(ctx aws.Context, input *GetHealthCheckInput, opts ...request.Option) (*GetHealthCheckOutput, error) { - req, out := c.GetHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckCount = "GetHealthCheckCount" - -// GetHealthCheckCountRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckCount for more information on using the GetHealthCheckCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckCountRequest method. -// req, resp := client.GetHealthCheckCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCount -func (c *Route53) GetHealthCheckCountRequest(input *GetHealthCheckCountInput) (req *request.Request, output *GetHealthCheckCountOutput) { - op := &request.Operation{ - Name: opGetHealthCheckCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheckcount", - } - - if input == nil { - input = &GetHealthCheckCountInput{} - } - - output = &GetHealthCheckCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckCount API operation for Amazon Route 53. -// -// Retrieves the number of health checks that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckCount for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckCount -func (c *Route53) GetHealthCheckCount(input *GetHealthCheckCountInput) (*GetHealthCheckCountOutput, error) { - req, out := c.GetHealthCheckCountRequest(input) - return out, req.Send() -} - -// GetHealthCheckCountWithContext is the same as GetHealthCheckCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckCountWithContext(ctx aws.Context, input *GetHealthCheckCountInput, opts ...request.Option) (*GetHealthCheckCountOutput, error) { - req, out := c.GetHealthCheckCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckLastFailureReason = "GetHealthCheckLastFailureReason" - -// GetHealthCheckLastFailureReasonRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckLastFailureReason operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckLastFailureReason for more information on using the GetHealthCheckLastFailureReason -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckLastFailureReasonRequest method. -// req, resp := client.GetHealthCheckLastFailureReasonRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReason -func (c *Route53) GetHealthCheckLastFailureReasonRequest(input *GetHealthCheckLastFailureReasonInput) (req *request.Request, output *GetHealthCheckLastFailureReasonOutput) { - op := &request.Operation{ - Name: opGetHealthCheckLastFailureReason, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}/lastfailurereason", - } - - if input == nil { - input = &GetHealthCheckLastFailureReasonInput{} - } - - output = &GetHealthCheckLastFailureReasonOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckLastFailureReason API operation for Amazon Route 53. -// -// Gets the reason that a specified health check failed most recently. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckLastFailureReason for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckLastFailureReason -func (c *Route53) GetHealthCheckLastFailureReason(input *GetHealthCheckLastFailureReasonInput) (*GetHealthCheckLastFailureReasonOutput, error) { - req, out := c.GetHealthCheckLastFailureReasonRequest(input) - return out, req.Send() -} - -// GetHealthCheckLastFailureReasonWithContext is the same as GetHealthCheckLastFailureReason with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckLastFailureReason for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckLastFailureReasonWithContext(ctx aws.Context, input *GetHealthCheckLastFailureReasonInput, opts ...request.Option) (*GetHealthCheckLastFailureReasonOutput, error) { - req, out := c.GetHealthCheckLastFailureReasonRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHealthCheckStatus = "GetHealthCheckStatus" - -// GetHealthCheckStatusRequest generates a "aws/request.Request" representing the -// client's request for the GetHealthCheckStatus operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHealthCheckStatus for more information on using the GetHealthCheckStatus -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHealthCheckStatusRequest method. -// req, resp := client.GetHealthCheckStatusRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatus -func (c *Route53) GetHealthCheckStatusRequest(input *GetHealthCheckStatusInput) (req *request.Request, output *GetHealthCheckStatusOutput) { - op := &request.Operation{ - Name: opGetHealthCheckStatus, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}/status", - } - - if input == nil { - input = &GetHealthCheckStatusInput{} - } - - output = &GetHealthCheckStatusOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHealthCheckStatus API operation for Amazon Route 53. -// -// Gets status of a specified health check. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHealthCheckStatus for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHealthCheckStatus -func (c *Route53) GetHealthCheckStatus(input *GetHealthCheckStatusInput) (*GetHealthCheckStatusOutput, error) { - req, out := c.GetHealthCheckStatusRequest(input) - return out, req.Send() -} - -// GetHealthCheckStatusWithContext is the same as GetHealthCheckStatus with the addition of -// the ability to pass a context and additional request options. -// -// See GetHealthCheckStatus for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHealthCheckStatusWithContext(ctx aws.Context, input *GetHealthCheckStatusInput, opts ...request.Option) (*GetHealthCheckStatusOutput, error) { - req, out := c.GetHealthCheckStatusRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZone = "GetHostedZone" - -// GetHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZone for more information on using the GetHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneRequest method. -// req, resp := client.GetHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZone -func (c *Route53) GetHostedZoneRequest(input *GetHostedZoneInput) (req *request.Request, output *GetHostedZoneOutput) { - op := &request.Operation{ - Name: opGetHostedZone, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &GetHostedZoneInput{} - } - - output = &GetHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZone API operation for Amazon Route 53. -// -// Gets information about a specified hosted zone including the four name servers -// assigned to the hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZone -func (c *Route53) GetHostedZone(input *GetHostedZoneInput) (*GetHostedZoneOutput, error) { - req, out := c.GetHostedZoneRequest(input) - return out, req.Send() -} - -// GetHostedZoneWithContext is the same as GetHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneWithContext(ctx aws.Context, input *GetHostedZoneInput, opts ...request.Option) (*GetHostedZoneOutput, error) { - req, out := c.GetHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZoneCount = "GetHostedZoneCount" - -// GetHostedZoneCountRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZoneCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZoneCount for more information on using the GetHostedZoneCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneCountRequest method. -// req, resp := client.GetHostedZoneCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCount -func (c *Route53) GetHostedZoneCountRequest(input *GetHostedZoneCountInput) (req *request.Request, output *GetHostedZoneCountOutput) { - op := &request.Operation{ - Name: opGetHostedZoneCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonecount", - } - - if input == nil { - input = &GetHostedZoneCountInput{} - } - - output = &GetHostedZoneCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZoneCount API operation for Amazon Route 53. -// -// Retrieves the number of hosted zones that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZoneCount for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneCount -func (c *Route53) GetHostedZoneCount(input *GetHostedZoneCountInput) (*GetHostedZoneCountOutput, error) { - req, out := c.GetHostedZoneCountRequest(input) - return out, req.Send() -} - -// GetHostedZoneCountWithContext is the same as GetHostedZoneCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZoneCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneCountWithContext(ctx aws.Context, input *GetHostedZoneCountInput, opts ...request.Option) (*GetHostedZoneCountOutput, error) { - req, out := c.GetHostedZoneCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetHostedZoneLimit = "GetHostedZoneLimit" - -// GetHostedZoneLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetHostedZoneLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetHostedZoneLimit for more information on using the GetHostedZoneLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetHostedZoneLimitRequest method. -// req, resp := client.GetHostedZoneLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneLimit -func (c *Route53) GetHostedZoneLimitRequest(input *GetHostedZoneLimitInput) (req *request.Request, output *GetHostedZoneLimitOutput) { - op := &request.Operation{ - Name: opGetHostedZoneLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonelimit/{Id}/{Type}", - } - - if input == nil { - input = &GetHostedZoneLimitInput{} - } - - output = &GetHostedZoneLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetHostedZoneLimit API operation for Amazon Route 53. -// -// Gets the specified limit for a specified hosted zone, for example, the maximum -// number of records that you can create in the hosted zone. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetHostedZoneLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeHostedZoneNotPrivate "HostedZoneNotPrivate" -// The specified hosted zone is a public hosted zone, not a private hosted zone. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetHostedZoneLimit -func (c *Route53) GetHostedZoneLimit(input *GetHostedZoneLimitInput) (*GetHostedZoneLimitOutput, error) { - req, out := c.GetHostedZoneLimitRequest(input) - return out, req.Send() -} - -// GetHostedZoneLimitWithContext is the same as GetHostedZoneLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetHostedZoneLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetHostedZoneLimitWithContext(ctx aws.Context, input *GetHostedZoneLimitInput, opts ...request.Option) (*GetHostedZoneLimitOutput, error) { - req, out := c.GetHostedZoneLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetQueryLoggingConfig = "GetQueryLoggingConfig" - -// GetQueryLoggingConfigRequest generates a "aws/request.Request" representing the -// client's request for the GetQueryLoggingConfig operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetQueryLoggingConfig for more information on using the GetQueryLoggingConfig -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetQueryLoggingConfigRequest method. -// req, resp := client.GetQueryLoggingConfigRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetQueryLoggingConfig -func (c *Route53) GetQueryLoggingConfigRequest(input *GetQueryLoggingConfigInput) (req *request.Request, output *GetQueryLoggingConfigOutput) { - op := &request.Operation{ - Name: opGetQueryLoggingConfig, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/queryloggingconfig/{Id}", - } - - if input == nil { - input = &GetQueryLoggingConfigInput{} - } - - output = &GetQueryLoggingConfigOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetQueryLoggingConfig API operation for Amazon Route 53. -// -// Gets information about a specified configuration for DNS query logging. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig and -// Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetQueryLoggingConfig for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchQueryLoggingConfig "NoSuchQueryLoggingConfig" -// There is no DNS query logging configuration with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetQueryLoggingConfig -func (c *Route53) GetQueryLoggingConfig(input *GetQueryLoggingConfigInput) (*GetQueryLoggingConfigOutput, error) { - req, out := c.GetQueryLoggingConfigRequest(input) - return out, req.Send() -} - -// GetQueryLoggingConfigWithContext is the same as GetQueryLoggingConfig with the addition of -// the ability to pass a context and additional request options. -// -// See GetQueryLoggingConfig for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetQueryLoggingConfigWithContext(ctx aws.Context, input *GetQueryLoggingConfigInput, opts ...request.Option) (*GetQueryLoggingConfigOutput, error) { - req, out := c.GetQueryLoggingConfigRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetReusableDelegationSet = "GetReusableDelegationSet" - -// GetReusableDelegationSetRequest generates a "aws/request.Request" representing the -// client's request for the GetReusableDelegationSet operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetReusableDelegationSet for more information on using the GetReusableDelegationSet -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetReusableDelegationSetRequest method. -// req, resp := client.GetReusableDelegationSetRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSet -func (c *Route53) GetReusableDelegationSetRequest(input *GetReusableDelegationSetInput) (req *request.Request, output *GetReusableDelegationSetOutput) { - op := &request.Operation{ - Name: opGetReusableDelegationSet, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/delegationset/{Id}", - } - - if input == nil { - input = &GetReusableDelegationSetInput{} - } - - output = &GetReusableDelegationSetOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetReusableDelegationSet API operation for Amazon Route 53. -// -// Retrieves information about a specified reusable delegation set, including -// the four name servers that are assigned to the delegation set. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetReusableDelegationSet for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSet -func (c *Route53) GetReusableDelegationSet(input *GetReusableDelegationSetInput) (*GetReusableDelegationSetOutput, error) { - req, out := c.GetReusableDelegationSetRequest(input) - return out, req.Send() -} - -// GetReusableDelegationSetWithContext is the same as GetReusableDelegationSet with the addition of -// the ability to pass a context and additional request options. -// -// See GetReusableDelegationSet for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetReusableDelegationSetWithContext(ctx aws.Context, input *GetReusableDelegationSetInput, opts ...request.Option) (*GetReusableDelegationSetOutput, error) { - req, out := c.GetReusableDelegationSetRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetReusableDelegationSetLimit = "GetReusableDelegationSetLimit" - -// GetReusableDelegationSetLimitRequest generates a "aws/request.Request" representing the -// client's request for the GetReusableDelegationSetLimit operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetReusableDelegationSetLimit for more information on using the GetReusableDelegationSetLimit -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetReusableDelegationSetLimitRequest method. -// req, resp := client.GetReusableDelegationSetLimitRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSetLimit -func (c *Route53) GetReusableDelegationSetLimitRequest(input *GetReusableDelegationSetLimitInput) (req *request.Request, output *GetReusableDelegationSetLimitOutput) { - op := &request.Operation{ - Name: opGetReusableDelegationSetLimit, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/reusabledelegationsetlimit/{Id}/{Type}", - } - - if input == nil { - input = &GetReusableDelegationSetLimitInput{} - } - - output = &GetReusableDelegationSetLimitOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetReusableDelegationSetLimit API operation for Amazon Route 53. -// -// Gets the maximum number of hosted zones that you can associate with the specified -// reusable delegation set. -// -// For the default limit, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) -// in the Amazon Route 53 Developer Guide. To request a higher limit, open a -// case (https://console.aws.amazon.com/support/home#/case/create?issueType=service-limit-increase&limitType=service-code-route53). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetReusableDelegationSetLimit for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetReusableDelegationSetLimit -func (c *Route53) GetReusableDelegationSetLimit(input *GetReusableDelegationSetLimitInput) (*GetReusableDelegationSetLimitOutput, error) { - req, out := c.GetReusableDelegationSetLimitRequest(input) - return out, req.Send() -} - -// GetReusableDelegationSetLimitWithContext is the same as GetReusableDelegationSetLimit with the addition of -// the ability to pass a context and additional request options. -// -// See GetReusableDelegationSetLimit for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetReusableDelegationSetLimitWithContext(ctx aws.Context, input *GetReusableDelegationSetLimitInput, opts ...request.Option) (*GetReusableDelegationSetLimitOutput, error) { - req, out := c.GetReusableDelegationSetLimitRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicy = "GetTrafficPolicy" - -// GetTrafficPolicyRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicy for more information on using the GetTrafficPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyRequest method. -// req, resp := client.GetTrafficPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicy -func (c *Route53) GetTrafficPolicyRequest(input *GetTrafficPolicyInput) (req *request.Request, output *GetTrafficPolicyOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicy, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &GetTrafficPolicyInput{} - } - - output = &GetTrafficPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicy API operation for Amazon Route 53. -// -// Gets information about a specific traffic policy version. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicy -func (c *Route53) GetTrafficPolicy(input *GetTrafficPolicyInput) (*GetTrafficPolicyOutput, error) { - req, out := c.GetTrafficPolicyRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyWithContext is the same as GetTrafficPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyWithContext(ctx aws.Context, input *GetTrafficPolicyInput, opts ...request.Option) (*GetTrafficPolicyOutput, error) { - req, out := c.GetTrafficPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicyInstance = "GetTrafficPolicyInstance" - -// GetTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicyInstance for more information on using the GetTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyInstanceRequest method. -// req, resp := client.GetTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstance -func (c *Route53) GetTrafficPolicyInstanceRequest(input *GetTrafficPolicyInstanceInput) (req *request.Request, output *GetTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicyInstance, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &GetTrafficPolicyInstanceInput{} - } - - output = &GetTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicyInstance API operation for Amazon Route 53. -// -// Gets information about a specified traffic policy instance. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// In the Amazon Route 53 console, traffic policy instances are known as policy -// records. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstance -func (c *Route53) GetTrafficPolicyInstance(input *GetTrafficPolicyInstanceInput) (*GetTrafficPolicyInstanceOutput, error) { - req, out := c.GetTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyInstanceWithContext is the same as GetTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyInstanceWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceInput, opts ...request.Option) (*GetTrafficPolicyInstanceOutput, error) { - req, out := c.GetTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetTrafficPolicyInstanceCount = "GetTrafficPolicyInstanceCount" - -// GetTrafficPolicyInstanceCountRequest generates a "aws/request.Request" representing the -// client's request for the GetTrafficPolicyInstanceCount operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetTrafficPolicyInstanceCount for more information on using the GetTrafficPolicyInstanceCount -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetTrafficPolicyInstanceCountRequest method. -// req, resp := client.GetTrafficPolicyInstanceCountRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceCount -func (c *Route53) GetTrafficPolicyInstanceCountRequest(input *GetTrafficPolicyInstanceCountInput) (req *request.Request, output *GetTrafficPolicyInstanceCountOutput) { - op := &request.Operation{ - Name: opGetTrafficPolicyInstanceCount, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstancecount", - } - - if input == nil { - input = &GetTrafficPolicyInstanceCountInput{} - } - - output = &GetTrafficPolicyInstanceCountOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetTrafficPolicyInstanceCount API operation for Amazon Route 53. -// -// Gets the number of traffic policy instances that are associated with the -// current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation GetTrafficPolicyInstanceCount for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/GetTrafficPolicyInstanceCount -func (c *Route53) GetTrafficPolicyInstanceCount(input *GetTrafficPolicyInstanceCountInput) (*GetTrafficPolicyInstanceCountOutput, error) { - req, out := c.GetTrafficPolicyInstanceCountRequest(input) - return out, req.Send() -} - -// GetTrafficPolicyInstanceCountWithContext is the same as GetTrafficPolicyInstanceCount with the addition of -// the ability to pass a context and additional request options. -// -// See GetTrafficPolicyInstanceCount for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) GetTrafficPolicyInstanceCountWithContext(ctx aws.Context, input *GetTrafficPolicyInstanceCountInput, opts ...request.Option) (*GetTrafficPolicyInstanceCountOutput, error) { - req, out := c.GetTrafficPolicyInstanceCountRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListGeoLocations = "ListGeoLocations" - -// ListGeoLocationsRequest generates a "aws/request.Request" representing the -// client's request for the ListGeoLocations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListGeoLocations for more information on using the ListGeoLocations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListGeoLocationsRequest method. -// req, resp := client.ListGeoLocationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocations -func (c *Route53) ListGeoLocationsRequest(input *ListGeoLocationsInput) (req *request.Request, output *ListGeoLocationsOutput) { - op := &request.Operation{ - Name: opListGeoLocations, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/geolocations", - } - - if input == nil { - input = &ListGeoLocationsInput{} - } - - output = &ListGeoLocationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListGeoLocations API operation for Amazon Route 53. -// -// Retrieves a list of supported geo locations. -// -// Countries are listed first, and continents are listed last. If Amazon Route -// 53 supports subdivisions for a country (for example, states or provinces), -// the subdivisions for that country are listed in alphabetical order immediately -// after the corresponding country. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListGeoLocations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListGeoLocations -func (c *Route53) ListGeoLocations(input *ListGeoLocationsInput) (*ListGeoLocationsOutput, error) { - req, out := c.ListGeoLocationsRequest(input) - return out, req.Send() -} - -// ListGeoLocationsWithContext is the same as ListGeoLocations with the addition of -// the ability to pass a context and additional request options. -// -// See ListGeoLocations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListGeoLocationsWithContext(ctx aws.Context, input *ListGeoLocationsInput, opts ...request.Option) (*ListGeoLocationsOutput, error) { - req, out := c.ListGeoLocationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListHealthChecks = "ListHealthChecks" - -// ListHealthChecksRequest generates a "aws/request.Request" representing the -// client's request for the ListHealthChecks operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHealthChecks for more information on using the ListHealthChecks -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHealthChecksRequest method. -// req, resp := client.ListHealthChecksRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecks -func (c *Route53) ListHealthChecksRequest(input *ListHealthChecksInput) (req *request.Request, output *ListHealthChecksOutput) { - op := &request.Operation{ - Name: opListHealthChecks, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/healthcheck", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListHealthChecksInput{} - } - - output = &ListHealthChecksOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHealthChecks API operation for Amazon Route 53. -// -// Retrieve a list of the health checks that are associated with the current -// AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHealthChecks for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeIncompatibleVersion "IncompatibleVersion" -// The resource you're trying to access is unsupported on this Amazon Route -// 53 endpoint. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHealthChecks -func (c *Route53) ListHealthChecks(input *ListHealthChecksInput) (*ListHealthChecksOutput, error) { - req, out := c.ListHealthChecksRequest(input) - return out, req.Send() -} - -// ListHealthChecksWithContext is the same as ListHealthChecks with the addition of -// the ability to pass a context and additional request options. -// -// See ListHealthChecks for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHealthChecksWithContext(ctx aws.Context, input *ListHealthChecksInput, opts ...request.Option) (*ListHealthChecksOutput, error) { - req, out := c.ListHealthChecksRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListHealthChecksPages iterates over the pages of a ListHealthChecks operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListHealthChecks method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListHealthChecks operation. -// pageNum := 0 -// err := client.ListHealthChecksPages(params, -// func(page *ListHealthChecksOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListHealthChecksPages(input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool) error { - return c.ListHealthChecksPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListHealthChecksPagesWithContext same as ListHealthChecksPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHealthChecksPagesWithContext(ctx aws.Context, input *ListHealthChecksInput, fn func(*ListHealthChecksOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListHealthChecksInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListHealthChecksRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListHealthChecksOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListHostedZones = "ListHostedZones" - -// ListHostedZonesRequest generates a "aws/request.Request" representing the -// client's request for the ListHostedZones operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHostedZones for more information on using the ListHostedZones -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHostedZonesRequest method. -// req, resp := client.ListHostedZonesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZones -func (c *Route53) ListHostedZonesRequest(input *ListHostedZonesInput) (req *request.Request, output *ListHostedZonesOutput) { - op := &request.Operation{ - Name: opListHostedZones, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone", - Paginator: &request.Paginator{ - InputTokens: []string{"Marker"}, - OutputTokens: []string{"NextMarker"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListHostedZonesInput{} - } - - output = &ListHostedZonesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHostedZones API operation for Amazon Route 53. -// -// Retrieves a list of the public and private hosted zones that are associated -// with the current AWS account. The response includes a HostedZones child element -// for each hosted zone. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of hosted zones, you can use the maxitems parameter to list them in -// groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHostedZones for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchDelegationSet "NoSuchDelegationSet" -// A reusable delegation set with the specified ID does not exist. -// -// * ErrCodeDelegationSetNotReusable "DelegationSetNotReusable" -// A reusable delegation set with the specified ID does not exist. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZones -func (c *Route53) ListHostedZones(input *ListHostedZonesInput) (*ListHostedZonesOutput, error) { - req, out := c.ListHostedZonesRequest(input) - return out, req.Send() -} - -// ListHostedZonesWithContext is the same as ListHostedZones with the addition of -// the ability to pass a context and additional request options. -// -// See ListHostedZones for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesWithContext(ctx aws.Context, input *ListHostedZonesInput, opts ...request.Option) (*ListHostedZonesOutput, error) { - req, out := c.ListHostedZonesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListHostedZonesPages iterates over the pages of a ListHostedZones operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListHostedZones method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListHostedZones operation. -// pageNum := 0 -// err := client.ListHostedZonesPages(params, -// func(page *ListHostedZonesOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListHostedZonesPages(input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool) error { - return c.ListHostedZonesPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListHostedZonesPagesWithContext same as ListHostedZonesPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesPagesWithContext(ctx aws.Context, input *ListHostedZonesInput, fn func(*ListHostedZonesOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListHostedZonesInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListHostedZonesRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListHostedZonesOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListHostedZonesByName = "ListHostedZonesByName" - -// ListHostedZonesByNameRequest generates a "aws/request.Request" representing the -// client's request for the ListHostedZonesByName operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListHostedZonesByName for more information on using the ListHostedZonesByName -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListHostedZonesByNameRequest method. -// req, resp := client.ListHostedZonesByNameRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByName -func (c *Route53) ListHostedZonesByNameRequest(input *ListHostedZonesByNameInput) (req *request.Request, output *ListHostedZonesByNameOutput) { - op := &request.Operation{ - Name: opListHostedZonesByName, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzonesbyname", - } - - if input == nil { - input = &ListHostedZonesByNameInput{} - } - - output = &ListHostedZonesByNameOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListHostedZonesByName API operation for Amazon Route 53. -// -// Retrieves a list of your hosted zones in lexicographic order. The response -// includes a HostedZones child element for each hosted zone created by the -// current AWS account. -// -// ListHostedZonesByName sorts hosted zones by name with the labels reversed. -// For example: -// -// com.example.www. -// -// Note the trailing dot, which can change the sort order in some circumstances. -// -// If the domain name includes escape characters or Punycode, ListHostedZonesByName -// alphabetizes the domain name using the escaped or Punycoded value, which -// is the format that Amazon Route 53 saves in its database. For example, to -// create a hosted zone for exämple.com, you specify ex\344mple.com for the -// domain name. ListHostedZonesByName alphabetizes it as: -// -// com.ex\344mple. -// -// The labels are reversed and alphabetized using the escaped value. For more -// information about valid domain name formats, including internationalized -// domain names, see DNS Domain Name Format (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) -// in the Amazon Route 53 Developer Guide. -// -// Amazon Route 53 returns up to 100 items in each response. If you have a lot -// of hosted zones, use the MaxItems parameter to list them in groups of up -// to 100. The response includes values that help navigate from one group of -// MaxItems hosted zones to the next: -// -// * The DNSName and HostedZoneId elements in the response contain the values, -// if any, specified for the dnsname and hostedzoneid parameters in the request -// that produced the current response. -// -// * The MaxItems element in the response contains the value, if any, that -// you specified for the maxitems parameter in the request that produced -// the current response. -// -// * If the value of IsTruncated in the response is true, there are more -// hosted zones associated with the current AWS account. -// -// If IsTruncated is false, this response includes the last hosted zone that -// is associated with the current account. The NextDNSName element and NextHostedZoneId -// elements are omitted from the response. -// -// * The NextDNSName and NextHostedZoneId elements in the response contain -// the domain name and the hosted zone ID of the next hosted zone that is -// associated with the current AWS account. If you want to list more hosted -// zones, make another call to ListHostedZonesByName, and specify the value -// of NextDNSName and NextHostedZoneId in the dnsname and hostedzoneid parameters, -// respectively. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListHostedZonesByName for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidDomainName "InvalidDomainName" -// The specified domain name is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListHostedZonesByName -func (c *Route53) ListHostedZonesByName(input *ListHostedZonesByNameInput) (*ListHostedZonesByNameOutput, error) { - req, out := c.ListHostedZonesByNameRequest(input) - return out, req.Send() -} - -// ListHostedZonesByNameWithContext is the same as ListHostedZonesByName with the addition of -// the ability to pass a context and additional request options. -// -// See ListHostedZonesByName for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListHostedZonesByNameWithContext(ctx aws.Context, input *ListHostedZonesByNameInput, opts ...request.Option) (*ListHostedZonesByNameOutput, error) { - req, out := c.ListHostedZonesByNameRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListQueryLoggingConfigs = "ListQueryLoggingConfigs" - -// ListQueryLoggingConfigsRequest generates a "aws/request.Request" representing the -// client's request for the ListQueryLoggingConfigs operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListQueryLoggingConfigs for more information on using the ListQueryLoggingConfigs -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListQueryLoggingConfigsRequest method. -// req, resp := client.ListQueryLoggingConfigsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListQueryLoggingConfigs -func (c *Route53) ListQueryLoggingConfigsRequest(input *ListQueryLoggingConfigsInput) (req *request.Request, output *ListQueryLoggingConfigsOutput) { - op := &request.Operation{ - Name: opListQueryLoggingConfigs, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/queryloggingconfig", - } - - if input == nil { - input = &ListQueryLoggingConfigsInput{} - } - - output = &ListQueryLoggingConfigsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListQueryLoggingConfigs API operation for Amazon Route 53. -// -// Lists the configurations for DNS query logging that are associated with the -// current AWS account or the configuration that is associated with a specified -// hosted zone. -// -// For more information about DNS query logs, see CreateQueryLoggingConfig. -// Additional information, including the format of DNS query logs, appears in -// Logging DNS Queries (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListQueryLoggingConfigs for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidPaginationToken "InvalidPaginationToken" -// The value that you specified to get the second or subsequent page of results -// is invalid. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListQueryLoggingConfigs -func (c *Route53) ListQueryLoggingConfigs(input *ListQueryLoggingConfigsInput) (*ListQueryLoggingConfigsOutput, error) { - req, out := c.ListQueryLoggingConfigsRequest(input) - return out, req.Send() -} - -// ListQueryLoggingConfigsWithContext is the same as ListQueryLoggingConfigs with the addition of -// the ability to pass a context and additional request options. -// -// See ListQueryLoggingConfigs for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListQueryLoggingConfigsWithContext(ctx aws.Context, input *ListQueryLoggingConfigsInput, opts ...request.Option) (*ListQueryLoggingConfigsOutput, error) { - req, out := c.ListQueryLoggingConfigsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListResourceRecordSets = "ListResourceRecordSets" - -// ListResourceRecordSetsRequest generates a "aws/request.Request" representing the -// client's request for the ListResourceRecordSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListResourceRecordSets for more information on using the ListResourceRecordSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListResourceRecordSetsRequest method. -// req, resp := client.ListResourceRecordSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSets -func (c *Route53) ListResourceRecordSetsRequest(input *ListResourceRecordSetsInput) (req *request.Request, output *ListResourceRecordSetsOutput) { - op := &request.Operation{ - Name: opListResourceRecordSets, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}/rrset", - Paginator: &request.Paginator{ - InputTokens: []string{"StartRecordName", "StartRecordType", "StartRecordIdentifier"}, - OutputTokens: []string{"NextRecordName", "NextRecordType", "NextRecordIdentifier"}, - LimitToken: "MaxItems", - TruncationToken: "IsTruncated", - }, - } - - if input == nil { - input = &ListResourceRecordSetsInput{} - } - - output = &ListResourceRecordSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListResourceRecordSets API operation for Amazon Route 53. -// -// Lists the resource record sets in a specified hosted zone. -// -// ListResourceRecordSets returns up to 100 resource record sets at a time in -// ASCII order, beginning at a position specified by the name and type elements. -// The action sorts results first by DNS name with the labels reversed, for -// example: -// -// com.example.www. -// -// Note the trailing dot, which can change the sort order in some circumstances. -// -// When multiple records have the same DNS name, the action sorts results by -// the record type. -// -// You can use the name and type elements to adjust the beginning position of -// the list of resource record sets returned: -// -// If you do not specify Name or TypeThe results begin with the first resource -// record set that the hosted zone contains. -// -// If you specify Name but not TypeThe results begin with the first resource -// record set in the list whose name is greater than or equal to Name. -// -// If you specify Type but not NameAmazon Route 53 returns the InvalidInput -// error. -// -// If you specify both Name and TypeThe results begin with the first resource -// record set in the list whose name is greater than or equal to Name, and whose -// type is greater than or equal to Type. -// -// This action returns the most current version of the records. This includes -// records that are PENDING, and that are not yet available on all Amazon Route -// 53 DNS servers. -// -// To ensure that you get an accurate listing of the resource record sets for -// a hosted zone at a point in time, do not submit a ChangeResourceRecordSets -// request while you're paging through the results of a ListResourceRecordSets -// request. If you do, some pages may display results without the latest changes -// while other pages display results with the latest changes. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListResourceRecordSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListResourceRecordSets -func (c *Route53) ListResourceRecordSets(input *ListResourceRecordSetsInput) (*ListResourceRecordSetsOutput, error) { - req, out := c.ListResourceRecordSetsRequest(input) - return out, req.Send() -} - -// ListResourceRecordSetsWithContext is the same as ListResourceRecordSets with the addition of -// the ability to pass a context and additional request options. -// -// See ListResourceRecordSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListResourceRecordSetsWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, opts ...request.Option) (*ListResourceRecordSetsOutput, error) { - req, out := c.ListResourceRecordSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// ListResourceRecordSetsPages iterates over the pages of a ListResourceRecordSets operation, -// calling the "fn" function with the response data for each page. To stop -// iterating, return false from the fn function. -// -// See ListResourceRecordSets method for more information on how to use this operation. -// -// Note: This operation can generate multiple requests to a service. -// -// // Example iterating over at most 3 pages of a ListResourceRecordSets operation. -// pageNum := 0 -// err := client.ListResourceRecordSetsPages(params, -// func(page *ListResourceRecordSetsOutput, lastPage bool) bool { -// pageNum++ -// fmt.Println(page) -// return pageNum <= 3 -// }) -// -func (c *Route53) ListResourceRecordSetsPages(input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool) error { - return c.ListResourceRecordSetsPagesWithContext(aws.BackgroundContext(), input, fn) -} - -// ListResourceRecordSetsPagesWithContext same as ListResourceRecordSetsPages except -// it takes a Context and allows setting request options on the pages. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListResourceRecordSetsPagesWithContext(ctx aws.Context, input *ListResourceRecordSetsInput, fn func(*ListResourceRecordSetsOutput, bool) bool, opts ...request.Option) error { - p := request.Pagination{ - NewRequest: func() (*request.Request, error) { - var inCpy *ListResourceRecordSetsInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.ListResourceRecordSetsRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - - cont := true - for p.Next() && cont { - cont = fn(p.Page().(*ListResourceRecordSetsOutput), !p.HasNextPage()) - } - return p.Err() -} - -const opListReusableDelegationSets = "ListReusableDelegationSets" - -// ListReusableDelegationSetsRequest generates a "aws/request.Request" representing the -// client's request for the ListReusableDelegationSets operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListReusableDelegationSets for more information on using the ListReusableDelegationSets -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListReusableDelegationSetsRequest method. -// req, resp := client.ListReusableDelegationSetsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSets -func (c *Route53) ListReusableDelegationSetsRequest(input *ListReusableDelegationSetsInput) (req *request.Request, output *ListReusableDelegationSetsOutput) { - op := &request.Operation{ - Name: opListReusableDelegationSets, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/delegationset", - } - - if input == nil { - input = &ListReusableDelegationSetsInput{} - } - - output = &ListReusableDelegationSetsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListReusableDelegationSets API operation for Amazon Route 53. -// -// Retrieves a list of the reusable delegation sets that are associated with -// the current AWS account. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListReusableDelegationSets for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListReusableDelegationSets -func (c *Route53) ListReusableDelegationSets(input *ListReusableDelegationSetsInput) (*ListReusableDelegationSetsOutput, error) { - req, out := c.ListReusableDelegationSetsRequest(input) - return out, req.Send() -} - -// ListReusableDelegationSetsWithContext is the same as ListReusableDelegationSets with the addition of -// the ability to pass a context and additional request options. -// -// See ListReusableDelegationSets for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListReusableDelegationSetsWithContext(ctx aws.Context, input *ListReusableDelegationSetsInput, opts ...request.Option) (*ListReusableDelegationSetsOutput, error) { - req, out := c.ListReusableDelegationSetsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTagsForResource = "ListTagsForResource" - -// ListTagsForResourceRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResource operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsForResource for more information on using the ListTagsForResource -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTagsForResourceRequest method. -// req, resp := client.ListTagsForResourceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResource -func (c *Route53) ListTagsForResourceRequest(input *ListTagsForResourceInput) (req *request.Request, output *ListTagsForResourceOutput) { - op := &request.Operation{ - Name: opListTagsForResource, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/tags/{ResourceType}/{ResourceId}", - } - - if input == nil { - input = &ListTagsForResourceInput{} - } - - output = &ListTagsForResourceOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsForResource API operation for Amazon Route 53. -// -// Lists tags for one health check or hosted zone. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTagsForResource for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResource -func (c *Route53) ListTagsForResource(input *ListTagsForResourceInput) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - return out, req.Send() -} - -// ListTagsForResourceWithContext is the same as ListTagsForResource with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsForResource for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTagsForResourceWithContext(ctx aws.Context, input *ListTagsForResourceInput, opts ...request.Option) (*ListTagsForResourceOutput, error) { - req, out := c.ListTagsForResourceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTagsForResources = "ListTagsForResources" - -// ListTagsForResourcesRequest generates a "aws/request.Request" representing the -// client's request for the ListTagsForResources operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTagsForResources for more information on using the ListTagsForResources -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTagsForResourcesRequest method. -// req, resp := client.ListTagsForResourcesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResources -func (c *Route53) ListTagsForResourcesRequest(input *ListTagsForResourcesInput) (req *request.Request, output *ListTagsForResourcesOutput) { - op := &request.Operation{ - Name: opListTagsForResources, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/tags/{ResourceType}", - } - - if input == nil { - input = &ListTagsForResourcesInput{} - } - - output = &ListTagsForResourcesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTagsForResources API operation for Amazon Route 53. -// -// Lists tags for up to 10 health checks or hosted zones. -// -// For information about using tags for cost allocation, see Using Cost Allocation -// Tags (http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html) -// in the AWS Billing and Cost Management User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTagsForResources for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeThrottlingException "ThrottlingException" -// The limit on the number of requests per second was exceeded. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTagsForResources -func (c *Route53) ListTagsForResources(input *ListTagsForResourcesInput) (*ListTagsForResourcesOutput, error) { - req, out := c.ListTagsForResourcesRequest(input) - return out, req.Send() -} - -// ListTagsForResourcesWithContext is the same as ListTagsForResources with the addition of -// the ability to pass a context and additional request options. -// -// See ListTagsForResources for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTagsForResourcesWithContext(ctx aws.Context, input *ListTagsForResourcesInput, opts ...request.Option) (*ListTagsForResourcesOutput, error) { - req, out := c.ListTagsForResourcesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicies = "ListTrafficPolicies" - -// ListTrafficPoliciesRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicies operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicies for more information on using the ListTrafficPolicies -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPoliciesRequest method. -// req, resp := client.ListTrafficPoliciesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicies -func (c *Route53) ListTrafficPoliciesRequest(input *ListTrafficPoliciesInput) (req *request.Request, output *ListTrafficPoliciesOutput) { - op := &request.Operation{ - Name: opListTrafficPolicies, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicies", - } - - if input == nil { - input = &ListTrafficPoliciesInput{} - } - - output = &ListTrafficPoliciesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicies API operation for Amazon Route 53. -// -// Gets information about the latest version for every traffic policy that is -// associated with the current AWS account. Policies are listed in the order -// in which they were created. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicies for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicies -func (c *Route53) ListTrafficPolicies(input *ListTrafficPoliciesInput) (*ListTrafficPoliciesOutput, error) { - req, out := c.ListTrafficPoliciesRequest(input) - return out, req.Send() -} - -// ListTrafficPoliciesWithContext is the same as ListTrafficPolicies with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicies for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPoliciesWithContext(ctx aws.Context, input *ListTrafficPoliciesInput, opts ...request.Option) (*ListTrafficPoliciesOutput, error) { - req, out := c.ListTrafficPoliciesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstances = "ListTrafficPolicyInstances" - -// ListTrafficPolicyInstancesRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstances operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstances for more information on using the ListTrafficPolicyInstances -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesRequest method. -// req, resp := client.ListTrafficPolicyInstancesRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstances -func (c *Route53) ListTrafficPolicyInstancesRequest(input *ListTrafficPolicyInstancesInput) (req *request.Request, output *ListTrafficPolicyInstancesOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstances, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances", - } - - if input == nil { - input = &ListTrafficPolicyInstancesInput{} - } - - output = &ListTrafficPolicyInstancesOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstances API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created by using -// the current AWS account. -// -// After you submit an UpdateTrafficPolicyInstance request, there's a brief -// delay while Amazon Route 53 creates the resource record sets that are specified -// in the traffic policy definition. For more information, see the State response -// element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstances for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstances -func (c *Route53) ListTrafficPolicyInstances(input *ListTrafficPolicyInstancesInput) (*ListTrafficPolicyInstancesOutput, error) { - req, out := c.ListTrafficPolicyInstancesRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesWithContext is the same as ListTrafficPolicyInstances with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstances for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesInput, opts ...request.Option) (*ListTrafficPolicyInstancesOutput, error) { - req, out := c.ListTrafficPolicyInstancesRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstancesByHostedZone = "ListTrafficPolicyInstancesByHostedZone" - -// ListTrafficPolicyInstancesByHostedZoneRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstancesByHostedZone operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstancesByHostedZone for more information on using the ListTrafficPolicyInstancesByHostedZone -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesByHostedZoneRequest method. -// req, resp := client.ListTrafficPolicyInstancesByHostedZoneRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByHostedZone -func (c *Route53) ListTrafficPolicyInstancesByHostedZoneRequest(input *ListTrafficPolicyInstancesByHostedZoneInput) (req *request.Request, output *ListTrafficPolicyInstancesByHostedZoneOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstancesByHostedZone, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances/hostedzone", - } - - if input == nil { - input = &ListTrafficPolicyInstancesByHostedZoneInput{} - } - - output = &ListTrafficPolicyInstancesByHostedZoneOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstancesByHostedZone API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created in a -// specified hosted zone. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstancesByHostedZone for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByHostedZone -func (c *Route53) ListTrafficPolicyInstancesByHostedZone(input *ListTrafficPolicyInstancesByHostedZoneInput) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { - req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesByHostedZoneWithContext is the same as ListTrafficPolicyInstancesByHostedZone with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstancesByHostedZone for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesByHostedZoneWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByHostedZoneInput, opts ...request.Option) (*ListTrafficPolicyInstancesByHostedZoneOutput, error) { - req, out := c.ListTrafficPolicyInstancesByHostedZoneRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyInstancesByPolicy = "ListTrafficPolicyInstancesByPolicy" - -// ListTrafficPolicyInstancesByPolicyRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyInstancesByPolicy operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyInstancesByPolicy for more information on using the ListTrafficPolicyInstancesByPolicy -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyInstancesByPolicyRequest method. -// req, resp := client.ListTrafficPolicyInstancesByPolicyRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByPolicy -func (c *Route53) ListTrafficPolicyInstancesByPolicyRequest(input *ListTrafficPolicyInstancesByPolicyInput) (req *request.Request, output *ListTrafficPolicyInstancesByPolicyOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyInstancesByPolicy, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicyinstances/trafficpolicy", - } - - if input == nil { - input = &ListTrafficPolicyInstancesByPolicyInput{} - } - - output = &ListTrafficPolicyInstancesByPolicyOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyInstancesByPolicy API operation for Amazon Route 53. -// -// Gets information about the traffic policy instances that you created by using -// a specify traffic policy version. -// -// After you submit a CreateTrafficPolicyInstance or an UpdateTrafficPolicyInstance -// request, there's a brief delay while Amazon Route 53 creates the resource -// record sets that are specified in the traffic policy definition. For more -// information, see the State response element. -// -// Amazon Route 53 returns a maximum of 100 items in each response. If you have -// a lot of traffic policy instances, you can use the MaxItems parameter to -// list them in groups of up to 100. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyInstancesByPolicy for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyInstancesByPolicy -func (c *Route53) ListTrafficPolicyInstancesByPolicy(input *ListTrafficPolicyInstancesByPolicyInput) (*ListTrafficPolicyInstancesByPolicyOutput, error) { - req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyInstancesByPolicyWithContext is the same as ListTrafficPolicyInstancesByPolicy with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyInstancesByPolicy for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyInstancesByPolicyWithContext(ctx aws.Context, input *ListTrafficPolicyInstancesByPolicyInput, opts ...request.Option) (*ListTrafficPolicyInstancesByPolicyOutput, error) { - req, out := c.ListTrafficPolicyInstancesByPolicyRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListTrafficPolicyVersions = "ListTrafficPolicyVersions" - -// ListTrafficPolicyVersionsRequest generates a "aws/request.Request" representing the -// client's request for the ListTrafficPolicyVersions operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListTrafficPolicyVersions for more information on using the ListTrafficPolicyVersions -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListTrafficPolicyVersionsRequest method. -// req, resp := client.ListTrafficPolicyVersionsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyVersions -func (c *Route53) ListTrafficPolicyVersionsRequest(input *ListTrafficPolicyVersionsInput) (req *request.Request, output *ListTrafficPolicyVersionsOutput) { - op := &request.Operation{ - Name: opListTrafficPolicyVersions, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/trafficpolicies/{Id}/versions", - } - - if input == nil { - input = &ListTrafficPolicyVersionsInput{} - } - - output = &ListTrafficPolicyVersionsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListTrafficPolicyVersions API operation for Amazon Route 53. -// -// Gets information about all of the versions for a specified traffic policy. -// -// Traffic policy versions are listed in numerical order by VersionNumber. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListTrafficPolicyVersions for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListTrafficPolicyVersions -func (c *Route53) ListTrafficPolicyVersions(input *ListTrafficPolicyVersionsInput) (*ListTrafficPolicyVersionsOutput, error) { - req, out := c.ListTrafficPolicyVersionsRequest(input) - return out, req.Send() -} - -// ListTrafficPolicyVersionsWithContext is the same as ListTrafficPolicyVersions with the addition of -// the ability to pass a context and additional request options. -// -// See ListTrafficPolicyVersions for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListTrafficPolicyVersionsWithContext(ctx aws.Context, input *ListTrafficPolicyVersionsInput, opts ...request.Option) (*ListTrafficPolicyVersionsOutput, error) { - req, out := c.ListTrafficPolicyVersionsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opListVPCAssociationAuthorizations = "ListVPCAssociationAuthorizations" - -// ListVPCAssociationAuthorizationsRequest generates a "aws/request.Request" representing the -// client's request for the ListVPCAssociationAuthorizations operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See ListVPCAssociationAuthorizations for more information on using the ListVPCAssociationAuthorizations -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the ListVPCAssociationAuthorizationsRequest method. -// req, resp := client.ListVPCAssociationAuthorizationsRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations -func (c *Route53) ListVPCAssociationAuthorizationsRequest(input *ListVPCAssociationAuthorizationsInput) (req *request.Request, output *ListVPCAssociationAuthorizationsOutput) { - op := &request.Operation{ - Name: opListVPCAssociationAuthorizations, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/hostedzone/{Id}/authorizevpcassociation", - } - - if input == nil { - input = &ListVPCAssociationAuthorizationsInput{} - } - - output = &ListVPCAssociationAuthorizationsOutput{} - req = c.newRequest(op, input, output) - return -} - -// ListVPCAssociationAuthorizations API operation for Amazon Route 53. -// -// Gets a list of the VPCs that were created by other accounts and that can -// be associated with a specified hosted zone because you've submitted one or -// more CreateVPCAssociationAuthorization requests. -// -// The response includes a VPCs element with a VPC child element for each VPC -// that can be associated with the hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation ListVPCAssociationAuthorizations for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeInvalidPaginationToken "InvalidPaginationToken" -// The value that you specified to get the second or subsequent page of results -// is invalid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/ListVPCAssociationAuthorizations -func (c *Route53) ListVPCAssociationAuthorizations(input *ListVPCAssociationAuthorizationsInput) (*ListVPCAssociationAuthorizationsOutput, error) { - req, out := c.ListVPCAssociationAuthorizationsRequest(input) - return out, req.Send() -} - -// ListVPCAssociationAuthorizationsWithContext is the same as ListVPCAssociationAuthorizations with the addition of -// the ability to pass a context and additional request options. -// -// See ListVPCAssociationAuthorizations for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) ListVPCAssociationAuthorizationsWithContext(ctx aws.Context, input *ListVPCAssociationAuthorizationsInput, opts ...request.Option) (*ListVPCAssociationAuthorizationsOutput, error) { - req, out := c.ListVPCAssociationAuthorizationsRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opTestDNSAnswer = "TestDNSAnswer" - -// TestDNSAnswerRequest generates a "aws/request.Request" representing the -// client's request for the TestDNSAnswer operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See TestDNSAnswer for more information on using the TestDNSAnswer -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the TestDNSAnswerRequest method. -// req, resp := client.TestDNSAnswerRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswer -func (c *Route53) TestDNSAnswerRequest(input *TestDNSAnswerInput) (req *request.Request, output *TestDNSAnswerOutput) { - op := &request.Operation{ - Name: opTestDNSAnswer, - HTTPMethod: "GET", - HTTPPath: "/2013-04-01/testdnsanswer", - } - - if input == nil { - input = &TestDNSAnswerInput{} - } - - output = &TestDNSAnswerOutput{} - req = c.newRequest(op, input, output) - return -} - -// TestDNSAnswer API operation for Amazon Route 53. -// -// Gets the value that Amazon Route 53 returns in response to a DNS request -// for a specified record name and type. You can optionally specify the IP address -// of a DNS resolver, an EDNS0 client subnet IP address, and a subnet mask. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation TestDNSAnswer for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/TestDNSAnswer -func (c *Route53) TestDNSAnswer(input *TestDNSAnswerInput) (*TestDNSAnswerOutput, error) { - req, out := c.TestDNSAnswerRequest(input) - return out, req.Send() -} - -// TestDNSAnswerWithContext is the same as TestDNSAnswer with the addition of -// the ability to pass a context and additional request options. -// -// See TestDNSAnswer for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) TestDNSAnswerWithContext(ctx aws.Context, input *TestDNSAnswerInput, opts ...request.Option) (*TestDNSAnswerOutput, error) { - req, out := c.TestDNSAnswerRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateHealthCheck = "UpdateHealthCheck" - -// UpdateHealthCheckRequest generates a "aws/request.Request" representing the -// client's request for the UpdateHealthCheck operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateHealthCheck for more information on using the UpdateHealthCheck -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateHealthCheckRequest method. -// req, resp := client.UpdateHealthCheckRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheck -func (c *Route53) UpdateHealthCheckRequest(input *UpdateHealthCheckInput) (req *request.Request, output *UpdateHealthCheckOutput) { - op := &request.Operation{ - Name: opUpdateHealthCheck, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/healthcheck/{HealthCheckId}", - } - - if input == nil { - input = &UpdateHealthCheckInput{} - } - - output = &UpdateHealthCheckOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateHealthCheck API operation for Amazon Route 53. -// -// Updates an existing health check. Note that some values can't be updated. -// -// For more information about updating health checks, see Creating, Updating, -// and Deleting Health Checks (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-deleting.html) -// in the Amazon Route 53 Developer Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateHealthCheck for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHealthCheck "NoSuchHealthCheck" -// No health check exists with the ID that you specified in the DeleteHealthCheck -// request. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeHealthCheckVersionMismatch "HealthCheckVersionMismatch" -// The value of HealthCheckVersion in the request doesn't match the value of -// HealthCheckVersion in the health check. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHealthCheck -func (c *Route53) UpdateHealthCheck(input *UpdateHealthCheckInput) (*UpdateHealthCheckOutput, error) { - req, out := c.UpdateHealthCheckRequest(input) - return out, req.Send() -} - -// UpdateHealthCheckWithContext is the same as UpdateHealthCheck with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateHealthCheck for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateHealthCheckWithContext(ctx aws.Context, input *UpdateHealthCheckInput, opts ...request.Option) (*UpdateHealthCheckOutput, error) { - req, out := c.UpdateHealthCheckRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateHostedZoneComment = "UpdateHostedZoneComment" - -// UpdateHostedZoneCommentRequest generates a "aws/request.Request" representing the -// client's request for the UpdateHostedZoneComment operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateHostedZoneComment for more information on using the UpdateHostedZoneComment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateHostedZoneCommentRequest method. -// req, resp := client.UpdateHostedZoneCommentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneComment -func (c *Route53) UpdateHostedZoneCommentRequest(input *UpdateHostedZoneCommentInput) (req *request.Request, output *UpdateHostedZoneCommentOutput) { - op := &request.Operation{ - Name: opUpdateHostedZoneComment, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/hostedzone/{Id}", - } - - if input == nil { - input = &UpdateHostedZoneCommentInput{} - } - - output = &UpdateHostedZoneCommentOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateHostedZoneComment API operation for Amazon Route 53. -// -// Updates the comment for a specified hosted zone. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateHostedZoneComment for usage and error information. -// -// Returned Error Codes: -// * ErrCodeNoSuchHostedZone "NoSuchHostedZone" -// No hosted zone exists with the ID that you specified. -// -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateHostedZoneComment -func (c *Route53) UpdateHostedZoneComment(input *UpdateHostedZoneCommentInput) (*UpdateHostedZoneCommentOutput, error) { - req, out := c.UpdateHostedZoneCommentRequest(input) - return out, req.Send() -} - -// UpdateHostedZoneCommentWithContext is the same as UpdateHostedZoneComment with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateHostedZoneComment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateHostedZoneCommentWithContext(ctx aws.Context, input *UpdateHostedZoneCommentInput, opts ...request.Option) (*UpdateHostedZoneCommentOutput, error) { - req, out := c.UpdateHostedZoneCommentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateTrafficPolicyComment = "UpdateTrafficPolicyComment" - -// UpdateTrafficPolicyCommentRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTrafficPolicyComment operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateTrafficPolicyComment for more information on using the UpdateTrafficPolicyComment -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateTrafficPolicyCommentRequest method. -// req, resp := client.UpdateTrafficPolicyCommentRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyComment -func (c *Route53) UpdateTrafficPolicyCommentRequest(input *UpdateTrafficPolicyCommentInput) (req *request.Request, output *UpdateTrafficPolicyCommentOutput) { - op := &request.Operation{ - Name: opUpdateTrafficPolicyComment, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicy/{Id}/{Version}", - } - - if input == nil { - input = &UpdateTrafficPolicyCommentInput{} - } - - output = &UpdateTrafficPolicyCommentOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateTrafficPolicyComment API operation for Amazon Route 53. -// -// Updates the comment for a specified traffic policy version. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateTrafficPolicyComment for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeConcurrentModification "ConcurrentModification" -// Another user submitted a request to create, update, or delete the object -// at the same time that you did. Retry the request. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyComment -func (c *Route53) UpdateTrafficPolicyComment(input *UpdateTrafficPolicyCommentInput) (*UpdateTrafficPolicyCommentOutput, error) { - req, out := c.UpdateTrafficPolicyCommentRequest(input) - return out, req.Send() -} - -// UpdateTrafficPolicyCommentWithContext is the same as UpdateTrafficPolicyComment with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateTrafficPolicyComment for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateTrafficPolicyCommentWithContext(ctx aws.Context, input *UpdateTrafficPolicyCommentInput, opts ...request.Option) (*UpdateTrafficPolicyCommentOutput, error) { - req, out := c.UpdateTrafficPolicyCommentRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opUpdateTrafficPolicyInstance = "UpdateTrafficPolicyInstance" - -// UpdateTrafficPolicyInstanceRequest generates a "aws/request.Request" representing the -// client's request for the UpdateTrafficPolicyInstance operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See UpdateTrafficPolicyInstance for more information on using the UpdateTrafficPolicyInstance -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the UpdateTrafficPolicyInstanceRequest method. -// req, resp := client.UpdateTrafficPolicyInstanceRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyInstance -func (c *Route53) UpdateTrafficPolicyInstanceRequest(input *UpdateTrafficPolicyInstanceInput) (req *request.Request, output *UpdateTrafficPolicyInstanceOutput) { - op := &request.Operation{ - Name: opUpdateTrafficPolicyInstance, - HTTPMethod: "POST", - HTTPPath: "/2013-04-01/trafficpolicyinstance/{Id}", - } - - if input == nil { - input = &UpdateTrafficPolicyInstanceInput{} - } - - output = &UpdateTrafficPolicyInstanceOutput{} - req = c.newRequest(op, input, output) - return -} - -// UpdateTrafficPolicyInstance API operation for Amazon Route 53. -// -// Updates the resource record sets in a specified hosted zone that were created -// based on the settings in a specified traffic policy version. -// -// When you update a traffic policy instance, Amazon Route 53 continues to respond -// to DNS queries for the root resource record set name (such as example.com) -// while it replaces one group of resource record sets with another. Amazon -// Route 53 performs the following operations: -// -// Amazon Route 53 creates a new group of resource record sets based on the -// specified traffic policy. This is true regardless of how significant the -// differences are between the existing resource record sets and the new resource -// record sets. -// -// When all of the new resource record sets have been created, Amazon Route -// 53 starts to respond to DNS queries for the root resource record set name -// (such as example.com) by using the new resource record sets. -// -// Amazon Route 53 deletes the old group of resource record sets that are associated -// with the root resource record set name. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for Amazon Route 53's -// API operation UpdateTrafficPolicyInstance for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidInput "InvalidInput" -// The input is not valid. -// -// * ErrCodeNoSuchTrafficPolicy "NoSuchTrafficPolicy" -// No traffic policy exists with the specified ID. -// -// * ErrCodeNoSuchTrafficPolicyInstance "NoSuchTrafficPolicyInstance" -// No traffic policy instance exists with the specified ID. -// -// * ErrCodePriorRequestNotComplete "PriorRequestNotComplete" -// If Amazon Route 53 can't process a request before the next request arrives, -// it will reject subsequent requests for the same hosted zone and return an -// HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly -// for the same request, we recommend that you wait, in intervals of increasing -// duration, before you try the request again. -// -// * ErrCodeConflictingTypes "ConflictingTypes" -// You tried to update a traffic policy instance by using a traffic policy version -// that has a different DNS type than the current type for the instance. You -// specified the type in the JSON document in the CreateTrafficPolicy or CreateTrafficPolicyVersionrequest. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01/UpdateTrafficPolicyInstance -func (c *Route53) UpdateTrafficPolicyInstance(input *UpdateTrafficPolicyInstanceInput) (*UpdateTrafficPolicyInstanceOutput, error) { - req, out := c.UpdateTrafficPolicyInstanceRequest(input) - return out, req.Send() -} - -// UpdateTrafficPolicyInstanceWithContext is the same as UpdateTrafficPolicyInstance with the addition of -// the ability to pass a context and additional request options. -// -// See UpdateTrafficPolicyInstance for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) UpdateTrafficPolicyInstanceWithContext(ctx aws.Context, input *UpdateTrafficPolicyInstanceInput, opts ...request.Option) (*UpdateTrafficPolicyInstanceOutput, error) { - req, out := c.UpdateTrafficPolicyInstanceRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type AccountLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested. Valid values include the following: - // - // * MAX_HEALTH_CHECKS_BY_OWNER: The maximum number of health checks that - // you can create using the current account. - // - // * MAX_HOSTED_ZONES_BY_OWNER: The maximum number of hosted zones that you - // can create using the current account. - // - // * MAX_REUSABLE_DELEGATION_SETS_BY_OWNER: The maximum number of reusable - // delegation sets that you can create using the current account. - // - // * MAX_TRAFFIC_POLICIES_BY_OWNER: The maximum number of traffic policies - // that you can create using the current account. - // - // * MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER: The maximum number of traffic - // policy instances that you can create using the current account. (Traffic - // policy instances are referred to as traffic flow policy records in the - // Amazon Route 53 console.) - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"AccountLimitType"` - - // The current value for the limit that is specified by AccountLimit$Type. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s AccountLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AccountLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *AccountLimit) SetType(v string) *AccountLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *AccountLimit) SetValue(v int64) *AccountLimit { - s.Value = &v - return s -} - -// A complex type that identifies the CloudWatch alarm that you want Amazon -// Route 53 health checkers to use to determine whether this health check is -// healthy. -type AlarmIdentifier struct { - _ struct{} `type:"structure"` - - // The name of the CloudWatch alarm that you want Amazon Route 53 health checkers - // to use to determine whether this health check is healthy. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - // - // For the current list of CloudWatch regions, see Amazon CloudWatch (http://docs.aws.amazon.com/general/latest/gr/rande.html#cw_region) - // in the AWS Regions and Endpoints chapter of the Amazon Web Services General - // Reference. - // - // Region is a required field - Region *string `min:"1" type:"string" required:"true" enum:"CloudWatchRegion"` -} - -// String returns the string representation -func (s AlarmIdentifier) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AlarmIdentifier) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AlarmIdentifier) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AlarmIdentifier"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Name", 1)) - } - if s.Region == nil { - invalidParams.Add(request.NewErrParamRequired("Region")) - } - if s.Region != nil && len(*s.Region) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Region", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetName sets the Name field's value. -func (s *AlarmIdentifier) SetName(v string) *AlarmIdentifier { - s.Name = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *AlarmIdentifier) SetRegion(v string) *AlarmIdentifier { - s.Region = &v - return s -} - -// Alias resource record sets only: Information about the CloudFront distribution, -// Elastic Beanstalk environment, ELB load balancer, Amazon S3 bucket, or Amazon -// Route 53 resource record set that you're redirecting queries to. An Elastic -// Beanstalk environment must have a regionalized subdomain. -// -// When creating resource record sets for a private hosted zone, note the following: -// -// * Resource record sets can't be created for CloudFront distributions in -// a private hosted zone. -// -// * Creating geolocation alias resource record sets or latency alias resource -// record sets in a private hosted zone is unsupported. -// -// * For information about creating failover resource record sets in a private -// hosted zone, see Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html). -type AliasTarget struct { - _ struct{} `type:"structure"` - - // Alias resource record sets only: The value that you specify depends on where - // you want to route queries: - // - // CloudFront distributionSpecify the domain name that CloudFront assigned when - // you created your distribution. - // - // Your CloudFront distribution must include an alternate domain name that matches - // the name of the resource record set. For example, if the name of the resource - // record set is acme.example.com, your CloudFront distribution must include - // acme.example.com as one of the alternate domain names. For more information, - // see Using Alternate Domain Names (CNAMEs) (http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html) - // in the Amazon CloudFront Developer Guide. - // - // Elastic Beanstalk environmentSpecify the CNAME attribute for the environment. - // (The environment must have a regionalized domain name.) You can use the following - // methods to get the value of the CNAME attribute: - // - // AWS Management Console: For information about how to get the value by using - // the console, see Using Custom Domains with AWS Elastic Beanstalk (http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customdomains.html) - // in the AWS Elastic Beanstalk Developer Guide. - // - // Elastic Beanstalk API: Use the DescribeEnvironments action to get the value - // of the CNAME attribute. For more information, see DescribeEnvironments (http://docs.aws.amazon.com/elasticbeanstalk/latest/api/API_DescribeEnvironments.html) - // in the AWS Elastic Beanstalk API Reference. - // - // AWS CLI: Use the describe-environments command to get the value of the CNAME - // attribute. For more information, see describe-environments (http://docs.aws.amazon.com/cli/latest/reference/elasticbeanstalk/describe-environments.html) - // in the AWS Command Line Interface Reference. - // - // ELB load balancerSpecify the DNS name that is associated with the load balancer. - // Get the DNS name by using the AWS Management Console, the ELB API, or the - // AWS CLI. - // - // AWS Management Console: Go to the EC2 page, choose Load Balancers in the - // navigation pane, choose the load balancer, choose the Description tab, and - // get the value of the DNS name field. (If you're routing traffic to a Classic - // Load Balancer, get the value that begins with dualstack.) - // - // Elastic Load Balancing API: Use DescribeLoadBalancers to get the value of - // DNSName. For more information, see the applicable guide: - // - // Classic Load Balancers: DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancers.html) - // - // Application and Network Load Balancers: DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) - // - // AWS CLI: Use describe-load-balancers to get the value of DNSName. For more - // information, see the applicable guide: - // - // Classic Load Balancers: describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html) - // - // Application and Network Load Balancers: describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-load-balancers.html) - // - // Amazon S3 bucket that is configured as a static websiteSpecify the domain - // name of the Amazon S3 website endpoint in which you created the bucket, for - // example, s3-website-us-east-2.amazonaws.com. For more information about valid - // values, see the table Amazon Simple Storage Service (S3) Website Endpoints - // (http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) in the - // Amazon Web Services General Reference. For more information about using S3 - // buckets for websites, see Getting Started with Amazon Route 53 (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/getting-started.html) - // in the Amazon Route 53 Developer Guide. - // - // Another Amazon Route 53 resource record setSpecify the value of the Name - // element for a resource record set in the current hosted zone. - // - // DNSName is a required field - DNSName *string `type:"string" required:"true"` - - // Applies only to alias, failover alias, geolocation alias, latency alias, - // and weighted alias resource record sets: When EvaluateTargetHealth is true, - // an alias resource record set inherits the health of the referenced AWS resource, - // such as an ELB load balancer, or the referenced resource record set. - // - // Note the following: - // - // * You can't set EvaluateTargetHealth to true when the alias target is - // a CloudFront distribution. - // - // * If the AWS resource that you specify in AliasTarget is a resource record - // set or a group of resource record sets (for example, a group of weighted - // resource record sets), but it is not another alias resource record set, - // we recommend that you associate a health check with all of the resource - // record sets in the alias target. For more information, see What Happens - // When You Omit Health Checks? (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html#dns-failover-complex-configs-hc-omitting) - // in the Amazon Route 53 Developer Guide. - // - // * If you specify an Elastic Beanstalk environment in HostedZoneId and - // DNSName, and if the environment contains an ELB load balancer, Elastic - // Load Balancing routes queries only to the healthy Amazon EC2 instances - // that are registered with the load balancer. (An environment automatically - // contains an ELB load balancer if it includes more than one EC2 instance.) - // If you set EvaluateTargetHealth to true and either no EC2 instances are - // healthy or the load balancer itself is unhealthy, Amazon Route 53 routes - // queries to other available resources that are healthy, if any. - // - // If the environment contains a single EC2 instance, there are no special requirements. - // - // * If you specify an ELB load balancer in AliasTarget, ELB routes queries - // only to the healthy EC2 instances that are registered with the load balancer. - // If no EC2 instances are healthy or if the load balancer itself is unhealthy, - // and if EvaluateTargetHealth is true for the corresponding alias resource - // record set, Amazon Route 53 routes queries to other resources. When you - // create a load balancer, you configure settings for ELB health checks; - // they're not Amazon Route 53 health checks, but they perform a similar - // function. Do not create Amazon Route 53 health checks for the EC2 instances - // that you register with an ELB load balancer. - // - // For more information, see How Health Checks Work in More Complex Amazon Route - // 53 Configurations (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-complex-configs.html) - // in the Amazon Route 53 Developer Guide. - // - // * We recommend that you set EvaluateTargetHealth to true only when you - // have enough idle capacity to handle the failure of one or more endpoints. - // - // For more information and examples, see Amazon Route 53 Health Checks and - // DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // in the Amazon Route 53 Developer Guide. - // - // EvaluateTargetHealth is a required field - EvaluateTargetHealth *bool `type:"boolean" required:"true"` - - // Alias resource records sets only: The value used depends on where you want - // to route traffic: - // - // CloudFront distributionSpecify Z2FDTNDATAQYW2. - // - // Alias resource record sets for CloudFront can't be created in a private zone. - // - // Elastic Beanstalk environmentSpecify the hosted zone ID for the region in - // which you created the environment. The environment must have a regionalized - // subdomain. For a list of regions and the corresponding hosted zone IDs, see - // AWS Elastic Beanstalk (http://docs.aws.amazon.com/general/latest/gr/rande.html#elasticbeanstalk_region) - // in the "AWS Regions and Endpoints" chapter of the Amazon Web Services General - // Reference. - // - // ELB load balancerSpecify the value of the hosted zone ID for the load balancer. - // Use the following methods to get the hosted zone ID: - // - // Elastic Load Balancing (http://docs.aws.amazon.com/general/latest/gr/rande.html#elb_region) - // table in the "AWS Regions and Endpoints" chapter of the Amazon Web Services - // General Reference: Use the value that corresponds with the region that you - // created your load balancer in. Note that there are separate columns for Application - // and Classic Load Balancers and for Network Load Balancers. - // - // AWS Management Console: Go to the Amazon EC2 page, choose Load Balancers - // in the navigation pane, select the load balancer, and get the value of the - // Hosted zone field on the Description tab. - // - // Elastic Load Balancing API: Use DescribeLoadBalancers to get the applicable - // value. For more information, see the applicable guide: - // - // Classic Load Balancers: Use DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DescribeLoadBalancers.html) - // to get the value of CanonicalHostedZoneNameId. - // - // Application and Network Load Balancers: Use DescribeLoadBalancers (http://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) - // to get the value of CanonicalHostedZoneId. - // - // AWS CLI: Use describe-load-balancers to get the applicable value. For more - // information, see the applicable guide: - // - // Classic Load Balancers: Use describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elb/describe-load-balancers.html) - // to get the value of CanonicalHostedZoneNameId. - // - // Application and Network Load Balancers: Use describe-load-balancers (http://docs.aws.amazon.com/cli/latest/reference/elbv2/describe-load-balancers.html) - // to get the value of CanonicalHostedZoneId. - // - // An Amazon S3 bucket configured as a static websiteSpecify the hosted zone - // ID for the region that you created the bucket in. For more information about - // valid values, see the Amazon Simple Storage Service Website Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region) - // table in the "AWS Regions and Endpoints" chapter of the Amazon Web Services - // General Reference. - // - // Another Amazon Route 53 resource record set in your hosted zoneSpecify the - // hosted zone ID of your hosted zone. (An alias resource record set can't reference - // a resource record set in a different hosted zone.) - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s AliasTarget) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AliasTarget) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AliasTarget) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AliasTarget"} - if s.DNSName == nil { - invalidParams.Add(request.NewErrParamRequired("DNSName")) - } - if s.EvaluateTargetHealth == nil { - invalidParams.Add(request.NewErrParamRequired("EvaluateTargetHealth")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDNSName sets the DNSName field's value. -func (s *AliasTarget) SetDNSName(v string) *AliasTarget { - s.DNSName = &v - return s -} - -// SetEvaluateTargetHealth sets the EvaluateTargetHealth field's value. -func (s *AliasTarget) SetEvaluateTargetHealth(v bool) *AliasTarget { - s.EvaluateTargetHealth = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *AliasTarget) SetHostedZoneId(v string) *AliasTarget { - s.HostedZoneId = &v - return s -} - -// A complex type that contains information about the request to associate a -// VPC with a private hosted zone. -type AssociateVPCWithHostedZoneInput struct { - _ struct{} `locationName:"AssociateVPCWithHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // Optional: A comment about the association request. - Comment *string `type:"string"` - - // The ID of the private hosted zone that you want to associate an Amazon VPC - // with. - // - // Note that you can't associate a VPC with a hosted zone that doesn't have - // an existing VPC association. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains information about the VPC that you want to associate - // with a private hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AssociateVPCWithHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssociateVPCWithHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssociateVPCWithHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssociateVPCWithHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *AssociateVPCWithHostedZoneInput) SetComment(v string) *AssociateVPCWithHostedZoneInput { - s.Comment = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *AssociateVPCWithHostedZoneInput) SetHostedZoneId(v string) *AssociateVPCWithHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *AssociateVPCWithHostedZoneInput) SetVPC(v *VPC) *AssociateVPCWithHostedZoneInput { - s.VPC = v - return s -} - -// A complex type that contains the response information for the AssociateVPCWithHostedZone -// request. -type AssociateVPCWithHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that describes the changes made to your hosted zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s AssociateVPCWithHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssociateVPCWithHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *AssociateVPCWithHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *AssociateVPCWithHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// The information for each resource record set that you want to change. -type Change struct { - _ struct{} `type:"structure"` - - // The action to perform: - // - // * CREATE: Creates a resource record set that has the specified values. - // - // * DELETE: Deletes a existing resource record set. - // - // To delete the resource record set that is associated with a traffic policy - // instance, use DeleteTrafficPolicyInstance. Amazon Route 53 will delete - // the resource record set automatically. If you delete the resource record - // set by using ChangeResourceRecordSets, Amazon Route 53 doesn't automatically - // delete the traffic policy instance, and you'll continue to be charged - // for it even though it's no longer in use. - // - // * UPSERT: If a resource record set doesn't already exist, Amazon Route - // 53 creates it. If a resource record set does exist, Amazon Route 53 updates - // it with the values in the request. - // - // Action is a required field - Action *string `type:"string" required:"true" enum:"ChangeAction"` - - // Information about the resource record set to create, delete, or update. - // - // ResourceRecordSet is a required field - ResourceRecordSet *ResourceRecordSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s Change) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Change) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *Change) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "Change"} - if s.Action == nil { - invalidParams.Add(request.NewErrParamRequired("Action")) - } - if s.ResourceRecordSet == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceRecordSet")) - } - if s.ResourceRecordSet != nil { - if err := s.ResourceRecordSet.Validate(); err != nil { - invalidParams.AddNested("ResourceRecordSet", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAction sets the Action field's value. -func (s *Change) SetAction(v string) *Change { - s.Action = &v - return s -} - -// SetResourceRecordSet sets the ResourceRecordSet field's value. -func (s *Change) SetResourceRecordSet(v *ResourceRecordSet) *Change { - s.ResourceRecordSet = v - return s -} - -// The information for a change request. -type ChangeBatch struct { - _ struct{} `type:"structure"` - - // Information about the changes to make to the record sets. - // - // Changes is a required field - Changes []*Change `locationNameList:"Change" min:"1" type:"list" required:"true"` - - // Optional: Any comments you want to include about a change batch request. - Comment *string `type:"string"` -} - -// String returns the string representation -func (s ChangeBatch) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeBatch) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeBatch) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeBatch"} - if s.Changes == nil { - invalidParams.Add(request.NewErrParamRequired("Changes")) - } - if s.Changes != nil && len(s.Changes) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Changes", 1)) - } - if s.Changes != nil { - for i, v := range s.Changes { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "Changes", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetChanges sets the Changes field's value. -func (s *ChangeBatch) SetChanges(v []*Change) *ChangeBatch { - s.Changes = v - return s -} - -// SetComment sets the Comment field's value. -func (s *ChangeBatch) SetComment(v string) *ChangeBatch { - s.Comment = &v - return s -} - -// A complex type that describes change information about changes made to your -// hosted zone. -type ChangeInfo struct { - _ struct{} `type:"structure"` - - // A complex type that describes change information about changes made to your - // hosted zone. - // - // This element contains an ID that you use when performing a GetChange action - // to get detailed information about the change. - Comment *string `type:"string"` - - // The ID of the request. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // The current state of the request. PENDING indicates that this request has - // not yet been applied to all Amazon Route 53 DNS servers. - // - // Status is a required field - Status *string `type:"string" required:"true" enum:"ChangeStatus"` - - // The date and time that the change request was submitted in ISO 8601 format - // (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal Time (UTC). - // For example, the value 2017-03-27T17:48:16.751Z represents March 27, 2017 - // at 17:48:16.751 UTC. - // - // SubmittedAt is a required field - SubmittedAt *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` -} - -// String returns the string representation -func (s ChangeInfo) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeInfo) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *ChangeInfo) SetComment(v string) *ChangeInfo { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *ChangeInfo) SetId(v string) *ChangeInfo { - s.Id = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *ChangeInfo) SetStatus(v string) *ChangeInfo { - s.Status = &v - return s -} - -// SetSubmittedAt sets the SubmittedAt field's value. -func (s *ChangeInfo) SetSubmittedAt(v time.Time) *ChangeInfo { - s.SubmittedAt = &v - return s -} - -// A complex type that contains change information for the resource record set. -type ChangeResourceRecordSetsInput struct { - _ struct{} `locationName:"ChangeResourceRecordSetsRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains an optional comment and the Changes element. - // - // ChangeBatch is a required field - ChangeBatch *ChangeBatch `type:"structure" required:"true"` - - // The ID of the hosted zone that contains the resource record sets that you - // want to change. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s ChangeResourceRecordSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeResourceRecordSetsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeResourceRecordSetsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeResourceRecordSetsInput"} - if s.ChangeBatch == nil { - invalidParams.Add(request.NewErrParamRequired("ChangeBatch")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.ChangeBatch != nil { - if err := s.ChangeBatch.Validate(); err != nil { - invalidParams.AddNested("ChangeBatch", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetChangeBatch sets the ChangeBatch field's value. -func (s *ChangeResourceRecordSetsInput) SetChangeBatch(v *ChangeBatch) *ChangeResourceRecordSetsInput { - s.ChangeBatch = v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ChangeResourceRecordSetsInput) SetHostedZoneId(v string) *ChangeResourceRecordSetsInput { - s.HostedZoneId = &v - return s -} - -// A complex type containing the response for the request. -type ChangeResourceRecordSetsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about changes made to your hosted - // zone. - // - // This element contains an ID that you use when performing a GetChange action - // to get detailed information about the change. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s ChangeResourceRecordSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeResourceRecordSetsOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *ChangeResourceRecordSetsOutput) SetChangeInfo(v *ChangeInfo) *ChangeResourceRecordSetsOutput { - s.ChangeInfo = v - return s -} - -// A complex type that contains information about the tags that you want to -// add, edit, or delete. -type ChangeTagsForResourceInput struct { - _ struct{} `locationName:"ChangeTagsForResourceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains a list of the tags that you want to add to the - // specified health check or hosted zone and/or the tags that you want to edit - // Value for. - // - // You can add a maximum of 10 tags to a health check or a hosted zone. - AddTags []*Tag `locationNameList:"Tag" min:"1" type:"list"` - - // A complex type that contains a list of the tags that you want to delete from - // the specified health check or hosted zone. You can specify up to 10 keys. - RemoveTagKeys []*string `locationNameList:"Key" min:"1" type:"list"` - - // The ID of the resource for which you want to add, change, or delete tags. - // - // ResourceId is a required field - ResourceId *string `location:"uri" locationName:"ResourceId" type:"string" required:"true"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ChangeTagsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeTagsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ChangeTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ChangeTagsForResourceInput"} - if s.AddTags != nil && len(s.AddTags) < 1 { - invalidParams.Add(request.NewErrParamMinLen("AddTags", 1)) - } - if s.RemoveTagKeys != nil && len(s.RemoveTagKeys) < 1 { - invalidParams.Add(request.NewErrParamMinLen("RemoveTagKeys", 1)) - } - if s.ResourceId == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceId")) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAddTags sets the AddTags field's value. -func (s *ChangeTagsForResourceInput) SetAddTags(v []*Tag) *ChangeTagsForResourceInput { - s.AddTags = v - return s -} - -// SetRemoveTagKeys sets the RemoveTagKeys field's value. -func (s *ChangeTagsForResourceInput) SetRemoveTagKeys(v []*string) *ChangeTagsForResourceInput { - s.RemoveTagKeys = v - return s -} - -// SetResourceId sets the ResourceId field's value. -func (s *ChangeTagsForResourceInput) SetResourceId(v string) *ChangeTagsForResourceInput { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ChangeTagsForResourceInput) SetResourceType(v string) *ChangeTagsForResourceInput { - s.ResourceType = &v - return s -} - -// Empty response for the request. -type ChangeTagsForResourceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s ChangeTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ChangeTagsForResourceOutput) GoString() string { - return s.String() -} - -// A complex type that contains information about the CloudWatch alarm that -// Amazon Route 53 is monitoring for this health check. -type CloudWatchAlarmConfiguration struct { - _ struct{} `type:"structure"` - - // For the metric that the CloudWatch alarm is associated with, the arithmetic - // operation that is used for the comparison. - // - // ComparisonOperator is a required field - ComparisonOperator *string `type:"string" required:"true" enum:"ComparisonOperator"` - - // For the metric that the CloudWatch alarm is associated with, a complex type - // that contains information about the dimensions for the metric. For information, - // see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html) - // in the Amazon CloudWatch User Guide. - Dimensions []*Dimension `locationNameList:"Dimension" type:"list"` - - // For the metric that the CloudWatch alarm is associated with, the number of - // periods that the metric is compared to the threshold. - // - // EvaluationPeriods is a required field - EvaluationPeriods *int64 `min:"1" type:"integer" required:"true"` - - // The name of the CloudWatch metric that the alarm is associated with. - // - // MetricName is a required field - MetricName *string `min:"1" type:"string" required:"true"` - - // The namespace of the metric that the alarm is associated with. For more information, - // see Amazon CloudWatch Namespaces, Dimensions, and Metrics Reference (http://docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/CW_Support_For_AWS.html) - // in the Amazon CloudWatch User Guide. - // - // Namespace is a required field - Namespace *string `min:"1" type:"string" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the duration - // of one evaluation period in seconds. - // - // Period is a required field - Period *int64 `min:"60" type:"integer" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the statistic - // that is applied to the metric. - // - // Statistic is a required field - Statistic *string `type:"string" required:"true" enum:"Statistic"` - - // For the metric that the CloudWatch alarm is associated with, the value the - // metric is compared with. - // - // Threshold is a required field - Threshold *float64 `type:"double" required:"true"` -} - -// String returns the string representation -func (s CloudWatchAlarmConfiguration) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CloudWatchAlarmConfiguration) GoString() string { - return s.String() -} - -// SetComparisonOperator sets the ComparisonOperator field's value. -func (s *CloudWatchAlarmConfiguration) SetComparisonOperator(v string) *CloudWatchAlarmConfiguration { - s.ComparisonOperator = &v - return s -} - -// SetDimensions sets the Dimensions field's value. -func (s *CloudWatchAlarmConfiguration) SetDimensions(v []*Dimension) *CloudWatchAlarmConfiguration { - s.Dimensions = v - return s -} - -// SetEvaluationPeriods sets the EvaluationPeriods field's value. -func (s *CloudWatchAlarmConfiguration) SetEvaluationPeriods(v int64) *CloudWatchAlarmConfiguration { - s.EvaluationPeriods = &v - return s -} - -// SetMetricName sets the MetricName field's value. -func (s *CloudWatchAlarmConfiguration) SetMetricName(v string) *CloudWatchAlarmConfiguration { - s.MetricName = &v - return s -} - -// SetNamespace sets the Namespace field's value. -func (s *CloudWatchAlarmConfiguration) SetNamespace(v string) *CloudWatchAlarmConfiguration { - s.Namespace = &v - return s -} - -// SetPeriod sets the Period field's value. -func (s *CloudWatchAlarmConfiguration) SetPeriod(v int64) *CloudWatchAlarmConfiguration { - s.Period = &v - return s -} - -// SetStatistic sets the Statistic field's value. -func (s *CloudWatchAlarmConfiguration) SetStatistic(v string) *CloudWatchAlarmConfiguration { - s.Statistic = &v - return s -} - -// SetThreshold sets the Threshold field's value. -func (s *CloudWatchAlarmConfiguration) SetThreshold(v float64) *CloudWatchAlarmConfiguration { - s.Threshold = &v - return s -} - -// A complex type that contains the health check request information. -type CreateHealthCheckInput struct { - _ struct{} `locationName:"CreateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request and that allows you to retry - // a failed CreateHealthCheck request without the risk of creating two identical - // health checks: - // - // * If you send a CreateHealthCheck request with the same CallerReference - // and settings as a previous request, and if the health check doesn't exist, - // Amazon Route 53 creates the health check. If the health check does exist, - // Amazon Route 53 returns the settings for the existing health check. - // - // * If you send a CreateHealthCheck request with the same CallerReference - // as a deleted health check, regardless of the settings, Amazon Route 53 - // returns a HealthCheckAlreadyExists error. - // - // * If you send a CreateHealthCheck request with the same CallerReference - // as an existing health check but with different settings, Amazon Route - // 53 returns a HealthCheckAlreadyExists error. - // - // * If you send a CreateHealthCheck request with a unique CallerReference - // but settings identical to an existing health check, Amazon Route 53 creates - // the health check. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that contains the response to a CreateHealthCheck request. - // - // HealthCheckConfig is a required field - HealthCheckConfig *HealthCheckConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateHealthCheckInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - if s.HealthCheckConfig == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckConfig")) - } - if s.HealthCheckConfig != nil { - if err := s.HealthCheckConfig.Validate(); err != nil { - invalidParams.AddNested("HealthCheckConfig", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateHealthCheckInput) SetCallerReference(v string) *CreateHealthCheckInput { - s.CallerReference = &v - return s -} - -// SetHealthCheckConfig sets the HealthCheckConfig field's value. -func (s *CreateHealthCheckInput) SetHealthCheckConfig(v *HealthCheckConfig) *CreateHealthCheckInput { - s.HealthCheckConfig = v - return s -} - -// A complex type containing the response information for the new health check. -type CreateHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains identifying information about the health check. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` - - // The unique URL representing the new health check. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *CreateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *CreateHealthCheckOutput { - s.HealthCheck = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateHealthCheckOutput) SetLocation(v string) *CreateHealthCheckOutput { - s.Location = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type CreateHostedZoneInput struct { - _ struct{} `locationName:"CreateHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request and that allows failed CreateHostedZone - // requests to be retried without the risk of executing the operation twice. - // You must use a unique CallerReference string every time you submit a CreateHostedZone - // request. CallerReference can be any unique string, for example, a date/time - // stamp. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // If you want to associate a reusable delegation set with this hosted zone, - // the ID that Amazon Route 53 assigned to the reusable delegation set when - // you created it. For more information about reusable delegation sets, see - // CreateReusableDelegationSet. - DelegationSetId *string `type:"string"` - - // (Optional) A complex type that contains the following optional values: - // - // * For public and private hosted zones, an optional comment - // - // * For private hosted zones, an optional PrivateZone element - // - // If you don't specify a comment or the PrivateZone element, omit HostedZoneConfig - // and the other elements. - HostedZoneConfig *HostedZoneConfig `type:"structure"` - - // The name of the domain. For resource record types that include a domain name, - // specify a fully qualified domain name, for example, www.example.com. The - // trailing dot is optional; Amazon Route 53 assumes that the domain name is - // fully qualified. This means that Amazon Route 53 treats www.example.com (without - // a trailing dot) and www.example.com. (with a trailing dot) as identical. - // - // If you're creating a public hosted zone, this is the name you have registered - // with your DNS registrar. If your domain name is registered with a registrar - // other than Amazon Route 53, change the name servers for your domain to the - // set of NameServers that CreateHostedZone returns in DelegationSet. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // (Private hosted zones only) A complex type that contains information about - // the Amazon VPC that you're associating with this hosted zone. - // - // You can specify only one Amazon VPC when you create a private hosted zone. - // To associate additional Amazon VPCs with the hosted zone, use AssociateVPCWithHostedZone - // after you create a hosted zone. - VPC *VPC `type:"structure"` -} - -// String returns the string representation -func (s CreateHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateHostedZoneInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateHostedZoneInput) SetCallerReference(v string) *CreateHostedZoneInput { - s.CallerReference = &v - return s -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *CreateHostedZoneInput) SetDelegationSetId(v string) *CreateHostedZoneInput { - s.DelegationSetId = &v - return s -} - -// SetHostedZoneConfig sets the HostedZoneConfig field's value. -func (s *CreateHostedZoneInput) SetHostedZoneConfig(v *HostedZoneConfig) *CreateHostedZoneInput { - s.HostedZoneConfig = v - return s -} - -// SetName sets the Name field's value. -func (s *CreateHostedZoneInput) SetName(v string) *CreateHostedZoneInput { - s.Name = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateHostedZoneInput) SetVPC(v *VPC) *CreateHostedZoneInput { - s.VPC = v - return s -} - -// A complex type containing the response information for the hosted zone. -type CreateHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the CreateHostedZone request. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` - - // A complex type that describes the name servers for this hosted zone. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` - - // The unique URL representing the new hosted zone. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains information about an Amazon VPC that you associated - // with this hosted zone. - VPC *VPC `type:"structure"` -} - -// String returns the string representation -func (s CreateHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *CreateHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *CreateHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *CreateHostedZoneOutput) SetDelegationSet(v *DelegationSet) *CreateHostedZoneOutput { - s.DelegationSet = v - return s -} - -// SetHostedZone sets the HostedZone field's value. -func (s *CreateHostedZoneOutput) SetHostedZone(v *HostedZone) *CreateHostedZoneOutput { - s.HostedZone = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateHostedZoneOutput) SetLocation(v string) *CreateHostedZoneOutput { - s.Location = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateHostedZoneOutput) SetVPC(v *VPC) *CreateHostedZoneOutput { - s.VPC = v - return s -} - -type CreateQueryLoggingConfigInput struct { - _ struct{} `locationName:"CreateQueryLoggingConfigRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The Amazon Resource Name (ARN) for the log group that you want to Amazon - // Route 53 to send query logs to. This is the format of the ARN: - // - // arn:aws:logs:region:account-id:log-group:log_group_name - // - // To get the ARN for a log group, you can use the CloudWatch console, the DescribeLogGroups - // (http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_DescribeLogGroups.html) - // API action, the describe-log-groups (http://docs.aws.amazon.com/cli/latest/reference/logs/describe-log-groups.html) - // command, or the applicable command in one of the AWS SDKs. - // - // CloudWatchLogsLogGroupArn is a required field - CloudWatchLogsLogGroupArn *string `type:"string" required:"true"` - - // The ID of the hosted zone that you want to log queries for. You can log queries - // only for public hosted zones. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateQueryLoggingConfigInput"} - if s.CloudWatchLogsLogGroupArn == nil { - invalidParams.Add(request.NewErrParamRequired("CloudWatchLogsLogGroupArn")) - } - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCloudWatchLogsLogGroupArn sets the CloudWatchLogsLogGroupArn field's value. -func (s *CreateQueryLoggingConfigInput) SetCloudWatchLogsLogGroupArn(v string) *CreateQueryLoggingConfigInput { - s.CloudWatchLogsLogGroupArn = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateQueryLoggingConfigInput) SetHostedZoneId(v string) *CreateQueryLoggingConfigInput { - s.HostedZoneId = &v - return s -} - -type CreateQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` - - // The unique URL representing the new query logging configuration. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains the ID for a query logging configuration, the - // ID of the hosted zone that you want to log queries for, and the ARN for the - // log group that you want Amazon Route 53 to send query logs to. - // - // QueryLoggingConfig is a required field - QueryLoggingConfig *QueryLoggingConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateQueryLoggingConfigOutput) SetLocation(v string) *CreateQueryLoggingConfigOutput { - s.Location = &v - return s -} - -// SetQueryLoggingConfig sets the QueryLoggingConfig field's value. -func (s *CreateQueryLoggingConfigOutput) SetQueryLoggingConfig(v *QueryLoggingConfig) *CreateQueryLoggingConfigOutput { - s.QueryLoggingConfig = v - return s -} - -type CreateReusableDelegationSetInput struct { - _ struct{} `locationName:"CreateReusableDelegationSetRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A unique string that identifies the request, and that allows you to retry - // failed CreateReusableDelegationSet requests without the risk of executing - // the operation twice. You must use a unique CallerReference string every time - // you submit a CreateReusableDelegationSet request. CallerReference can be - // any unique string, for example a date/time stamp. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // If you want to mark the delegation set for an existing hosted zone as reusable, - // the ID for that hosted zone. - HostedZoneId *string `type:"string"` -} - -// String returns the string representation -func (s CreateReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateReusableDelegationSetInput"} - if s.CallerReference == nil { - invalidParams.Add(request.NewErrParamRequired("CallerReference")) - } - if s.CallerReference != nil && len(*s.CallerReference) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CallerReference", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetCallerReference sets the CallerReference field's value. -func (s *CreateReusableDelegationSetInput) SetCallerReference(v string) *CreateReusableDelegationSetInput { - s.CallerReference = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateReusableDelegationSetInput) SetHostedZoneId(v string) *CreateReusableDelegationSetInput { - s.HostedZoneId = &v - return s -} - -type CreateReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains name server information. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` - - // The unique URL representing the new reusable delegation set. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *CreateReusableDelegationSetOutput) SetDelegationSet(v *DelegationSet) *CreateReusableDelegationSetOutput { - s.DelegationSet = v - return s -} - -// SetLocation sets the Location field's value. -func (s *CreateReusableDelegationSetOutput) SetLocation(v string) *CreateReusableDelegationSetOutput { - s.Location = &v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to create. -type CreateTrafficPolicyInput struct { - _ struct{} `locationName:"CreateTrafficPolicyRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // (Optional) Any comments that you want to include about the traffic policy. - Comment *string `type:"string"` - - // The definition of this traffic policy in JSON format. For more information, - // see Traffic Policy Document Format (http://docs.aws.amazon.com/Route53/latest/APIReference/api-policies-traffic-policy-document-format.html). - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The name of the traffic policy. - // - // Name is a required field - Name *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyInput"} - if s.Document == nil { - invalidParams.Add(request.NewErrParamRequired("Document")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *CreateTrafficPolicyInput) SetComment(v string) *CreateTrafficPolicyInput { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *CreateTrafficPolicyInput) SetDocument(v string) *CreateTrafficPolicyInput { - s.Document = &v - return s -} - -// SetName sets the Name field's value. -func (s *CreateTrafficPolicyInput) SetName(v string) *CreateTrafficPolicyInput { - s.Name = &v - return s -} - -// A complex type that contains information about the resource record sets that -// you want to create based on a specified traffic policy. -type CreateTrafficPolicyInstanceInput struct { - _ struct{} `locationName:"CreateTrafficPolicyInstanceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the hosted zone in which you want Amazon Route 53 to create resource - // record sets by using the configuration in a traffic policy. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The domain name (such as example.com) or subdomain name (such as www.example.com) - // for which Amazon Route 53 responds to DNS queries by using the resource record - // sets that Amazon Route 53 creates for this traffic policy instance. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // (Optional) The TTL that you want Amazon Route 53 to assign to all of the - // resource record sets that it creates in the specified hosted zone. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that you want to use to create resource record - // sets in the specified hosted zone. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The version of the traffic policy that you want to use to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyInstanceInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.TTL == nil { - invalidParams.Add(request.NewErrParamRequired("TTL")) - } - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateTrafficPolicyInstanceInput) SetHostedZoneId(v string) *CreateTrafficPolicyInstanceInput { - s.HostedZoneId = &v - return s -} - -// SetName sets the Name field's value. -func (s *CreateTrafficPolicyInstanceInput) SetName(v string) *CreateTrafficPolicyInstanceInput { - s.Name = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTTL(v int64) *CreateTrafficPolicyInstanceInput { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTrafficPolicyId(v string) *CreateTrafficPolicyInstanceInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *CreateTrafficPolicyInstanceInput) SetTrafficPolicyVersion(v int64) *CreateTrafficPolicyInstanceInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicyInstance -// request. -type CreateTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy instance. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyInstanceOutput) SetLocation(v string) *CreateTrafficPolicyInstanceOutput { - s.Location = &v - return s -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *CreateTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *CreateTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicy -// request. -type CreateTrafficPolicyOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyOutput) SetLocation(v string) *CreateTrafficPolicyOutput { - s.Location = &v - return s -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *CreateTrafficPolicyOutput) SetTrafficPolicy(v *TrafficPolicy) *CreateTrafficPolicyOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to create a new version for. -type CreateTrafficPolicyVersionInput struct { - _ struct{} `locationName:"CreateTrafficPolicyVersionRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The comment that you specified in the CreateTrafficPolicyVersion request, - // if any. - Comment *string `type:"string"` - - // The definition of this version of the traffic policy, in JSON format. You - // specified the JSON in the CreateTrafficPolicyVersion request. For more information - // about the JSON format, see CreateTrafficPolicy. - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The ID of the traffic policy for which you want to create a new version. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyVersionInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyVersionInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateTrafficPolicyVersionInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateTrafficPolicyVersionInput"} - if s.Document == nil { - invalidParams.Add(request.NewErrParamRequired("Document")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *CreateTrafficPolicyVersionInput) SetComment(v string) *CreateTrafficPolicyVersionInput { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *CreateTrafficPolicyVersionInput) SetDocument(v string) *CreateTrafficPolicyVersionInput { - s.Document = &v - return s -} - -// SetId sets the Id field's value. -func (s *CreateTrafficPolicyVersionInput) SetId(v string) *CreateTrafficPolicyVersionInput { - s.Id = &v - return s -} - -// A complex type that contains the response information for the CreateTrafficPolicyVersion -// request. -type CreateTrafficPolicyVersionOutput struct { - _ struct{} `type:"structure"` - - // A unique URL that represents a new traffic policy version. - // - // Location is a required field - Location *string `location:"header" locationName:"Location" type:"string" required:"true"` - - // A complex type that contains settings for the new version of the traffic - // policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateTrafficPolicyVersionOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateTrafficPolicyVersionOutput) GoString() string { - return s.String() -} - -// SetLocation sets the Location field's value. -func (s *CreateTrafficPolicyVersionOutput) SetLocation(v string) *CreateTrafficPolicyVersionOutput { - s.Location = &v - return s -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *CreateTrafficPolicyVersionOutput) SetTrafficPolicy(v *TrafficPolicy) *CreateTrafficPolicyVersionOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the request to authorize associating -// a VPC with your private hosted zone. Authorization is only required when -// a private hosted zone and a VPC were created by using different accounts. -type CreateVPCAssociationAuthorizationInput struct { - _ struct{} `locationName:"CreateVPCAssociationAuthorizationRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the private hosted zone that you want to authorize associating - // a VPC with. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains the VPC ID and region for the VPC that you want - // to authorize associating with your hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateVPCAssociationAuthorizationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateVPCAssociationAuthorizationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *CreateVPCAssociationAuthorizationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "CreateVPCAssociationAuthorizationInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateVPCAssociationAuthorizationInput) SetHostedZoneId(v string) *CreateVPCAssociationAuthorizationInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateVPCAssociationAuthorizationInput) SetVPC(v *VPC) *CreateVPCAssociationAuthorizationInput { - s.VPC = v - return s -} - -// A complex type that contains the response information from a CreateVPCAssociationAuthorization -// request. -type CreateVPCAssociationAuthorizationOutput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you authorized associating a VPC with. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The VPC that you authorized associating with a hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s CreateVPCAssociationAuthorizationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s CreateVPCAssociationAuthorizationOutput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *CreateVPCAssociationAuthorizationOutput) SetHostedZoneId(v string) *CreateVPCAssociationAuthorizationOutput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *CreateVPCAssociationAuthorizationOutput) SetVPC(v *VPC) *CreateVPCAssociationAuthorizationOutput { - s.VPC = v - return s -} - -// A complex type that lists the name servers in a delegation set, as well as -// the CallerReference and the ID for the delegation set. -type DelegationSet struct { - _ struct{} `type:"structure"` - - // The value that you specified for CallerReference when you created the reusable - // delegation set. - CallerReference *string `min:"1" type:"string"` - - // The ID that Amazon Route 53 assigns to a reusable delegation set. - Id *string `type:"string"` - - // A complex type that contains a list of the authoritative name servers for - // a hosted zone or for a reusable delegation set. - // - // NameServers is a required field - NameServers []*string `locationNameList:"NameServer" min:"1" type:"list" required:"true"` -} - -// String returns the string representation -func (s DelegationSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DelegationSet) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *DelegationSet) SetCallerReference(v string) *DelegationSet { - s.CallerReference = &v - return s -} - -// SetId sets the Id field's value. -func (s *DelegationSet) SetId(v string) *DelegationSet { - s.Id = &v - return s -} - -// SetNameServers sets the NameServers field's value. -func (s *DelegationSet) SetNameServers(v []*string) *DelegationSet { - s.NameServers = v - return s -} - -// This action deletes a health check. -type DeleteHealthCheckInput struct { - _ struct{} `type:"structure"` - - // The ID of the health check that you want to delete. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteHealthCheckInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *DeleteHealthCheckInput) SetHealthCheckId(v string) *DeleteHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// An empty element. -type DeleteHealthCheckOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHealthCheckOutput) GoString() string { - return s.String() -} - -// A request to delete a hosted zone. -type DeleteHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteHostedZoneInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteHostedZoneInput) SetId(v string) *DeleteHostedZoneInput { - s.Id = &v - return s -} - -// A complex type that contains the response to a DeleteHostedZone request. -type DeleteHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains the ID, the status, and the date and time of - // a request to delete a hosted zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DeleteHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *DeleteHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *DeleteHostedZoneOutput { - s.ChangeInfo = v - return s -} - -type DeleteQueryLoggingConfigInput struct { - _ struct{} `type:"structure"` - - // The ID of the configuration that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteQueryLoggingConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteQueryLoggingConfigInput) SetId(v string) *DeleteQueryLoggingConfigInput { - s.Id = &v - return s -} - -type DeleteQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// A request to delete a reusable delegation set. -type DeleteReusableDelegationSetInput struct { - _ struct{} `type:"structure"` - - // The ID of the reusable delegation set that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteReusableDelegationSetInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteReusableDelegationSetInput) SetId(v string) *DeleteReusableDelegationSetInput { - s.Id = &v - return s -} - -// An empty element. -type DeleteReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// A request to delete a specified traffic policy version. -type DeleteTrafficPolicyInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy that you want to delete. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The version number of the traffic policy that you want to delete. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTrafficPolicyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteTrafficPolicyInput) SetId(v string) *DeleteTrafficPolicyInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *DeleteTrafficPolicyInput) SetVersion(v int64) *DeleteTrafficPolicyInput { - s.Version = &v - return s -} - -// A request to delete a specified traffic policy instance. -type DeleteTrafficPolicyInstanceInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy instance that you want to delete. - // - // When you delete a traffic policy instance, Amazon Route 53 also deletes all - // of the resource record sets that were created when you created the traffic - // policy instance. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *DeleteTrafficPolicyInstanceInput) SetId(v string) *DeleteTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// An empty element. -type DeleteTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// An empty element. -type DeleteTrafficPolicyOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteTrafficPolicyOutput) GoString() string { - return s.String() -} - -// A complex type that contains information about the request to remove authorization -// to associate a VPC that was created by one AWS account with a hosted zone -// that was created with a different AWS account. -type DeleteVPCAssociationAuthorizationInput struct { - _ struct{} `locationName:"DeleteVPCAssociationAuthorizationRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // When removing authorization to associate a VPC that was created by one AWS - // account with a hosted zone that was created with a different AWS account, - // the ID of the hosted zone. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // When removing authorization to associate a VPC that was created by one AWS - // account with a hosted zone that was created with a different AWS account, - // a complex type that includes the ID and region of the VPC. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DeleteVPCAssociationAuthorizationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteVPCAssociationAuthorizationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DeleteVPCAssociationAuthorizationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DeleteVPCAssociationAuthorizationInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *DeleteVPCAssociationAuthorizationInput) SetHostedZoneId(v string) *DeleteVPCAssociationAuthorizationInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *DeleteVPCAssociationAuthorizationInput) SetVPC(v *VPC) *DeleteVPCAssociationAuthorizationInput { - s.VPC = v - return s -} - -// Empty response for the request. -type DeleteVPCAssociationAuthorizationOutput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s DeleteVPCAssociationAuthorizationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DeleteVPCAssociationAuthorizationOutput) GoString() string { - return s.String() -} - -// For the metric that the CloudWatch alarm is associated with, a complex type -// that contains information about one dimension. -type Dimension struct { - _ struct{} `type:"structure"` - - // For the metric that the CloudWatch alarm is associated with, the name of - // one dimension. - // - // Name is a required field - Name *string `min:"1" type:"string" required:"true"` - - // For the metric that the CloudWatch alarm is associated with, the value of - // one dimension. - // - // Value is a required field - Value *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s Dimension) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Dimension) GoString() string { - return s.String() -} - -// SetName sets the Name field's value. -func (s *Dimension) SetName(v string) *Dimension { - s.Name = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Dimension) SetValue(v string) *Dimension { - s.Value = &v - return s -} - -// A complex type that contains information about the VPC that you want to disassociate -// from a specified private hosted zone. -type DisassociateVPCFromHostedZoneInput struct { - _ struct{} `locationName:"DisassociateVPCFromHostedZoneRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // Optional: A comment about the disassociation request. - Comment *string `type:"string"` - - // The ID of the private hosted zone that you want to disassociate a VPC from. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // A complex type that contains information about the VPC that you're disassociating - // from the specified hosted zone. - // - // VPC is a required field - VPC *VPC `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DisassociateVPCFromHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DisassociateVPCFromHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DisassociateVPCFromHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DisassociateVPCFromHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.VPC == nil { - invalidParams.Add(request.NewErrParamRequired("VPC")) - } - if s.VPC != nil { - if err := s.VPC.Validate(); err != nil { - invalidParams.AddNested("VPC", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetComment(v string) *DisassociateVPCFromHostedZoneInput { - s.Comment = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetHostedZoneId(v string) *DisassociateVPCFromHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetVPC sets the VPC field's value. -func (s *DisassociateVPCFromHostedZoneInput) SetVPC(v *VPC) *DisassociateVPCFromHostedZoneInput { - s.VPC = v - return s -} - -// A complex type that contains the response information for the disassociate -// request. -type DisassociateVPCFromHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that describes the changes made to the specified private hosted - // zone. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s DisassociateVPCFromHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DisassociateVPCFromHostedZoneOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *DisassociateVPCFromHostedZoneOutput) SetChangeInfo(v *ChangeInfo) *DisassociateVPCFromHostedZoneOutput { - s.ChangeInfo = v - return s -} - -// A complex type that contains information about a geo location. -type GeoLocation struct { - _ struct{} `type:"structure"` - - // The two-letter code for the continent. - // - // Valid values: AF | AN | AS | EU | OC | NA | SA - // - // Constraint: Specifying ContinentCode with either CountryCode or SubdivisionCode - // returns an InvalidInput error. - ContinentCode *string `min:"2" type:"string"` - - // The two-letter code for the country. - CountryCode *string `min:"1" type:"string"` - - // The code for the subdivision, for example, a state in the United States or - // a province in Canada. - SubdivisionCode *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GeoLocation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GeoLocation) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GeoLocation) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GeoLocation"} - if s.ContinentCode != nil && len(*s.ContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ContinentCode", 2)) - } - if s.CountryCode != nil && len(*s.CountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CountryCode", 1)) - } - if s.SubdivisionCode != nil && len(*s.SubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GeoLocation) SetContinentCode(v string) *GeoLocation { - s.ContinentCode = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GeoLocation) SetCountryCode(v string) *GeoLocation { - s.CountryCode = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GeoLocation) SetSubdivisionCode(v string) *GeoLocation { - s.SubdivisionCode = &v - return s -} - -// A complex type that contains the codes and full continent, country, and subdivision -// names for the specified geolocation code. -type GeoLocationDetails struct { - _ struct{} `type:"structure"` - - // The two-letter code for the continent. - ContinentCode *string `min:"2" type:"string"` - - // The full name of the continent. - ContinentName *string `min:"1" type:"string"` - - // The two-letter code for the country. - CountryCode *string `min:"1" type:"string"` - - // The name of the country. - CountryName *string `min:"1" type:"string"` - - // The code for the subdivision, for example, a state in the United States or - // a province in Canada. - SubdivisionCode *string `min:"1" type:"string"` - - // The full name of the subdivision, for example, a state in the United States - // or a province in Canada. - SubdivisionName *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GeoLocationDetails) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GeoLocationDetails) GoString() string { - return s.String() -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GeoLocationDetails) SetContinentCode(v string) *GeoLocationDetails { - s.ContinentCode = &v - return s -} - -// SetContinentName sets the ContinentName field's value. -func (s *GeoLocationDetails) SetContinentName(v string) *GeoLocationDetails { - s.ContinentName = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GeoLocationDetails) SetCountryCode(v string) *GeoLocationDetails { - s.CountryCode = &v - return s -} - -// SetCountryName sets the CountryName field's value. -func (s *GeoLocationDetails) SetCountryName(v string) *GeoLocationDetails { - s.CountryName = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GeoLocationDetails) SetSubdivisionCode(v string) *GeoLocationDetails { - s.SubdivisionCode = &v - return s -} - -// SetSubdivisionName sets the SubdivisionName field's value. -func (s *GeoLocationDetails) SetSubdivisionName(v string) *GeoLocationDetails { - s.SubdivisionName = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetAccountLimitInput struct { - _ struct{} `type:"structure"` - - // The limit that you want to get. Valid values include the following: - // - // * MAX_HEALTH_CHECKS_BY_OWNER: The maximum number of health checks that - // you can create using the current account. - // - // * MAX_HOSTED_ZONES_BY_OWNER: The maximum number of hosted zones that you - // can create using the current account. - // - // * MAX_REUSABLE_DELEGATION_SETS_BY_OWNER: The maximum number of reusable - // delegation sets that you can create using the current account. - // - // * MAX_TRAFFIC_POLICIES_BY_OWNER: The maximum number of traffic policies - // that you can create using the current account. - // - // * MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER: The maximum number of traffic - // policy instances that you can create using the current account. (Traffic - // policy instances are referred to as traffic flow policy records in the - // Amazon Route 53 console.) - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"AccountLimitType"` -} - -// String returns the string representation -func (s GetAccountLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetAccountLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetAccountLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetAccountLimitInput"} - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetType sets the Type field's value. -func (s *GetAccountLimitInput) SetType(v string) *GetAccountLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetAccountLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of entities that you have created of the specified type. - // For example, if you specified MAX_HEALTH_CHECKS_BY_OWNER for the value of - // Type in the request, the value of Count is the current number of health checks - // that you have created using the current account. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the specified limit. For example, if you specified - // MAX_HEALTH_CHECKS_BY_OWNER for the value of Type in the request, the value - // of Limit is the maximum number of health checks that you can create using - // the current account. - // - // Limit is a required field - Limit *AccountLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetAccountLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetAccountLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetAccountLimitOutput) SetCount(v int64) *GetAccountLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetAccountLimitOutput) SetLimit(v *AccountLimit) *GetAccountLimitOutput { - s.Limit = v - return s -} - -// The input for a GetChange request. -type GetChangeInput struct { - _ struct{} `type:"structure"` - - // The ID of the change batch request. The value that you specify here is the - // value that ChangeResourceRecordSets returned in the Id element when you submitted - // the request. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetChangeInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetChangeInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetChangeInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetChangeInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetChangeInput) SetId(v string) *GetChangeInput { - s.Id = &v - return s -} - -// A complex type that contains the ChangeInfo element. -type GetChangeOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the specified change batch. - // - // ChangeInfo is a required field - ChangeInfo *ChangeInfo `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetChangeOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetChangeOutput) GoString() string { - return s.String() -} - -// SetChangeInfo sets the ChangeInfo field's value. -func (s *GetChangeOutput) SetChangeInfo(v *ChangeInfo) *GetChangeOutput { - s.ChangeInfo = v - return s -} - -type GetCheckerIpRangesInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetCheckerIpRangesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCheckerIpRangesInput) GoString() string { - return s.String() -} - -type GetCheckerIpRangesOutput struct { - _ struct{} `type:"structure"` - - // CheckerIpRanges is a required field - CheckerIpRanges []*string `type:"list" required:"true"` -} - -// String returns the string representation -func (s GetCheckerIpRangesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCheckerIpRangesOutput) GoString() string { - return s.String() -} - -// SetCheckerIpRanges sets the CheckerIpRanges field's value. -func (s *GetCheckerIpRangesOutput) SetCheckerIpRanges(v []*string) *GetCheckerIpRangesOutput { - s.CheckerIpRanges = v - return s -} - -// A request for information about whether a specified geographic location is -// supported for Amazon Route 53 geolocation resource record sets. -type GetGeoLocationInput struct { - _ struct{} `type:"structure"` - - // Amazon Route 53 supports the following continent codes: - // - // * AF: Africa - // - // * AN: Antarctica - // - // * AS: Asia - // - // * EU: Europe - // - // * OC: Oceania - // - // * NA: North America - // - // * SA: South America - ContinentCode *string `location:"querystring" locationName:"continentcode" min:"2" type:"string"` - - // Amazon Route 53 uses the two-letter country codes that are specified in ISO - // standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - CountryCode *string `location:"querystring" locationName:"countrycode" min:"1" type:"string"` - - // Amazon Route 53 uses the one- to three-letter subdivision codes that are - // specified in ISO standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - // Amazon Route 53 doesn't support subdivision codes for all countries. If you - // specify SubdivisionCode, you must also specify CountryCode. - SubdivisionCode *string `location:"querystring" locationName:"subdivisioncode" min:"1" type:"string"` -} - -// String returns the string representation -func (s GetGeoLocationInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetGeoLocationInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetGeoLocationInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetGeoLocationInput"} - if s.ContinentCode != nil && len(*s.ContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ContinentCode", 2)) - } - if s.CountryCode != nil && len(*s.CountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("CountryCode", 1)) - } - if s.SubdivisionCode != nil && len(*s.SubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetContinentCode sets the ContinentCode field's value. -func (s *GetGeoLocationInput) SetContinentCode(v string) *GetGeoLocationInput { - s.ContinentCode = &v - return s -} - -// SetCountryCode sets the CountryCode field's value. -func (s *GetGeoLocationInput) SetCountryCode(v string) *GetGeoLocationInput { - s.CountryCode = &v - return s -} - -// SetSubdivisionCode sets the SubdivisionCode field's value. -func (s *GetGeoLocationInput) SetSubdivisionCode(v string) *GetGeoLocationInput { - s.SubdivisionCode = &v - return s -} - -// A complex type that contains the response information for the specified geolocation -// code. -type GetGeoLocationOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains the codes and full continent, country, and subdivision - // names for the specified geolocation code. - // - // GeoLocationDetails is a required field - GeoLocationDetails *GeoLocationDetails `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetGeoLocationOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetGeoLocationOutput) GoString() string { - return s.String() -} - -// SetGeoLocationDetails sets the GeoLocationDetails field's value. -func (s *GetGeoLocationOutput) SetGeoLocationDetails(v *GeoLocationDetails) *GetGeoLocationOutput { - s.GeoLocationDetails = v - return s -} - -// A request for the number of health checks that are associated with the current -// AWS account. -type GetHealthCheckCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetHealthCheckCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckCountInput) GoString() string { - return s.String() -} - -// A complex type that contains the response to a GetHealthCheckCount request. -type GetHealthCheckCountOutput struct { - _ struct{} `type:"structure"` - - // The number of health checks associated with the current AWS account. - // - // HealthCheckCount is a required field - HealthCheckCount *int64 `type:"long" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckCountOutput) GoString() string { - return s.String() -} - -// SetHealthCheckCount sets the HealthCheckCount field's value. -func (s *GetHealthCheckCountOutput) SetHealthCheckCount(v int64) *GetHealthCheckCountOutput { - s.HealthCheckCount = &v - return s -} - -// A request to get information about a specified health check. -type GetHealthCheckInput struct { - _ struct{} `type:"structure"` - - // The identifier that Amazon Route 53 assigned to the health check when you - // created it. When you add or update a resource record set, you use this value - // to specify which health check to use. The value can be up to 64 characters - // long. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckInput) SetHealthCheckId(v string) *GetHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// A request for the reason that a health check failed most recently. -type GetHealthCheckLastFailureReasonInput struct { - _ struct{} `type:"structure"` - - // The ID for the health check for which you want the last failure reason. When - // you created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // If you want to get the last failure reason for a calculated health check, - // you must use the Amazon Route 53 console or the CloudWatch console. You can't - // use GetHealthCheckLastFailureReason for a calculated health check. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckLastFailureReasonInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckLastFailureReasonInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckLastFailureReasonInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckLastFailureReasonInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckLastFailureReasonInput) SetHealthCheckId(v string) *GetHealthCheckLastFailureReasonInput { - s.HealthCheckId = &v - return s -} - -// A complex type that contains the response to a GetHealthCheckLastFailureReason -// request. -type GetHealthCheckLastFailureReasonOutput struct { - _ struct{} `type:"structure"` - - // A list that contains one Observation element for each Amazon Route 53 health - // checker that is reporting a last failure reason. - // - // HealthCheckObservations is a required field - HealthCheckObservations []*HealthCheckObservation `locationNameList:"HealthCheckObservation" type:"list" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckLastFailureReasonOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckLastFailureReasonOutput) GoString() string { - return s.String() -} - -// SetHealthCheckObservations sets the HealthCheckObservations field's value. -func (s *GetHealthCheckLastFailureReasonOutput) SetHealthCheckObservations(v []*HealthCheckObservation) *GetHealthCheckLastFailureReasonOutput { - s.HealthCheckObservations = v - return s -} - -// A complex type that contains the response to a GetHealthCheck request. -type GetHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about one health check that is associated - // with the current AWS account. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *GetHealthCheckOutput) SetHealthCheck(v *HealthCheck) *GetHealthCheckOutput { - s.HealthCheck = v - return s -} - -// A request to get the status for a health check. -type GetHealthCheckStatusInput struct { - _ struct{} `type:"structure"` - - // The ID for the health check that you want the current status for. When you - // created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // If you want to check the status of a calculated health check, you must use - // the Amazon Route 53 console or the CloudWatch console. You can't use GetHealthCheckStatus - // to get the status of a calculated health check. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckStatusInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckStatusInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHealthCheckStatusInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHealthCheckStatusInput"} - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *GetHealthCheckStatusInput) SetHealthCheckId(v string) *GetHealthCheckStatusInput { - s.HealthCheckId = &v - return s -} - -// A complex type that contains the response to a GetHealthCheck request. -type GetHealthCheckStatusOutput struct { - _ struct{} `type:"structure"` - - // A list that contains one HealthCheckObservation element for each Amazon Route - // 53 health checker that is reporting a status about the health check endpoint. - // - // HealthCheckObservations is a required field - HealthCheckObservations []*HealthCheckObservation `locationNameList:"HealthCheckObservation" type:"list" required:"true"` -} - -// String returns the string representation -func (s GetHealthCheckStatusOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHealthCheckStatusOutput) GoString() string { - return s.String() -} - -// SetHealthCheckObservations sets the HealthCheckObservations field's value. -func (s *GetHealthCheckStatusOutput) SetHealthCheckObservations(v []*HealthCheckObservation) *GetHealthCheckStatusOutput { - s.HealthCheckObservations = v - return s -} - -// A request to retrieve a count of all the hosted zones that are associated -// with the current AWS account. -type GetHostedZoneCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetHostedZoneCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneCountInput) GoString() string { - return s.String() -} - -// A complex type that contains the response to a GetHostedZoneCount request. -type GetHostedZoneCountOutput struct { - _ struct{} `type:"structure"` - - // The total number of public and private hosted zones that are associated with - // the current AWS account. - // - // HostedZoneCount is a required field - HostedZoneCount *int64 `type:"long" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneCountOutput) GoString() string { - return s.String() -} - -// SetHostedZoneCount sets the HostedZoneCount field's value. -func (s *GetHostedZoneCountOutput) SetHostedZoneCount(v int64) *GetHostedZoneCountOutput { - s.HostedZoneCount = &v - return s -} - -// A request to get information about a specified hosted zone. -type GetHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHostedZoneInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetHostedZoneInput) SetId(v string) *GetHostedZoneInput { - s.Id = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetHostedZoneLimitInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to get a limit for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // The limit that you want to get. Valid values include the following: - // - // * MAX_RRSETS_BY_ZONE: The maximum number of records that you can create - // in the specified hosted zone. - // - // * MAX_VPCS_ASSOCIATED_BY_ZONE: The maximum number of Amazon VPCs that - // you can associate with the specified private hosted zone. - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"HostedZoneLimitType"` -} - -// String returns the string representation -func (s GetHostedZoneLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetHostedZoneLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetHostedZoneLimitInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *GetHostedZoneLimitInput) SetHostedZoneId(v string) *GetHostedZoneLimitInput { - s.HostedZoneId = &v - return s -} - -// SetType sets the Type field's value. -func (s *GetHostedZoneLimitInput) SetType(v string) *GetHostedZoneLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetHostedZoneLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of entities that you have created of the specified type. - // For example, if you specified MAX_RRSETS_BY_ZONE for the value of Type in - // the request, the value of Count is the current number of records that you - // have created in the specified hosted zone. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the specified limit. For example, if you specified - // MAX_RRSETS_BY_ZONE for the value of Type in the request, the value of Limit - // is the maximum number of records that you can create in the specified hosted - // zone. - // - // Limit is a required field - Limit *HostedZoneLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetHostedZoneLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetHostedZoneLimitOutput) SetCount(v int64) *GetHostedZoneLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetHostedZoneLimitOutput) SetLimit(v *HostedZoneLimit) *GetHostedZoneLimitOutput { - s.Limit = v - return s -} - -// A complex type that contain the response to a GetHostedZone request. -type GetHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A complex type that lists the Amazon Route 53 name servers for the specified - // hosted zone. - DelegationSet *DelegationSet `type:"structure"` - - // A complex type that contains general information about the specified hosted - // zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` - - // A complex type that contains information about the VPCs that are associated - // with the specified hosted zone. - VPCs []*VPC `locationNameList:"VPC" min:"1" type:"list"` -} - -// String returns the string representation -func (s GetHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetHostedZoneOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *GetHostedZoneOutput) SetDelegationSet(v *DelegationSet) *GetHostedZoneOutput { - s.DelegationSet = v - return s -} - -// SetHostedZone sets the HostedZone field's value. -func (s *GetHostedZoneOutput) SetHostedZone(v *HostedZone) *GetHostedZoneOutput { - s.HostedZone = v - return s -} - -// SetVPCs sets the VPCs field's value. -func (s *GetHostedZoneOutput) SetVPCs(v []*VPC) *GetHostedZoneOutput { - s.VPCs = v - return s -} - -type GetQueryLoggingConfigInput struct { - _ struct{} `type:"structure"` - - // The ID of the configuration for DNS query logging that you want to get information - // about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetQueryLoggingConfigInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetQueryLoggingConfigInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetQueryLoggingConfigInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetQueryLoggingConfigInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetQueryLoggingConfigInput) SetId(v string) *GetQueryLoggingConfigInput { - s.Id = &v - return s -} - -type GetQueryLoggingConfigOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the query logging configuration - // that you specified in a GetQueryLoggingConfig request. - // - // QueryLoggingConfig is a required field - QueryLoggingConfig *QueryLoggingConfig `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetQueryLoggingConfigOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetQueryLoggingConfigOutput) GoString() string { - return s.String() -} - -// SetQueryLoggingConfig sets the QueryLoggingConfig field's value. -func (s *GetQueryLoggingConfigOutput) SetQueryLoggingConfig(v *QueryLoggingConfig) *GetQueryLoggingConfigOutput { - s.QueryLoggingConfig = v - return s -} - -// A request to get information about a specified reusable delegation set. -type GetReusableDelegationSetInput struct { - _ struct{} `type:"structure"` - - // The ID of the reusable delegation set that you want to get a list of name - // servers for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetReusableDelegationSetInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetReusableDelegationSetInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetReusableDelegationSetInput) SetId(v string) *GetReusableDelegationSetInput { - s.Id = &v - return s -} - -// A complex type that contains information about the request to create a hosted -// zone. -type GetReusableDelegationSetLimitInput struct { - _ struct{} `type:"structure"` - - // The ID of the delegation set that you want to get the limit for. - // - // DelegationSetId is a required field - DelegationSetId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // Specify MAX_ZONES_BY_REUSABLE_DELEGATION_SET to get the maximum number of - // hosted zones that you can associate with the specified reusable delegation - // set. - // - // Type is a required field - Type *string `location:"uri" locationName:"Type" type:"string" required:"true" enum:"ReusableDelegationSetLimitType"` -} - -// String returns the string representation -func (s GetReusableDelegationSetLimitInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetLimitInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetReusableDelegationSetLimitInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetReusableDelegationSetLimitInput"} - if s.DelegationSetId == nil { - invalidParams.Add(request.NewErrParamRequired("DelegationSetId")) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *GetReusableDelegationSetLimitInput) SetDelegationSetId(v string) *GetReusableDelegationSetLimitInput { - s.DelegationSetId = &v - return s -} - -// SetType sets the Type field's value. -func (s *GetReusableDelegationSetLimitInput) SetType(v string) *GetReusableDelegationSetLimitInput { - s.Type = &v - return s -} - -// A complex type that contains the requested limit. -type GetReusableDelegationSetLimitOutput struct { - _ struct{} `type:"structure"` - - // The current number of hosted zones that you can associate with the specified - // reusable delegation set. - // - // Count is a required field - Count *int64 `type:"long" required:"true"` - - // The current setting for the limit on hosted zones that you can associate - // with the specified reusable delegation set. - // - // Limit is a required field - Limit *ReusableDelegationSetLimit `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetLimitOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetLimitOutput) GoString() string { - return s.String() -} - -// SetCount sets the Count field's value. -func (s *GetReusableDelegationSetLimitOutput) SetCount(v int64) *GetReusableDelegationSetLimitOutput { - s.Count = &v - return s -} - -// SetLimit sets the Limit field's value. -func (s *GetReusableDelegationSetLimitOutput) SetLimit(v *ReusableDelegationSetLimit) *GetReusableDelegationSetLimitOutput { - s.Limit = v - return s -} - -// A complex type that contains the response to the GetReusableDelegationSet -// request. -type GetReusableDelegationSetOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about the reusable delegation set. - // - // DelegationSet is a required field - DelegationSet *DelegationSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetReusableDelegationSetOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetReusableDelegationSetOutput) GoString() string { - return s.String() -} - -// SetDelegationSet sets the DelegationSet field's value. -func (s *GetReusableDelegationSetOutput) SetDelegationSet(v *DelegationSet) *GetReusableDelegationSetOutput { - s.DelegationSet = v - return s -} - -// Gets information about a specific traffic policy version. -type GetTrafficPolicyInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The version number of the traffic policy that you want to get information - // about. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetTrafficPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetTrafficPolicyInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetTrafficPolicyInput) SetId(v string) *GetTrafficPolicyInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *GetTrafficPolicyInput) SetVersion(v int64) *GetTrafficPolicyInput { - s.Version = &v - return s -} - -// Request to get the number of traffic policy instances that are associated -// with the current AWS account. -type GetTrafficPolicyInstanceCountInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceCountInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceCountInput) GoString() string { - return s.String() -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type GetTrafficPolicyInstanceCountOutput struct { - _ struct{} `type:"structure"` - - // The number of traffic policy instances that are associated with the current - // AWS account. - // - // TrafficPolicyInstanceCount is a required field - TrafficPolicyInstanceCount *int64 `type:"integer" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceCountOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceCountOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstanceCount sets the TrafficPolicyInstanceCount field's value. -func (s *GetTrafficPolicyInstanceCountOutput) SetTrafficPolicyInstanceCount(v int64) *GetTrafficPolicyInstanceCountOutput { - s.TrafficPolicyInstanceCount = &v - return s -} - -// Gets information about a specified traffic policy instance. -type GetTrafficPolicyInstanceInput struct { - _ struct{} `type:"structure"` - - // The ID of the traffic policy instance that you want to get information about. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *GetTrafficPolicyInstanceInput) SetId(v string) *GetTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type GetTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *GetTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *GetTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// A complex type that contains the response information for the request. -type GetTrafficPolicyOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the specified traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s GetTrafficPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetTrafficPolicyOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *GetTrafficPolicyOutput) SetTrafficPolicy(v *TrafficPolicy) *GetTrafficPolicyOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about one health check that is associated -// with the current AWS account. -type HealthCheck struct { - _ struct{} `type:"structure"` - - // A unique string that you specified when you created the health check. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that contains information about the CloudWatch alarm that - // Amazon Route 53 is monitoring for this health check. - CloudWatchAlarmConfiguration *CloudWatchAlarmConfiguration `type:"structure"` - - // A complex type that contains detailed information about one health check. - // - // HealthCheckConfig is a required field - HealthCheckConfig *HealthCheckConfig `type:"structure" required:"true"` - - // The version of the health check. You can optionally pass this value in a - // call to UpdateHealthCheck to prevent overwriting another change to the health - // check. - // - // HealthCheckVersion is a required field - HealthCheckVersion *int64 `min:"1" type:"long" required:"true"` - - // The identifier that Amazon Route 53assigned to the health check when you - // created it. When you add or update a resource record set, you use this value - // to specify which health check to use. The value can be up to 64 characters - // long. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // If the health check was created by another service, the service that created - // the health check. When a health check is created by another service, you - // can't edit or delete it using Amazon Route 53. - LinkedService *LinkedService `type:"structure"` -} - -// String returns the string representation -func (s HealthCheck) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheck) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *HealthCheck) SetCallerReference(v string) *HealthCheck { - s.CallerReference = &v - return s -} - -// SetCloudWatchAlarmConfiguration sets the CloudWatchAlarmConfiguration field's value. -func (s *HealthCheck) SetCloudWatchAlarmConfiguration(v *CloudWatchAlarmConfiguration) *HealthCheck { - s.CloudWatchAlarmConfiguration = v - return s -} - -// SetHealthCheckConfig sets the HealthCheckConfig field's value. -func (s *HealthCheck) SetHealthCheckConfig(v *HealthCheckConfig) *HealthCheck { - s.HealthCheckConfig = v - return s -} - -// SetHealthCheckVersion sets the HealthCheckVersion field's value. -func (s *HealthCheck) SetHealthCheckVersion(v int64) *HealthCheck { - s.HealthCheckVersion = &v - return s -} - -// SetId sets the Id field's value. -func (s *HealthCheck) SetId(v string) *HealthCheck { - s.Id = &v - return s -} - -// SetLinkedService sets the LinkedService field's value. -func (s *HealthCheck) SetLinkedService(v *LinkedService) *HealthCheck { - s.LinkedService = v - return s -} - -// A complex type that contains information about the health check. -type HealthCheckConfig struct { - _ struct{} `type:"structure"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - AlarmIdentifier *AlarmIdentifier `type:"structure"` - - // (CALCULATED Health Checks Only) A complex type that contains one ChildHealthCheck - // element for each health check that you want to associate with a CALCULATED - // health check. - ChildHealthChecks []*string `locationNameList:"ChildHealthCheck" type:"list"` - - // Specify whether you want Amazon Route 53 to send the value of FullyQualifiedDomainName - // to the endpoint in the client_hello message during TLS negotiation. This - // allows the endpoint to respond to HTTPS health check requests with the applicable - // SSL/TLS certificate. - // - // Some endpoints require that HTTPS requests include the host name in the client_hello - // message. If you don't enable SNI, the status of the health check will be - // SSL alert handshake_failure. A health check can also have that status for - // other reasons. If SNI is enabled and you're still getting the error, check - // the SSL/TLS configuration on your endpoint and confirm that your certificate - // is valid. - // - // The SSL/TLS certificate on your endpoint includes a domain name in the Common - // Name field and possibly several more in the Subject Alternative Names field. - // One of the domain names in the certificate should match the value that you - // specify for FullyQualifiedDomainName. If the endpoint responds to the client_hello - // message with a certificate that does not include the domain name that you - // specified in FullyQualifiedDomainName, a health checker will retry the handshake. - // In the second attempt, the health checker will omit FullyQualifiedDomainName - // from the client_hello message. - EnableSNI *bool `type:"boolean"` - - // The number of consecutive health checks that an endpoint must pass or fail - // for Amazon Route 53 to change the current status of the endpoint from unhealthy - // to healthy or vice versa. For more information, see How Amazon Route 53 Determines - // Whether an Endpoint Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // If you don't specify a value for FailureThreshold, the default value is three - // health checks. - FailureThreshold *int64 `min:"1" type:"integer"` - - // Amazon Route 53 behavior depends on whether you specify a value for IPAddress. - // - // If you specify a value forIPAddress: - // - // Amazon Route 53 sends health check requests to the specified IPv4 or IPv6 - // address and passes the value of FullyQualifiedDomainName in the Host header - // for all health checks except TCP health checks. This is typically the fully - // qualified DNS name of the endpoint on which you want Amazon Route 53 to perform - // health checks. - // - // When Amazon Route 53 checks the health of an endpoint, here is how it constructs - // the Host header: - // - // * If you specify a value of 80 for Port and HTTP or HTTP_STR_MATCH for - // Type, Amazon Route 53 passes the value of FullyQualifiedDomainName to - // the endpoint in the Host header. - // - // * If you specify a value of 443 for Port and HTTPS or HTTPS_STR_MATCH - // for Type, Amazon Route 53 passes the value of FullyQualifiedDomainName - // to the endpoint in the Host header. - // - // * If you specify another value for Port and any value except TCP for Type, - // Amazon Route 53 passes FullyQualifiedDomainName:Port to the endpoint in - // the Host header. - // - // If you don't specify a value for FullyQualifiedDomainName, Amazon Route 53 - // substitutes the value of IPAddress in the Host header in each of the preceding - // cases. - // - // If you don't specify a value for IPAddress: - // - // Amazon Route 53 sends a DNS request to the domain that you specify for FullyQualifiedDomainName - // at the interval that you specify for RequestInterval. Using an IPv4 address - // that DNS returns, Amazon Route 53 then checks the health of the endpoint. - // - // If you don't specify a value for IPAddress, Amazon Route 53 uses only IPv4 - // to send health checks to the endpoint. If there's no resource record set - // with a type of A for the name that you specify for FullyQualifiedDomainName, - // the health check fails with a "DNS resolution failed" error. - // - // If you want to check the health of weighted, latency, or failover resource - // record sets and you choose to specify the endpoint only by FullyQualifiedDomainName, - // we recommend that you create a separate health check for each endpoint. For - // example, create a health check for each HTTP server that is serving content - // for www.example.com. For the value of FullyQualifiedDomainName, specify the - // domain name of the server (such as us-east-2-www.example.com), not the name - // of the resource record sets (www.example.com). - // - // In this configuration, if you create a health check for which the value of - // FullyQualifiedDomainName matches the name of the resource record sets and - // you then associate the health check with those resource record sets, health - // check results will be unpredictable. - // - // In addition, if the value that you specify for Type is HTTP, HTTPS, HTTP_STR_MATCH, - // or HTTPS_STR_MATCH, Amazon Route 53 passes the value of FullyQualifiedDomainName - // in the Host header, as it does when you specify a value for IPAddress. If - // the value of Type is TCP, Amazon Route 53 doesn't pass a Host header. - FullyQualifiedDomainName *string `type:"string"` - - // The number of child health checks that are associated with a CALCULATED health - // that Amazon Route 53 must consider healthy for the CALCULATED health check - // to be considered healthy. To specify the child health checks that you want - // to associate with a CALCULATED health check, use the HealthCheckConfig$ChildHealthChecks - // and HealthCheckConfig$ChildHealthChecks elements. - // - // Note the following: - // - // * If you specify a number greater than the number of child health checks, - // Amazon Route 53 always considers this health check to be unhealthy. - // - // * If you specify 0, Amazon Route 53 always considers this health check - // to be healthy. - HealthThreshold *int64 `type:"integer"` - - // The IPv4 or IPv6 IP address of the endpoint that you want Amazon Route 53 - // to perform health checks on. If you don't specify a value for IPAddress, - // Amazon Route 53 sends a DNS request to resolve the domain name that you specify - // in FullyQualifiedDomainName at the interval that you specify in RequestInterval. - // Using an IP address returned by DNS, Amazon Route 53 then checks the health - // of the endpoint. - // - // Use one of the following formats for the value of IPAddress: - // - // * IPv4 address: four values between 0 and 255, separated by periods (.), - // for example, 192.0.2.44. - // - // * IPv6 address: eight groups of four hexadecimal values, separated by - // colons (:), for example, 2001:0db8:85a3:0000:0000:abcd:0001:2345. You - // can also shorten IPv6 addresses as described in RFC 5952, for example, - // 2001:db8:85a3::abcd:1:2345. - // - // If the endpoint is an EC2 instance, we recommend that you create an Elastic - // IP address, associate it with your EC2 instance, and specify the Elastic - // IP address for IPAddress. This ensures that the IP address of your instance - // will never change. - // - // For more information, see HealthCheckConfig$FullyQualifiedDomainName. - // - // Constraints: Amazon Route 53 can't check the health of endpoints for which - // the IP address is in local, private, non-routable, or multicast ranges. For - // more information about IP addresses for which you can't create health checks, - // see the following documents: - // - // * RFC 5735, Special Use IPv4 Addresses (https://tools.ietf.org/html/rfc5735) - // - // * RFC 6598, IANA-Reserved IPv4 Prefix for Shared Address Space (https://tools.ietf.org/html/rfc6598) - // - // * RFC 5156, Special-Use IPv6 Addresses (https://tools.ietf.org/html/rfc5156) - // - // When the value of Type is CALCULATED or CLOUDWATCH_METRIC, omit IPAddress. - IPAddress *string `type:"string"` - - // When CloudWatch has insufficient data about the metric to determine the alarm - // state, the status that you want Amazon Route 53 to assign to the health check: - // - // * Healthy: Amazon Route 53 considers the health check to be healthy. - // - // * Unhealthy: Amazon Route 53 considers the health check to be unhealthy. - // - // * LastKnownStatus: Amazon Route 53 uses the status of the health check - // from the last time that CloudWatch had sufficient data to determine the - // alarm state. For new health checks that have no last known status, the - // default status for the health check is healthy. - InsufficientDataHealthStatus *string `type:"string" enum:"InsufficientDataHealthStatus"` - - // Specify whether you want Amazon Route 53 to invert the status of a health - // check, for example, to consider a health check unhealthy when it otherwise - // would be considered healthy. - Inverted *bool `type:"boolean"` - - // Specify whether you want Amazon Route 53 to measure the latency between health - // checkers in multiple AWS regions and your endpoint, and to display CloudWatch - // latency graphs on the Health Checks page in the Amazon Route 53 console. - // - // You can't change the value of MeasureLatency after you create a health check. - MeasureLatency *bool `type:"boolean"` - - // The port on the endpoint on which you want Amazon Route 53 to perform health - // checks. Specify a value for Port only when you specify a value for IPAddress. - Port *int64 `min:"1" type:"integer"` - - // A complex type that contains one Region element for each region from which - // you want Amazon Route 53 health checkers to check the specified endpoint. - // - // If you don't specify any regions, Amazon Route 53 health checkers automatically - // performs checks from all of the regions that are listed under Valid Values. - // - // If you update a health check to remove a region that has been performing - // health checks, Amazon Route 53 will briefly continue to perform checks from - // that region to ensure that some health checkers are always checking the endpoint - // (for example, if you replace three regions with four different regions). - Regions []*string `locationNameList:"Region" min:"3" type:"list"` - - // The number of seconds between the time that Amazon Route 53 gets a response - // from your endpoint and the time that it sends the next health check request. - // Each Amazon Route 53 health checker makes requests at this interval. - // - // You can't change the value of RequestInterval after you create a health check. - // - // If you don't specify a value for RequestInterval, the default value is 30 - // seconds. - RequestInterval *int64 `min:"10" type:"integer"` - - // The path, if any, that you want Amazon Route 53 to request when performing - // health checks. The path can be any value for which your endpoint will return - // an HTTP status code of 2xx or 3xx when the endpoint is healthy, for example, - // the file /docs/route53-health-check.html. - ResourcePath *string `type:"string"` - - // If the value of Type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that - // you want Amazon Route 53 to search for in the response body from the specified - // resource. If the string appears in the response body, Amazon Route 53 considers - // the resource healthy. - // - // Amazon Route 53 considers case when searching for SearchString in the response - // body. - SearchString *string `type:"string"` - - // The type of health check that you want to create, which indicates how Amazon - // Route 53 determines whether an endpoint is healthy. - // - // You can't change the value of Type after you create a health check. - // - // You can create the following types of health checks: - // - // * HTTP: Amazon Route 53 tries to establish a TCP connection. If successful, - // Amazon Route 53 submits an HTTP request and waits for an HTTP status code - // of 200 or greater and less than 400. - // - // * HTTPS: Amazon Route 53 tries to establish a TCP connection. If successful, - // Amazon Route 53 submits an HTTPS request and waits for an HTTP status - // code of 200 or greater and less than 400. - // - // If you specify HTTPS for the value of Type, the endpoint must support TLS - // v1.0 or later. - // - // * HTTP_STR_MATCH: Amazon Route 53 tries to establish a TCP connection. - // If successful, Amazon Route 53 submits an HTTP request and searches the - // first 5,120 bytes of the response body for the string that you specify - // in SearchString. - // - // * HTTPS_STR_MATCH: Amazon Route 53 tries to establish a TCP connection. - // If successful, Amazon Route 53 submits an HTTPS request and searches the - // first 5,120 bytes of the response body for the string that you specify - // in SearchString. - // - // * TCP: Amazon Route 53 tries to establish a TCP connection. - // - // * CLOUDWATCH_METRIC: The health check is associated with a CloudWatch - // alarm. If the state of the alarm is OK, the health check is considered - // healthy. If the state is ALARM, the health check is considered unhealthy. - // If CloudWatch doesn't have sufficient data to determine whether the state - // is OK or ALARM, the health check status depends on the setting for InsufficientDataHealthStatus: - // Healthy, Unhealthy, or LastKnownStatus. - // - // * CALCULATED: For health checks that monitor the status of other health - // checks, Amazon Route 53 adds up the number of health checks that Amazon - // Route 53 health checkers consider to be healthy and compares that number - // with the value of HealthThreshold. - // - // For more information, see How Amazon Route 53 Determines Whether an Endpoint - // Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"HealthCheckType"` -} - -// String returns the string representation -func (s HealthCheckConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheckConfig) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *HealthCheckConfig) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "HealthCheckConfig"} - if s.FailureThreshold != nil && *s.FailureThreshold < 1 { - invalidParams.Add(request.NewErrParamMinValue("FailureThreshold", 1)) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } - if s.Regions != nil && len(s.Regions) < 3 { - invalidParams.Add(request.NewErrParamMinLen("Regions", 3)) - } - if s.RequestInterval != nil && *s.RequestInterval < 10 { - invalidParams.Add(request.NewErrParamMinValue("RequestInterval", 10)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.AlarmIdentifier != nil { - if err := s.AlarmIdentifier.Validate(); err != nil { - invalidParams.AddNested("AlarmIdentifier", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAlarmIdentifier sets the AlarmIdentifier field's value. -func (s *HealthCheckConfig) SetAlarmIdentifier(v *AlarmIdentifier) *HealthCheckConfig { - s.AlarmIdentifier = v - return s -} - -// SetChildHealthChecks sets the ChildHealthChecks field's value. -func (s *HealthCheckConfig) SetChildHealthChecks(v []*string) *HealthCheckConfig { - s.ChildHealthChecks = v - return s -} - -// SetEnableSNI sets the EnableSNI field's value. -func (s *HealthCheckConfig) SetEnableSNI(v bool) *HealthCheckConfig { - s.EnableSNI = &v - return s -} - -// SetFailureThreshold sets the FailureThreshold field's value. -func (s *HealthCheckConfig) SetFailureThreshold(v int64) *HealthCheckConfig { - s.FailureThreshold = &v - return s -} - -// SetFullyQualifiedDomainName sets the FullyQualifiedDomainName field's value. -func (s *HealthCheckConfig) SetFullyQualifiedDomainName(v string) *HealthCheckConfig { - s.FullyQualifiedDomainName = &v - return s -} - -// SetHealthThreshold sets the HealthThreshold field's value. -func (s *HealthCheckConfig) SetHealthThreshold(v int64) *HealthCheckConfig { - s.HealthThreshold = &v - return s -} - -// SetIPAddress sets the IPAddress field's value. -func (s *HealthCheckConfig) SetIPAddress(v string) *HealthCheckConfig { - s.IPAddress = &v - return s -} - -// SetInsufficientDataHealthStatus sets the InsufficientDataHealthStatus field's value. -func (s *HealthCheckConfig) SetInsufficientDataHealthStatus(v string) *HealthCheckConfig { - s.InsufficientDataHealthStatus = &v - return s -} - -// SetInverted sets the Inverted field's value. -func (s *HealthCheckConfig) SetInverted(v bool) *HealthCheckConfig { - s.Inverted = &v - return s -} - -// SetMeasureLatency sets the MeasureLatency field's value. -func (s *HealthCheckConfig) SetMeasureLatency(v bool) *HealthCheckConfig { - s.MeasureLatency = &v - return s -} - -// SetPort sets the Port field's value. -func (s *HealthCheckConfig) SetPort(v int64) *HealthCheckConfig { - s.Port = &v - return s -} - -// SetRegions sets the Regions field's value. -func (s *HealthCheckConfig) SetRegions(v []*string) *HealthCheckConfig { - s.Regions = v - return s -} - -// SetRequestInterval sets the RequestInterval field's value. -func (s *HealthCheckConfig) SetRequestInterval(v int64) *HealthCheckConfig { - s.RequestInterval = &v - return s -} - -// SetResourcePath sets the ResourcePath field's value. -func (s *HealthCheckConfig) SetResourcePath(v string) *HealthCheckConfig { - s.ResourcePath = &v - return s -} - -// SetSearchString sets the SearchString field's value. -func (s *HealthCheckConfig) SetSearchString(v string) *HealthCheckConfig { - s.SearchString = &v - return s -} - -// SetType sets the Type field's value. -func (s *HealthCheckConfig) SetType(v string) *HealthCheckConfig { - s.Type = &v - return s -} - -// A complex type that contains the last failure reason as reported by one Amazon -// Route 53 health checker. -type HealthCheckObservation struct { - _ struct{} `type:"structure"` - - // The IP address of the Amazon Route 53 health checker that provided the failure - // reason in StatusReport. - IPAddress *string `type:"string"` - - // The region of the Amazon Route 53 health checker that provided the status - // in StatusReport. - Region *string `min:"1" type:"string" enum:"HealthCheckRegion"` - - // A complex type that contains the last failure reason as reported by one Amazon - // Route 53 health checker and the time of the failed health check. - StatusReport *StatusReport `type:"structure"` -} - -// String returns the string representation -func (s HealthCheckObservation) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HealthCheckObservation) GoString() string { - return s.String() -} - -// SetIPAddress sets the IPAddress field's value. -func (s *HealthCheckObservation) SetIPAddress(v string) *HealthCheckObservation { - s.IPAddress = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *HealthCheckObservation) SetRegion(v string) *HealthCheckObservation { - s.Region = &v - return s -} - -// SetStatusReport sets the StatusReport field's value. -func (s *HealthCheckObservation) SetStatusReport(v *StatusReport) *HealthCheckObservation { - s.StatusReport = v - return s -} - -// A complex type that contains general information about the hosted zone. -type HostedZone struct { - _ struct{} `type:"structure"` - - // The value that you specified for CallerReference when you created the hosted - // zone. - // - // CallerReference is a required field - CallerReference *string `min:"1" type:"string" required:"true"` - - // A complex type that includes the Comment and PrivateZone elements. If you - // omitted the HostedZoneConfig and Comment elements from the request, the Config - // and Comment elements don't appear in the response. - Config *HostedZoneConfig `type:"structure"` - - // The ID that Amazon Route 53 assigned to the hosted zone when you created - // it. - // - // Id is a required field - Id *string `type:"string" required:"true"` - - // If the hosted zone was created by another service, the service that created - // the hosted zone. When a hosted zone is created by another service, you can't - // edit or delete it using Amazon Route 53. - LinkedService *LinkedService `type:"structure"` - - // The name of the domain. For public hosted zones, this is the name that you - // have registered with your DNS registrar. - // - // For information about how to specify characters other than a-z, 0-9, and - // - (hyphen) and how to specify internationalized domain names, see CreateHostedZone. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The number of resource record sets in the hosted zone. - ResourceRecordSetCount *int64 `type:"long"` -} - -// String returns the string representation -func (s HostedZone) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZone) GoString() string { - return s.String() -} - -// SetCallerReference sets the CallerReference field's value. -func (s *HostedZone) SetCallerReference(v string) *HostedZone { - s.CallerReference = &v - return s -} - -// SetConfig sets the Config field's value. -func (s *HostedZone) SetConfig(v *HostedZoneConfig) *HostedZone { - s.Config = v - return s -} - -// SetId sets the Id field's value. -func (s *HostedZone) SetId(v string) *HostedZone { - s.Id = &v - return s -} - -// SetLinkedService sets the LinkedService field's value. -func (s *HostedZone) SetLinkedService(v *LinkedService) *HostedZone { - s.LinkedService = v - return s -} - -// SetName sets the Name field's value. -func (s *HostedZone) SetName(v string) *HostedZone { - s.Name = &v - return s -} - -// SetResourceRecordSetCount sets the ResourceRecordSetCount field's value. -func (s *HostedZone) SetResourceRecordSetCount(v int64) *HostedZone { - s.ResourceRecordSetCount = &v - return s -} - -// A complex type that contains an optional comment about your hosted zone. -// If you don't want to specify a comment, omit both the HostedZoneConfig and -// Comment elements. -type HostedZoneConfig struct { - _ struct{} `type:"structure"` - - // Any comments that you want to include about the hosted zone. - Comment *string `type:"string"` - - // A value that indicates whether this is a private hosted zone. - PrivateZone *bool `type:"boolean"` -} - -// String returns the string representation -func (s HostedZoneConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZoneConfig) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *HostedZoneConfig) SetComment(v string) *HostedZoneConfig { - s.Comment = &v - return s -} - -// SetPrivateZone sets the PrivateZone field's value. -func (s *HostedZoneConfig) SetPrivateZone(v bool) *HostedZoneConfig { - s.PrivateZone = &v - return s -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type HostedZoneLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested. Valid values include the following: - // - // * MAX_RRSETS_BY_ZONE: The maximum number of records that you can create - // in the specified hosted zone. - // - // * MAX_VPCS_ASSOCIATED_BY_ZONE: The maximum number of Amazon VPCs that - // you can associate with the specified private hosted zone. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"HostedZoneLimitType"` - - // The current value for the limit that is specified by Type. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s HostedZoneLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s HostedZoneLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *HostedZoneLimit) SetType(v string) *HostedZoneLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *HostedZoneLimit) SetValue(v int64) *HostedZoneLimit { - s.Value = &v - return s -} - -// If a health check or hosted zone was created by another service, LinkedService -// is a complex type that describes the service that created the resource. When -// a resource is created by another service, you can't edit or delete it using -// Amazon Route 53. -type LinkedService struct { - _ struct{} `type:"structure"` - - // If the health check or hosted zone was created by another service, an optional - // description that can be provided by the other service. When a resource is - // created by another service, you can't edit or delete it using Amazon Route - // 53. - Description *string `type:"string"` - - // If the health check or hosted zone was created by another service, the service - // that created the resource. When a resource is created by another service, - // you can't edit or delete it using Amazon Route 53. - ServicePrincipal *string `type:"string"` -} - -// String returns the string representation -func (s LinkedService) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s LinkedService) GoString() string { - return s.String() -} - -// SetDescription sets the Description field's value. -func (s *LinkedService) SetDescription(v string) *LinkedService { - s.Description = &v - return s -} - -// SetServicePrincipal sets the ServicePrincipal field's value. -func (s *LinkedService) SetServicePrincipal(v string) *LinkedService { - s.ServicePrincipal = &v - return s -} - -// A request to get a list of geographic locations that Amazon Route 53 supports -// for geolocation resource record sets. -type ListGeoLocationsInput struct { - _ struct{} `type:"structure"` - - // (Optional) The maximum number of geolocations to be included in the response - // body for this request. If more than MaxItems geolocations remain to be listed, - // then the value of the IsTruncated element in the response is true. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // The code for the continent with which you want to start listing locations - // that Amazon Route 53 supports for geolocation. If Amazon Route 53 has already - // returned a page or more of results, if IsTruncated is true, and if NextContinentCode - // from the previous response has a value, enter that value in StartContinentCode - // to return the next page of results. - // - // Include StartContinentCode only if you want to list continents. Don't include - // StartContinentCode when you're listing countries or countries with their - // subdivisions. - StartContinentCode *string `location:"querystring" locationName:"startcontinentcode" min:"2" type:"string"` - - // The code for the country with which you want to start listing locations that - // Amazon Route 53 supports for geolocation. If Amazon Route 53 has already - // returned a page or more of results, if IsTruncated is true, and if NextCountryCode - // from the previous response has a value, enter that value in StartCountryCode - // to return the next page of results. - // - // Amazon Route 53 uses the two-letter country codes that are specified in ISO - // standard 3166-1 alpha-2 (https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2). - StartCountryCode *string `location:"querystring" locationName:"startcountrycode" min:"1" type:"string"` - - // The code for the subdivision (for example, state or province) with which - // you want to start listing locations that Amazon Route 53 supports for geolocation. - // If Amazon Route 53 has already returned a page or more of results, if IsTruncated - // is true, and if NextSubdivisionCode from the previous response has a value, - // enter that value in StartSubdivisionCode to return the next page of results. - // - // To list subdivisions of a country, you must include both StartCountryCode - // and StartSubdivisionCode. - StartSubdivisionCode *string `location:"querystring" locationName:"startsubdivisioncode" min:"1" type:"string"` -} - -// String returns the string representation -func (s ListGeoLocationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListGeoLocationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListGeoLocationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListGeoLocationsInput"} - if s.StartContinentCode != nil && len(*s.StartContinentCode) < 2 { - invalidParams.Add(request.NewErrParamMinLen("StartContinentCode", 2)) - } - if s.StartCountryCode != nil && len(*s.StartCountryCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartCountryCode", 1)) - } - if s.StartSubdivisionCode != nil && len(*s.StartSubdivisionCode) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartSubdivisionCode", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListGeoLocationsInput) SetMaxItems(v string) *ListGeoLocationsInput { - s.MaxItems = &v - return s -} - -// SetStartContinentCode sets the StartContinentCode field's value. -func (s *ListGeoLocationsInput) SetStartContinentCode(v string) *ListGeoLocationsInput { - s.StartContinentCode = &v - return s -} - -// SetStartCountryCode sets the StartCountryCode field's value. -func (s *ListGeoLocationsInput) SetStartCountryCode(v string) *ListGeoLocationsInput { - s.StartCountryCode = &v - return s -} - -// SetStartSubdivisionCode sets the StartSubdivisionCode field's value. -func (s *ListGeoLocationsInput) SetStartSubdivisionCode(v string) *ListGeoLocationsInput { - s.StartSubdivisionCode = &v - return s -} - -// A complex type containing the response information for the request. -type ListGeoLocationsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one GeoLocationDetails element for each location - // that Amazon Route 53 supports for geolocation. - // - // GeoLocationDetailsList is a required field - GeoLocationDetailsList []*GeoLocationDetails `locationNameList:"GeoLocationDetails" type:"list" required:"true"` - - // A value that indicates whether more locations remain to be listed after the - // last location in this response. If so, the value of IsTruncated is true. - // To get more values, submit another request and include the values of NextContinentCode, - // NextCountryCode, and NextSubdivisionCode in the StartContinentCode, StartCountryCode, - // and StartSubdivisionCode, as applicable. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for MaxItems in the request. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextContinentCode in the StartContinentCode - // parameter in another ListGeoLocations request. - NextContinentCode *string `min:"2" type:"string"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextCountryCode in the StartCountryCode parameter - // in another ListGeoLocations request. - NextCountryCode *string `min:"1" type:"string"` - - // If IsTruncated is true, you can make a follow-up request to display more - // locations. Enter the value of NextSubdivisionCode in the StartSubdivisionCode - // parameter in another ListGeoLocations request. - NextSubdivisionCode *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s ListGeoLocationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListGeoLocationsOutput) GoString() string { - return s.String() -} - -// SetGeoLocationDetailsList sets the GeoLocationDetailsList field's value. -func (s *ListGeoLocationsOutput) SetGeoLocationDetailsList(v []*GeoLocationDetails) *ListGeoLocationsOutput { - s.GeoLocationDetailsList = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListGeoLocationsOutput) SetIsTruncated(v bool) *ListGeoLocationsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListGeoLocationsOutput) SetMaxItems(v string) *ListGeoLocationsOutput { - s.MaxItems = &v - return s -} - -// SetNextContinentCode sets the NextContinentCode field's value. -func (s *ListGeoLocationsOutput) SetNextContinentCode(v string) *ListGeoLocationsOutput { - s.NextContinentCode = &v - return s -} - -// SetNextCountryCode sets the NextCountryCode field's value. -func (s *ListGeoLocationsOutput) SetNextCountryCode(v string) *ListGeoLocationsOutput { - s.NextCountryCode = &v - return s -} - -// SetNextSubdivisionCode sets the NextSubdivisionCode field's value. -func (s *ListGeoLocationsOutput) SetNextSubdivisionCode(v string) *ListGeoLocationsOutput { - s.NextSubdivisionCode = &v - return s -} - -// A request to retrieve a list of the health checks that are associated with -// the current AWS account. -type ListHealthChecksInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // health checks. To get another group, submit another ListHealthChecks request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first health check that Amazon Route 53 - // will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more health checks to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // The maximum number of health checks that you want ListHealthChecks to return - // in response to the current request. Amazon Route 53 returns a maximum of - // 100 items. If you set MaxItems to a value greater than 100, Amazon Route - // 53 returns only the first 100 health checks. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHealthChecksInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHealthChecksInput) GoString() string { - return s.String() -} - -// SetMarker sets the Marker field's value. -func (s *ListHealthChecksInput) SetMarker(v string) *ListHealthChecksInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHealthChecksInput) SetMaxItems(v string) *ListHealthChecksInput { - s.MaxItems = &v - return s -} - -// A complex type that contains the response to a ListHealthChecks request. -type ListHealthChecksOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one HealthCheck element for each health check - // that is associated with the current AWS account. - // - // HealthChecks is a required field - HealthChecks []*HealthCheck `locationNameList:"HealthCheck" type:"list" required:"true"` - - // A flag that indicates whether there are more health checks to be listed. - // If the response was truncated, you can get the next group of health checks - // by submitting another ListHealthChecks request and specifying the value of - // NextMarker in the marker parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListHealthChecks, Marker is the value - // that you specified for the marker parameter in the previous request. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHealthChecks - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the first health - // check that Amazon Route 53 returns if you submit another ListHealthChecks - // request and specify the value of NextMarker in the marker parameter. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListHealthChecksOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHealthChecksOutput) GoString() string { - return s.String() -} - -// SetHealthChecks sets the HealthChecks field's value. -func (s *ListHealthChecksOutput) SetHealthChecks(v []*HealthCheck) *ListHealthChecksOutput { - s.HealthChecks = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHealthChecksOutput) SetIsTruncated(v bool) *ListHealthChecksOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHealthChecksOutput) SetMarker(v string) *ListHealthChecksOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHealthChecksOutput) SetMaxItems(v string) *ListHealthChecksOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListHealthChecksOutput) SetNextMarker(v string) *ListHealthChecksOutput { - s.NextMarker = &v - return s -} - -// Retrieves a list of the public and private hosted zones that are associated -// with the current AWS account in ASCII order by domain name. -type ListHostedZonesByNameInput struct { - _ struct{} `type:"structure"` - - // (Optional) For your first request to ListHostedZonesByName, include the dnsname - // parameter only if you want to specify the name of the first hosted zone in - // the response. If you don't include the dnsname parameter, Amazon Route 53 - // returns all of the hosted zones that were created by the current AWS account, - // in ASCII order. For subsequent requests, include both dnsname and hostedzoneid - // parameters. For dnsname, specify the value of NextDNSName from the previous - // response. - DNSName *string `location:"querystring" locationName:"dnsname" type:"string"` - - // (Optional) For your first request to ListHostedZonesByName, do not include - // the hostedzoneid parameter. - // - // If you have more hosted zones than the value of maxitems, ListHostedZonesByName - // returns only the first maxitems hosted zones. To get the next group of maxitems - // hosted zones, submit another request to ListHostedZonesByName and include - // both dnsname and hostedzoneid parameters. For the value of hostedzoneid, - // specify the value of the NextHostedZoneId element from the previous response. - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of hosted zones to be included in the response body for - // this request. If you have more than maxitems hosted zones, then the value - // of the IsTruncated element in the response is true, and the values of NextDNSName - // and NextHostedZoneId specify the first hosted zone in the next group of maxitems - // hosted zones. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesByNameInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesByNameInput) GoString() string { - return s.String() -} - -// SetDNSName sets the DNSName field's value. -func (s *ListHostedZonesByNameInput) SetDNSName(v string) *ListHostedZonesByNameInput { - s.DNSName = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListHostedZonesByNameInput) SetHostedZoneId(v string) *ListHostedZonesByNameInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesByNameInput) SetMaxItems(v string) *ListHostedZonesByNameInput { - s.MaxItems = &v - return s -} - -// A complex type that contains the response information for the request. -type ListHostedZonesByNameOutput struct { - _ struct{} `type:"structure"` - - // For the second and subsequent calls to ListHostedZonesByName, DNSName is - // the value that you specified for the dnsname parameter in the request that - // produced the current response. - DNSName *string `type:"string"` - - // The ID that Amazon Route 53 assigned to the hosted zone when you created - // it. - HostedZoneId *string `type:"string"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZones is a required field - HostedZones []*HostedZone `locationNameList:"HostedZone" type:"list" required:"true"` - - // A flag that indicates whether there are more hosted zones to be listed. If - // the response was truncated, you can get the next group of maxitems hosted - // zones by calling ListHostedZonesByName again and specifying the values of - // NextDNSName and NextHostedZoneId elements in the dnsname and hostedzoneid - // parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHostedZonesByName - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextDNSName is the name of the first - // hosted zone in the next group of maxitems hosted zones. Call ListHostedZonesByName - // again and specify the value of NextDNSName and NextHostedZoneId in the dnsname - // and hostedzoneid parameters, respectively. - // - // This element is present only if IsTruncated is true. - NextDNSName *string `type:"string"` - - // If IsTruncated is true, the value of NextHostedZoneId identifies the first - // hosted zone in the next group of maxitems hosted zones. Call ListHostedZonesByName - // again and specify the value of NextDNSName and NextHostedZoneId in the dnsname - // and hostedzoneid parameters, respectively. - // - // This element is present only if IsTruncated is true. - NextHostedZoneId *string `type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesByNameOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesByNameOutput) GoString() string { - return s.String() -} - -// SetDNSName sets the DNSName field's value. -func (s *ListHostedZonesByNameOutput) SetDNSName(v string) *ListHostedZonesByNameOutput { - s.DNSName = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListHostedZonesByNameOutput) SetHostedZoneId(v string) *ListHostedZonesByNameOutput { - s.HostedZoneId = &v - return s -} - -// SetHostedZones sets the HostedZones field's value. -func (s *ListHostedZonesByNameOutput) SetHostedZones(v []*HostedZone) *ListHostedZonesByNameOutput { - s.HostedZones = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHostedZonesByNameOutput) SetIsTruncated(v bool) *ListHostedZonesByNameOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesByNameOutput) SetMaxItems(v string) *ListHostedZonesByNameOutput { - s.MaxItems = &v - return s -} - -// SetNextDNSName sets the NextDNSName field's value. -func (s *ListHostedZonesByNameOutput) SetNextDNSName(v string) *ListHostedZonesByNameOutput { - s.NextDNSName = &v - return s -} - -// SetNextHostedZoneId sets the NextHostedZoneId field's value. -func (s *ListHostedZonesByNameOutput) SetNextHostedZoneId(v string) *ListHostedZonesByNameOutput { - s.NextHostedZoneId = &v - return s -} - -// A request to retrieve a list of the public and private hosted zones that -// are associated with the current AWS account. -type ListHostedZonesInput struct { - _ struct{} `type:"structure"` - - // If you're using reusable delegation sets and you want to list all of the - // hosted zones that are associated with a reusable delegation set, specify - // the ID of that reusable delegation set. - DelegationSetId *string `location:"querystring" locationName:"delegationsetid" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // hosted zones. To get more hosted zones, submit another ListHostedZones request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first hosted zone that Amazon Route 53 will - // return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more hosted zones to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // (Optional) The maximum number of hosted zones that you want Amazon Route - // 53 to return. If you have more than maxitems hosted zones, the value of IsTruncated - // in the response is true, and the value of NextMarker is the hosted zone ID - // of the first hosted zone that Amazon Route 53 will return if you submit another - // request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesInput) GoString() string { - return s.String() -} - -// SetDelegationSetId sets the DelegationSetId field's value. -func (s *ListHostedZonesInput) SetDelegationSetId(v string) *ListHostedZonesInput { - s.DelegationSetId = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHostedZonesInput) SetMarker(v string) *ListHostedZonesInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesInput) SetMaxItems(v string) *ListHostedZonesInput { - s.MaxItems = &v - return s -} - -type ListHostedZonesOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZones is a required field - HostedZones []*HostedZone `locationNameList:"HostedZone" type:"list" required:"true"` - - // A flag indicating whether there are more hosted zones to be listed. If the - // response was truncated, you can get more hosted zones by submitting another - // ListHostedZones request and specifying the value of NextMarker in the marker - // parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListHostedZones, Marker is the value - // that you specified for the marker parameter in the request that produced - // the current response. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListHostedZones - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the first hosted - // zone in the next group of hosted zones. Submit another ListHostedZones request, - // and specify the value of NextMarker from the response in the marker parameter. - // - // This element is present only if IsTruncated is true. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListHostedZonesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListHostedZonesOutput) GoString() string { - return s.String() -} - -// SetHostedZones sets the HostedZones field's value. -func (s *ListHostedZonesOutput) SetHostedZones(v []*HostedZone) *ListHostedZonesOutput { - s.HostedZones = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListHostedZonesOutput) SetIsTruncated(v bool) *ListHostedZonesOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListHostedZonesOutput) SetMarker(v string) *ListHostedZonesOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListHostedZonesOutput) SetMaxItems(v string) *ListHostedZonesOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListHostedZonesOutput) SetNextMarker(v string) *ListHostedZonesOutput { - s.NextMarker = &v - return s -} - -type ListQueryLoggingConfigsInput struct { - _ struct{} `type:"structure"` - - // (Optional) If you want to list the query logging configuration that is associated - // with a hosted zone, specify the ID in HostedZoneId. - // - // If you don't specify a hosted zone ID, ListQueryLoggingConfigs returns all - // of the configurations that are associated with the current AWS account. - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // (Optional) The maximum number of query logging configurations that you want - // Amazon Route 53 to return in response to the current request. If the current - // AWS account has more than MaxResults configurations, use the value of ListQueryLoggingConfigsResponse$NextToken - // in the response to get the next page of results. - // - // If you don't specify a value for MaxResults, Amazon Route 53 returns up to - // 100 configurations. - MaxResults *string `location:"querystring" locationName:"maxresults" type:"string"` - - // (Optional) If the current AWS account has more than MaxResults query logging - // configurations, use NextToken to get the second and subsequent pages of results. - // - // For the first ListQueryLoggingConfigs request, omit this value. - // - // For the second and subsequent requests, get the value of NextToken from the - // previous response and specify that value for NextToken in the request. - NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` -} - -// String returns the string representation -func (s ListQueryLoggingConfigsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListQueryLoggingConfigsInput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListQueryLoggingConfigsInput) SetHostedZoneId(v string) *ListQueryLoggingConfigsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListQueryLoggingConfigsInput) SetMaxResults(v string) *ListQueryLoggingConfigsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListQueryLoggingConfigsInput) SetNextToken(v string) *ListQueryLoggingConfigsInput { - s.NextToken = &v - return s -} - -type ListQueryLoggingConfigsOutput struct { - _ struct{} `type:"structure"` - - // If a response includes the last of the query logging configurations that - // are associated with the current AWS account, NextToken doesn't appear in - // the response. - // - // If a response doesn't include the last of the configurations, you can get - // more configurations by submitting another ListQueryLoggingConfigs request. - // Get the value of NextToken that Amazon Route 53 returned in the previous - // response and include it in NextToken in the next request. - NextToken *string `type:"string"` - - // An array that contains one QueryLoggingConfig element for each configuration - // for DNS query logging that is associated with the current AWS account. - // - // QueryLoggingConfigs is a required field - QueryLoggingConfigs []*QueryLoggingConfig `locationNameList:"QueryLoggingConfig" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListQueryLoggingConfigsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListQueryLoggingConfigsOutput) GoString() string { - return s.String() -} - -// SetNextToken sets the NextToken field's value. -func (s *ListQueryLoggingConfigsOutput) SetNextToken(v string) *ListQueryLoggingConfigsOutput { - s.NextToken = &v - return s -} - -// SetQueryLoggingConfigs sets the QueryLoggingConfigs field's value. -func (s *ListQueryLoggingConfigsOutput) SetQueryLoggingConfigs(v []*QueryLoggingConfig) *ListQueryLoggingConfigsOutput { - s.QueryLoggingConfigs = v - return s -} - -// A request for the resource record sets that are associated with a specified -// hosted zone. -type ListResourceRecordSetsInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that contains the resource record sets that you - // want to list. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // (Optional) The maximum number of resource records sets to include in the - // response body for this request. If the response includes more than maxitems - // resource record sets, the value of the IsTruncated element in the response - // is true, and the values of the NextRecordName and NextRecordType elements - // in the response identify the first resource record set in the next group - // of maxitems resource record sets. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // Weighted resource record sets only: If results were truncated for a given - // DNS name and type, specify the value of NextRecordIdentifier from the previous - // response to get the next resource record set that has the current DNS name - // and type. - StartRecordIdentifier *string `location:"querystring" locationName:"identifier" min:"1" type:"string"` - - // The first name in the lexicographic ordering of resource record sets that - // you want to list. - StartRecordName *string `location:"querystring" locationName:"name" type:"string"` - - // The type of resource record set to begin the record listing from. - // - // Valid values for basic resource record sets: A | AAAA | CAA | CNAME | MX - // | NAPTR | NS | PTR | SOA | SPF | SRV | TXT - // - // Values for weighted, latency, geo, and failover resource record sets: A | - // AAAA | CAA | CNAME | MX | NAPTR | PTR | SPF | SRV | TXT - // - // Values for alias resource record sets: - // - // * CloudFront distribution: A or AAAA - // - // * Elastic Beanstalk environment that has a regionalized subdomain: A - // - // * ELB load balancer: A | AAAA - // - // * Amazon S3 bucket: A - // - // * Another resource record set in this hosted zone: The type of the resource - // record set that the alias references. - // - // Constraint: Specifying type without specifying name returns an InvalidInput - // error. - StartRecordType *string `location:"querystring" locationName:"type" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListResourceRecordSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListResourceRecordSetsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListResourceRecordSetsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListResourceRecordSetsInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.StartRecordIdentifier != nil && len(*s.StartRecordIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("StartRecordIdentifier", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListResourceRecordSetsInput) SetHostedZoneId(v string) *ListResourceRecordSetsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListResourceRecordSetsInput) SetMaxItems(v string) *ListResourceRecordSetsInput { - s.MaxItems = &v - return s -} - -// SetStartRecordIdentifier sets the StartRecordIdentifier field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordIdentifier(v string) *ListResourceRecordSetsInput { - s.StartRecordIdentifier = &v - return s -} - -// SetStartRecordName sets the StartRecordName field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordName(v string) *ListResourceRecordSetsInput { - s.StartRecordName = &v - return s -} - -// SetStartRecordType sets the StartRecordType field's value. -func (s *ListResourceRecordSetsInput) SetStartRecordType(v string) *ListResourceRecordSetsInput { - s.StartRecordType = &v - return s -} - -// A complex type that contains list information for the resource record set. -type ListResourceRecordSetsOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether more resource record sets remain to be listed. - // If your results were truncated, you can make a follow-up pagination request - // by using the NextRecordName element. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The maximum number of records you requested. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // Weighted, latency, geolocation, and failover resource record sets only: If - // results were truncated for a given DNS name and type, the value of SetIdentifier - // for the next resource record set that has the current DNS name and type. - NextRecordIdentifier *string `min:"1" type:"string"` - - // If the results were truncated, the name of the next record in the list. - // - // This element is present only if IsTruncated is true. - NextRecordName *string `type:"string"` - - // If the results were truncated, the type of the next record in the list. - // - // This element is present only if IsTruncated is true. - NextRecordType *string `type:"string" enum:"RRType"` - - // Information about multiple resource record sets. - // - // ResourceRecordSets is a required field - ResourceRecordSets []*ResourceRecordSet `locationNameList:"ResourceRecordSet" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListResourceRecordSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListResourceRecordSetsOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListResourceRecordSetsOutput) SetIsTruncated(v bool) *ListResourceRecordSetsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListResourceRecordSetsOutput) SetMaxItems(v string) *ListResourceRecordSetsOutput { - s.MaxItems = &v - return s -} - -// SetNextRecordIdentifier sets the NextRecordIdentifier field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordIdentifier(v string) *ListResourceRecordSetsOutput { - s.NextRecordIdentifier = &v - return s -} - -// SetNextRecordName sets the NextRecordName field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordName(v string) *ListResourceRecordSetsOutput { - s.NextRecordName = &v - return s -} - -// SetNextRecordType sets the NextRecordType field's value. -func (s *ListResourceRecordSetsOutput) SetNextRecordType(v string) *ListResourceRecordSetsOutput { - s.NextRecordType = &v - return s -} - -// SetResourceRecordSets sets the ResourceRecordSets field's value. -func (s *ListResourceRecordSetsOutput) SetResourceRecordSets(v []*ResourceRecordSet) *ListResourceRecordSetsOutput { - s.ResourceRecordSets = v - return s -} - -// A request to get a list of the reusable delegation sets that are associated -// with the current AWS account. -type ListReusableDelegationSetsInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // reusable delegation sets. To get another group, submit another ListReusableDelegationSets - // request. - // - // For the value of marker, specify the value of NextMarker from the previous - // response, which is the ID of the first reusable delegation set that Amazon - // Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more reusable delegation sets to get. - Marker *string `location:"querystring" locationName:"marker" type:"string"` - - // The number of reusable delegation sets that you want Amazon Route 53 to return - // in the response to this request. If you specify a value greater than 100, - // Amazon Route 53 returns only the first 100 reusable delegation sets. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` -} - -// String returns the string representation -func (s ListReusableDelegationSetsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListReusableDelegationSetsInput) GoString() string { - return s.String() -} - -// SetMarker sets the Marker field's value. -func (s *ListReusableDelegationSetsInput) SetMarker(v string) *ListReusableDelegationSetsInput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListReusableDelegationSetsInput) SetMaxItems(v string) *ListReusableDelegationSetsInput { - s.MaxItems = &v - return s -} - -// A complex type that contains information about the reusable delegation sets -// that are associated with the current AWS account. -type ListReusableDelegationSetsOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains one DelegationSet element for each reusable - // delegation set that was created by the current AWS account. - // - // DelegationSets is a required field - DelegationSets []*DelegationSet `locationNameList:"DelegationSet" type:"list" required:"true"` - - // A flag that indicates whether there are more reusable delegation sets to - // be listed. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // For the second and subsequent calls to ListReusableDelegationSets, Marker - // is the value that you specified for the marker parameter in the request that - // produced the current response. - // - // Marker is a required field - Marker *string `type:"string" required:"true"` - - // The value that you specified for the maxitems parameter in the call to ListReusableDelegationSets - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, the value of NextMarker identifies the next reusable - // delegation set that Amazon Route 53 will return if you submit another ListReusableDelegationSets - // request and specify the value of NextMarker in the marker parameter. - NextMarker *string `type:"string"` -} - -// String returns the string representation -func (s ListReusableDelegationSetsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListReusableDelegationSetsOutput) GoString() string { - return s.String() -} - -// SetDelegationSets sets the DelegationSets field's value. -func (s *ListReusableDelegationSetsOutput) SetDelegationSets(v []*DelegationSet) *ListReusableDelegationSetsOutput { - s.DelegationSets = v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListReusableDelegationSetsOutput) SetIsTruncated(v bool) *ListReusableDelegationSetsOutput { - s.IsTruncated = &v - return s -} - -// SetMarker sets the Marker field's value. -func (s *ListReusableDelegationSetsOutput) SetMarker(v string) *ListReusableDelegationSetsOutput { - s.Marker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListReusableDelegationSetsOutput) SetMaxItems(v string) *ListReusableDelegationSetsOutput { - s.MaxItems = &v - return s -} - -// SetNextMarker sets the NextMarker field's value. -func (s *ListReusableDelegationSetsOutput) SetNextMarker(v string) *ListReusableDelegationSetsOutput { - s.NextMarker = &v - return s -} - -// A complex type containing information about a request for a list of the tags -// that are associated with an individual resource. -type ListTagsForResourceInput struct { - _ struct{} `type:"structure"` - - // The ID of the resource for which you want to retrieve tags. - // - // ResourceId is a required field - ResourceId *string `location:"uri" locationName:"ResourceId" type:"string" required:"true"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ListTagsForResourceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourceInput"} - if s.ResourceId == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceId")) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceId sets the ResourceId field's value. -func (s *ListTagsForResourceInput) SetResourceId(v string) *ListTagsForResourceInput { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ListTagsForResourceInput) SetResourceType(v string) *ListTagsForResourceInput { - s.ResourceType = &v - return s -} - -// A complex type that contains information about the health checks or hosted -// zones for which you want to list tags. -type ListTagsForResourceOutput struct { - _ struct{} `type:"structure"` - - // A ResourceTagSet containing tags associated with the specified resource. - // - // ResourceTagSet is a required field - ResourceTagSet *ResourceTagSet `type:"structure" required:"true"` -} - -// String returns the string representation -func (s ListTagsForResourceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourceOutput) GoString() string { - return s.String() -} - -// SetResourceTagSet sets the ResourceTagSet field's value. -func (s *ListTagsForResourceOutput) SetResourceTagSet(v *ResourceTagSet) *ListTagsForResourceOutput { - s.ResourceTagSet = v - return s -} - -// A complex type that contains information about the health checks or hosted -// zones for which you want to list tags. -type ListTagsForResourcesInput struct { - _ struct{} `locationName:"ListTagsForResourcesRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that contains the ResourceId element for each resource for - // which you want to get a list of tags. - // - // ResourceIds is a required field - ResourceIds []*string `locationNameList:"ResourceId" min:"1" type:"list" required:"true"` - - // The type of the resources. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - // - // ResourceType is a required field - ResourceType *string `location:"uri" locationName:"ResourceType" type:"string" required:"true" enum:"TagResourceType"` -} - -// String returns the string representation -func (s ListTagsForResourcesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourcesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTagsForResourcesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTagsForResourcesInput"} - if s.ResourceIds == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceIds")) - } - if s.ResourceIds != nil && len(s.ResourceIds) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceIds", 1)) - } - if s.ResourceType == nil { - invalidParams.Add(request.NewErrParamRequired("ResourceType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetResourceIds sets the ResourceIds field's value. -func (s *ListTagsForResourcesInput) SetResourceIds(v []*string) *ListTagsForResourcesInput { - s.ResourceIds = v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ListTagsForResourcesInput) SetResourceType(v string) *ListTagsForResourcesInput { - s.ResourceType = &v - return s -} - -// A complex type containing tags for the specified resources. -type ListTagsForResourcesOutput struct { - _ struct{} `type:"structure"` - - // A list of ResourceTagSets containing tags associated with the specified resources. - // - // ResourceTagSets is a required field - ResourceTagSets []*ResourceTagSet `locationNameList:"ResourceTagSet" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTagsForResourcesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTagsForResourcesOutput) GoString() string { - return s.String() -} - -// SetResourceTagSets sets the ResourceTagSets field's value. -func (s *ListTagsForResourcesOutput) SetResourceTagSets(v []*ResourceTagSet) *ListTagsForResourcesOutput { - s.ResourceTagSets = v - return s -} - -// A complex type that contains the information about the request to list the -// traffic policies that are associated with the current AWS account. -type ListTrafficPoliciesInput struct { - _ struct{} `type:"structure"` - - // (Optional) The maximum number of traffic policies that you want Amazon Route - // 53 to return in response to this request. If you have more than MaxItems - // traffic policies, the value of IsTruncated in the response is true, and the - // value of TrafficPolicyIdMarker is the ID of the first traffic policy that - // Amazon Route 53 will return if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // (Conditional) For your first request to ListTrafficPolicies, don't include - // the TrafficPolicyIdMarker parameter. - // - // If you have more traffic policies than the value of MaxItems, ListTrafficPolicies - // returns only the first MaxItems traffic policies. To get the next group of - // policies, submit another request to ListTrafficPolicies. For the value of - // TrafficPolicyIdMarker, specify the value of TrafficPolicyIdMarker that was - // returned in the previous response. - TrafficPolicyIdMarker *string `location:"querystring" locationName:"trafficpolicyid" min:"1" type:"string"` -} - -// String returns the string representation -func (s ListTrafficPoliciesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPoliciesInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPoliciesInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPoliciesInput"} - if s.TrafficPolicyIdMarker != nil && len(*s.TrafficPolicyIdMarker) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyIdMarker", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPoliciesInput) SetMaxItems(v string) *ListTrafficPoliciesInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyIdMarker sets the TrafficPolicyIdMarker field's value. -func (s *ListTrafficPoliciesInput) SetTrafficPolicyIdMarker(v string) *ListTrafficPoliciesInput { - s.TrafficPolicyIdMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPoliciesOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of traffic policies - // by submitting another ListTrafficPolicies request and specifying the value - // of TrafficPolicyIdMarker in the TrafficPolicyIdMarker request parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the ListTrafficPolicies - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If the value of IsTruncated is true, TrafficPolicyIdMarker is the ID of the - // first traffic policy in the next group of MaxItems traffic policies. - // - // TrafficPolicyIdMarker is a required field - TrafficPolicyIdMarker *string `min:"1" type:"string" required:"true"` - - // A list that contains one TrafficPolicySummary element for each traffic policy - // that was created by the current AWS account. - // - // TrafficPolicySummaries is a required field - TrafficPolicySummaries []*TrafficPolicySummary `locationNameList:"TrafficPolicySummary" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPoliciesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPoliciesOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPoliciesOutput) SetIsTruncated(v bool) *ListTrafficPoliciesOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPoliciesOutput) SetMaxItems(v string) *ListTrafficPoliciesOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyIdMarker sets the TrafficPolicyIdMarker field's value. -func (s *ListTrafficPoliciesOutput) SetTrafficPolicyIdMarker(v string) *ListTrafficPoliciesOutput { - s.TrafficPolicyIdMarker = &v - return s -} - -// SetTrafficPolicySummaries sets the TrafficPolicySummaries field's value. -func (s *ListTrafficPoliciesOutput) SetTrafficPolicySummaries(v []*TrafficPolicySummary) *ListTrafficPoliciesOutput { - s.TrafficPolicySummaries = v - return s -} - -// A request for the traffic policy instances that you created in a specified -// hosted zone. -type ListTrafficPolicyInstancesByHostedZoneInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you want to list traffic policy instances - // for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"querystring" locationName:"id" type:"string" required:"true"` - - // The maximum number of traffic policy instances to be included in the response - // body for this request. If you have more than MaxItems traffic policy instances, - // the value of the IsTruncated element in the response is true, and the values - // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance that Amazon Route 53 will return - // if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // If the value of IsTruncated in the previous response is true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, - // specify the value of TrafficPolicyInstanceNameMarker from the previous response, - // which is the name of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response is true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, - // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, - // which is the type of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyInstancesByHostedZoneInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetHostedZoneId(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.HostedZoneId = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetMaxItems(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByHostedZoneInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesByHostedZoneOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of traffic - // policy instances by submitting another ListTrafficPolicyInstancesByHostedZone - // request and specifying the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker in the corresponding request parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the ListTrafficPolicyInstancesByHostedZone - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of traffic policy instances. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance in the next group of traffic policy instances. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByHostedZoneOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesByHostedZoneOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesByHostedZoneOutput { - s.TrafficPolicyInstances = v - return s -} - -// A complex type that contains the information about the request to list your -// traffic policy instances. -type ListTrafficPolicyInstancesByPolicyInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of hostedzoneid, specify the value of HostedZoneIdMarker from - // the previous response, which is the hosted zone ID of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of traffic policy instances to be included in the response - // body for this request. If you have more than MaxItems traffic policy instances, - // the value of the IsTruncated element in the response is true, and the values - // of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // represent the first traffic policy instance that Amazon Route 53 will return - // if you submit another request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // The ID of the traffic policy for which you want to list traffic policy instances. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `location:"querystring" locationName:"id" min:"1" type:"string" required:"true"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of trafficpolicyinstancename, specify the value of TrafficPolicyInstanceNameMarker - // from the previous response, which is the name of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstancesByPolicy request. - // - // For the value of trafficpolicyinstancetype, specify the value of TrafficPolicyInstanceTypeMarker - // from the previous response, which is the name of the first traffic policy - // instance that Amazon Route 53 will return if you submit another request. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` - - // The version of the traffic policy for which you want to list traffic policy - // instances. The version must be associated with the traffic policy that is - // specified by TrafficPolicyId. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `location:"querystring" locationName:"version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByPolicyInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByPolicyInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyInstancesByPolicyInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyInstancesByPolicyInput"} - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.HostedZoneIdMarker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetMaxItems(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyId(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *ListTrafficPolicyInstancesByPolicyInput) SetTrafficPolicyVersion(v int64) *ListTrafficPolicyInstancesByPolicyInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesByPolicyOutput struct { - _ struct{} `type:"structure"` - - // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance in the next group of traffic policy instances. - HostedZoneIdMarker *string `type:"string"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get the next group of traffic - // policy instances by calling ListTrafficPolicyInstancesByPolicy again and - // specifying the values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker elements in the corresponding request - // parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicyInstancesByPolicy - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance in the next group of MaxItems traffic policy - // instances. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance in the next group of MaxItems traffic policy instances. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesByPolicyOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesByPolicyOutput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.HostedZoneIdMarker = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesByPolicyOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesByPolicyOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesByPolicyOutput { - s.TrafficPolicyInstances = v - return s -} - -// A request to get information about the traffic policy instances that you -// created by using the current AWS account. -type ListTrafficPolicyInstancesInput struct { - _ struct{} `type:"structure"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of HostedZoneId, specify - // the value of HostedZoneIdMarker from the previous response, which is the - // hosted zone ID of the first traffic policy instance in the next group of - // traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - HostedZoneIdMarker *string `location:"querystring" locationName:"hostedzoneid" type:"string"` - - // The maximum number of traffic policy instances that you want Amazon Route - // 53 to return in response to a ListTrafficPolicyInstances request. If you - // have more than MaxItems traffic policy instances, the value of the IsTruncated - // element in the response is true, and the values of HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, - // and TrafficPolicyInstanceTypeMarker represent the first traffic policy instance - // in the next group of MaxItems traffic policy instances. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancename, - // specify the value of TrafficPolicyInstanceNameMarker from the previous response, - // which is the name of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceNameMarker *string `location:"querystring" locationName:"trafficpolicyinstancename" type:"string"` - - // If the value of IsTruncated in the previous response was true, you have more - // traffic policy instances. To get more traffic policy instances, submit another - // ListTrafficPolicyInstances request. For the value of trafficpolicyinstancetype, - // specify the value of TrafficPolicyInstanceTypeMarker from the previous response, - // which is the type of the first traffic policy instance in the next group - // of traffic policy instances. - // - // If the value of IsTruncated in the previous response was false, there are - // no more traffic policy instances to get. - TrafficPolicyInstanceTypeMarker *string `location:"querystring" locationName:"trafficpolicyinstancetype" type:"string" enum:"RRType"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesInput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesInput { - s.HostedZoneIdMarker = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesInput) SetMaxItems(v string) *ListTrafficPolicyInstancesInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesInput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesInput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesInput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyInstancesOutput struct { - _ struct{} `type:"structure"` - - // If IsTruncated is true, HostedZoneIdMarker is the ID of the hosted zone of - // the first traffic policy instance that Amazon Route 53 will return if you - // submit another ListTrafficPolicyInstances request. - HostedZoneIdMarker *string `type:"string"` - - // A flag that indicates whether there are more traffic policy instances to - // be listed. If the response was truncated, you can get more traffic policy - // instances by calling ListTrafficPolicyInstances again and specifying the - // values of the HostedZoneIdMarker, TrafficPolicyInstanceNameMarker, and TrafficPolicyInstanceTypeMarker - // in the corresponding request parameters. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the MaxItems parameter in the call to ListTrafficPolicyInstances - // that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // If IsTruncated is true, TrafficPolicyInstanceNameMarker is the name of the - // first traffic policy instance that Amazon Route 53 will return if you submit - // another ListTrafficPolicyInstances request. - TrafficPolicyInstanceNameMarker *string `type:"string"` - - // If IsTruncated is true, TrafficPolicyInstanceTypeMarker is the DNS type of - // the resource record sets that are associated with the first traffic policy - // instance that Amazon Route 53 will return if you submit another ListTrafficPolicyInstances - // request. - TrafficPolicyInstanceTypeMarker *string `type:"string" enum:"RRType"` - - // A list that contains one TrafficPolicyInstance element for each traffic policy - // instance that matches the elements in the request. - // - // TrafficPolicyInstances is a required field - TrafficPolicyInstances []*TrafficPolicyInstance `locationNameList:"TrafficPolicyInstance" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyInstancesOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyInstancesOutput) GoString() string { - return s.String() -} - -// SetHostedZoneIdMarker sets the HostedZoneIdMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetHostedZoneIdMarker(v string) *ListTrafficPolicyInstancesOutput { - s.HostedZoneIdMarker = &v - return s -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyInstancesOutput) SetIsTruncated(v bool) *ListTrafficPolicyInstancesOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyInstancesOutput) SetMaxItems(v string) *ListTrafficPolicyInstancesOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyInstanceNameMarker sets the TrafficPolicyInstanceNameMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstanceNameMarker(v string) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstanceNameMarker = &v - return s -} - -// SetTrafficPolicyInstanceTypeMarker sets the TrafficPolicyInstanceTypeMarker field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstanceTypeMarker(v string) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstanceTypeMarker = &v - return s -} - -// SetTrafficPolicyInstances sets the TrafficPolicyInstances field's value. -func (s *ListTrafficPolicyInstancesOutput) SetTrafficPolicyInstances(v []*TrafficPolicyInstance) *ListTrafficPolicyInstancesOutput { - s.TrafficPolicyInstances = v - return s -} - -// A complex type that contains the information about the request to list your -// traffic policies. -type ListTrafficPolicyVersionsInput struct { - _ struct{} `type:"structure"` - - // Specify the value of Id of the traffic policy for which you want to list - // all versions. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The maximum number of traffic policy versions that you want Amazon Route - // 53 to include in the response body for this request. If the specified traffic - // policy has more than MaxItems versions, the value of IsTruncated in the response - // is true, and the value of the TrafficPolicyVersionMarker element is the ID - // of the first version that Amazon Route 53 will return if you submit another - // request. - MaxItems *string `location:"querystring" locationName:"maxitems" type:"string"` - - // For your first request to ListTrafficPolicyVersions, don't include the TrafficPolicyVersionMarker - // parameter. - // - // If you have more traffic policy versions than the value of MaxItems, ListTrafficPolicyVersions - // returns only the first group of MaxItems versions. To get more traffic policy - // versions, submit another ListTrafficPolicyVersions request. For the value - // of TrafficPolicyVersionMarker, specify the value of TrafficPolicyVersionMarker - // in the previous response. - TrafficPolicyVersionMarker *string `location:"querystring" locationName:"trafficpolicyversion" type:"string"` -} - -// String returns the string representation -func (s ListTrafficPolicyVersionsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyVersionsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListTrafficPolicyVersionsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListTrafficPolicyVersionsInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *ListTrafficPolicyVersionsInput) SetId(v string) *ListTrafficPolicyVersionsInput { - s.Id = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyVersionsInput) SetMaxItems(v string) *ListTrafficPolicyVersionsInput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicyVersionMarker sets the TrafficPolicyVersionMarker field's value. -func (s *ListTrafficPolicyVersionsInput) SetTrafficPolicyVersionMarker(v string) *ListTrafficPolicyVersionsInput { - s.TrafficPolicyVersionMarker = &v - return s -} - -// A complex type that contains the response information for the request. -type ListTrafficPolicyVersionsOutput struct { - _ struct{} `type:"structure"` - - // A flag that indicates whether there are more traffic policies to be listed. - // If the response was truncated, you can get the next group of traffic policies - // by submitting another ListTrafficPolicyVersions request and specifying the - // value of NextMarker in the marker parameter. - // - // IsTruncated is a required field - IsTruncated *bool `type:"boolean" required:"true"` - - // The value that you specified for the maxitems parameter in the ListTrafficPolicyVersions - // request that produced the current response. - // - // MaxItems is a required field - MaxItems *string `type:"string" required:"true"` - - // A list that contains one TrafficPolicy element for each traffic policy version - // that is associated with the specified traffic policy. - // - // TrafficPolicies is a required field - TrafficPolicies []*TrafficPolicy `locationNameList:"TrafficPolicy" type:"list" required:"true"` - - // If IsTruncated is true, the value of TrafficPolicyVersionMarker identifies - // the first traffic policy that Amazon Route 53 will return if you submit another - // request. Call ListTrafficPolicyVersions again and specify the value of TrafficPolicyVersionMarker - // in the TrafficPolicyVersionMarker request parameter. - // - // This element is present only if IsTruncated is true. - // - // TrafficPolicyVersionMarker is a required field - TrafficPolicyVersionMarker *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s ListTrafficPolicyVersionsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListTrafficPolicyVersionsOutput) GoString() string { - return s.String() -} - -// SetIsTruncated sets the IsTruncated field's value. -func (s *ListTrafficPolicyVersionsOutput) SetIsTruncated(v bool) *ListTrafficPolicyVersionsOutput { - s.IsTruncated = &v - return s -} - -// SetMaxItems sets the MaxItems field's value. -func (s *ListTrafficPolicyVersionsOutput) SetMaxItems(v string) *ListTrafficPolicyVersionsOutput { - s.MaxItems = &v - return s -} - -// SetTrafficPolicies sets the TrafficPolicies field's value. -func (s *ListTrafficPolicyVersionsOutput) SetTrafficPolicies(v []*TrafficPolicy) *ListTrafficPolicyVersionsOutput { - s.TrafficPolicies = v - return s -} - -// SetTrafficPolicyVersionMarker sets the TrafficPolicyVersionMarker field's value. -func (s *ListTrafficPolicyVersionsOutput) SetTrafficPolicyVersionMarker(v string) *ListTrafficPolicyVersionsOutput { - s.TrafficPolicyVersionMarker = &v - return s -} - -// A complex type that contains information about that can be associated with -// your hosted zone. -type ListVPCAssociationAuthorizationsInput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone for which you want a list of VPCs that can be associated - // with the hosted zone. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"uri" locationName:"Id" type:"string" required:"true"` - - // Optional: An integer that specifies the maximum number of VPCs that you want - // Amazon Route 53 to return. If you don't specify a value for MaxResults, Amazon - // Route 53 returns up to 50 VPCs per page. - MaxResults *string `location:"querystring" locationName:"maxresults" type:"string"` - - // Optional: If a response includes a NextToken element, there are more VPCs - // that can be associated with the specified hosted zone. To get the next page - // of results, submit another request, and include the value of NextToken from - // the response in the nexttoken parameter in another ListVPCAssociationAuthorizations - // request. - NextToken *string `location:"querystring" locationName:"nexttoken" type:"string"` -} - -// String returns the string representation -func (s ListVPCAssociationAuthorizationsInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListVPCAssociationAuthorizationsInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ListVPCAssociationAuthorizationsInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ListVPCAssociationAuthorizationsInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetHostedZoneId(v string) *ListVPCAssociationAuthorizationsInput { - s.HostedZoneId = &v - return s -} - -// SetMaxResults sets the MaxResults field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetMaxResults(v string) *ListVPCAssociationAuthorizationsInput { - s.MaxResults = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListVPCAssociationAuthorizationsInput) SetNextToken(v string) *ListVPCAssociationAuthorizationsInput { - s.NextToken = &v - return s -} - -// A complex type that contains the response information for the request. -type ListVPCAssociationAuthorizationsOutput struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that you can associate the listed VPCs with. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // When the response includes a NextToken element, there are more VPCs that - // can be associated with the specified hosted zone. To get the next page of - // VPCs, submit another ListVPCAssociationAuthorizations request, and include - // the value of the NextToken element from the response in the nexttoken request - // parameter. - NextToken *string `type:"string"` - - // The list of VPCs that are authorized to be associated with the specified - // hosted zone. - // - // VPCs is a required field - VPCs []*VPC `locationNameList:"VPC" min:"1" type:"list" required:"true"` -} - -// String returns the string representation -func (s ListVPCAssociationAuthorizationsOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ListVPCAssociationAuthorizationsOutput) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetHostedZoneId(v string) *ListVPCAssociationAuthorizationsOutput { - s.HostedZoneId = &v - return s -} - -// SetNextToken sets the NextToken field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetNextToken(v string) *ListVPCAssociationAuthorizationsOutput { - s.NextToken = &v - return s -} - -// SetVPCs sets the VPCs field's value. -func (s *ListVPCAssociationAuthorizationsOutput) SetVPCs(v []*VPC) *ListVPCAssociationAuthorizationsOutput { - s.VPCs = v - return s -} - -// A complex type that contains information about a configuration for DNS query -// logging. -type QueryLoggingConfig struct { - _ struct{} `type:"structure"` - - // The Amazon Resource Name (ARN) of the CloudWatch Logs log group that Amazon - // Route 53 is publishing logs to. - // - // CloudWatchLogsLogGroupArn is a required field - CloudWatchLogsLogGroupArn *string `type:"string" required:"true"` - - // The ID of the hosted zone that CloudWatch Logs is logging queries for. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The ID for a configuration for DNS query logging. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s QueryLoggingConfig) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s QueryLoggingConfig) GoString() string { - return s.String() -} - -// SetCloudWatchLogsLogGroupArn sets the CloudWatchLogsLogGroupArn field's value. -func (s *QueryLoggingConfig) SetCloudWatchLogsLogGroupArn(v string) *QueryLoggingConfig { - s.CloudWatchLogsLogGroupArn = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *QueryLoggingConfig) SetHostedZoneId(v string) *QueryLoggingConfig { - s.HostedZoneId = &v - return s -} - -// SetId sets the Id field's value. -func (s *QueryLoggingConfig) SetId(v string) *QueryLoggingConfig { - s.Id = &v - return s -} - -// Information specific to the resource record. -// -// If you're creating an alias resource record set, omit ResourceRecord. -type ResourceRecord struct { - _ struct{} `type:"structure"` - - // The current or new DNS record value, not to exceed 4,000 characters. In the - // case of a DELETE action, if the current value does not match the actual value, - // an error is returned. For descriptions about how to format Value for different - // record types, see Supported DNS Resource Record Types (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html) - // in the Amazon Route 53 Developer Guide. - // - // You can specify more than one value for all record types except CNAME and - // SOA. - // - // If you're creating an alias resource record set, omit Value. - // - // Value is a required field - Value *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s ResourceRecord) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceRecord) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ResourceRecord) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ResourceRecord"} - if s.Value == nil { - invalidParams.Add(request.NewErrParamRequired("Value")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetValue sets the Value field's value. -func (s *ResourceRecord) SetValue(v string) *ResourceRecord { - s.Value = &v - return s -} - -// Information about the resource record set to create or delete. -type ResourceRecordSet struct { - _ struct{} `type:"structure"` - - // Alias resource record sets only: Information about the CloudFront distribution, - // AWS Elastic Beanstalk environment, ELB load balancer, Amazon S3 bucket, or - // Amazon Route 53 resource record set to which you're redirecting queries. - // The AWS Elastic Beanstalk environment must have a regionalized subdomain. - // - // If you're creating resource records sets for a private hosted zone, note - // the following: - // - // * You can't create alias resource record sets for CloudFront distributions - // in a private hosted zone. - // - // * Creating geolocation alias resource record sets or latency alias resource - // record sets in a private hosted zone is unsupported. - // - // * For information about creating failover resource record sets in a private - // hosted zone, see Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - // in the Amazon Route 53 Developer Guide. - AliasTarget *AliasTarget `type:"structure"` - - // Failover resource record sets only: To configure failover, you add the Failover - // element to two resource record sets. For one resource record set, you specify - // PRIMARY as the value for Failover; for the other resource record set, you - // specify SECONDARY. In addition, you include the HealthCheckId element and - // specify the health check that you want Amazon Route 53 to perform for each - // resource record set. - // - // Except where noted, the following failover behaviors assume that you have - // included the HealthCheckId element in both resource record sets: - // - // * When the primary resource record set is healthy, Amazon Route 53 responds - // to DNS queries with the applicable value from the primary resource record - // set regardless of the health of the secondary resource record set. - // - // * When the primary resource record set is unhealthy and the secondary - // resource record set is healthy, Amazon Route 53 responds to DNS queries - // with the applicable value from the secondary resource record set. - // - // * When the secondary resource record set is unhealthy, Amazon Route 53 - // responds to DNS queries with the applicable value from the primary resource - // record set regardless of the health of the primary resource record set. - // - // * If you omit the HealthCheckId element for the secondary resource record - // set, and if the primary resource record set is unhealthy, Amazon Route - // 53 always responds to DNS queries with the applicable value from the secondary - // resource record set. This is true regardless of the health of the associated - // endpoint. - // - // You can't create non-failover resource record sets that have the same values - // for the Name and Type elements as failover resource record sets. - // - // For failover alias resource record sets, you must also include the EvaluateTargetHealth - // element and set the value to true. - // - // For more information about configuring failover for Amazon Route 53, see - // the following topics in the Amazon Route 53 Developer Guide: - // - // * Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // - // * Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - Failover *string `type:"string" enum:"ResourceRecordSetFailover"` - - // Geo location resource record sets only: A complex type that lets you control - // how Amazon Route 53 responds to DNS queries based on the geographic origin - // of the query. For example, if you want all queries from Africa to be routed - // to a web server with an IP address of 192.0.2.111, create a resource record - // set with a Type of A and a ContinentCode of AF. - // - // Creating geolocation and geolocation alias resource record sets in private - // hosted zones is not supported. - // - // If you create separate resource record sets for overlapping geographic regions - // (for example, one resource record set for a continent and one for a country - // on the same continent), priority goes to the smallest geographic region. - // This allows you to route most queries for a continent to one resource and - // to route queries for a country on that continent to a different resource. - // - // You can't create two geolocation resource record sets that specify the same - // geographic location. - // - // The value * in the CountryCode element matches all geographic locations that - // aren't specified in other geolocation resource record sets that have the - // same values for the Name and Type elements. - // - // Geolocation works by mapping IP addresses to locations. However, some IP - // addresses aren't mapped to geographic locations, so even if you create geolocation - // resource record sets that cover all seven continents, Amazon Route 53 will - // receive some DNS queries from locations that it can't identify. We recommend - // that you create a resource record set for which the value of CountryCode - // is *, which handles both queries that come from locations for which you haven't - // created geolocation resource record sets and queries from IP addresses that - // aren't mapped to a location. If you don't create a * resource record set, - // Amazon Route 53 returns a "no answer" response for queries from those locations. - // - // You can't create non-geolocation resource record sets that have the same - // values for the Name and Type elements as geolocation resource record sets. - GeoLocation *GeoLocation `type:"structure"` - - // If you want Amazon Route 53 to return this resource record set in response - // to a DNS query only when a health check is passing, include the HealthCheckId - // element and specify the ID of the applicable health check. - // - // Amazon Route 53 determines whether a resource record set is healthy based - // on one of the following: - // - // * By periodically sending a request to the endpoint that is specified - // in the health check - // - // * By aggregating the status of a specified group of health checks (calculated - // health checks) - // - // * By determining the current state of a CloudWatch alarm (CloudWatch metric - // health checks) - // - // For more information, see How Amazon Route 53 Determines Whether an Endpoint - // Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html). - // - // The HealthCheckId element is only useful when Amazon Route 53 is choosing - // between two or more resource record sets to respond to a DNS query, and you - // want Amazon Route 53 to base the choice in part on the status of a health - // check. Configuring health checks only makes sense in the following configurations: - // - // * You're checking the health of the resource record sets in a group of - // weighted, latency, geolocation, or failover resource record sets, and - // you specify health check IDs for all of the resource record sets. If the - // health check for one resource record set specifies an endpoint that is - // not healthy, Amazon Route 53 stops responding to queries using the value - // for that resource record set. - // - // * You set EvaluateTargetHealth to true for the resource record sets in - // a group of alias, weighted alias, latency alias, geolocation alias, or - // failover alias resource record sets, and you specify health check IDs - // for all of the resource record sets that are referenced by the alias resource - // record sets. - // - // Amazon Route 53 doesn't check the health of the endpoint specified in the - // resource record set, for example, the endpoint specified by the IP address - // in the Value element. When you add a HealthCheckId element to a resource - // record set, Amazon Route 53 checks the health of the endpoint that you specified - // in the health check. - // - // For geolocation resource record sets, if an endpoint is unhealthy, Amazon - // Route 53 looks for a resource record set for the larger, associated geographic - // region. For example, suppose you have resource record sets for a state in - // the United States, for the United States, for North America, and for all - // locations. If the endpoint for the state resource record set is unhealthy, - // Amazon Route 53 checks the resource record sets for the United States, for - // North America, and for all locations (a resource record set for which the - // value of CountryCode is *), in that order, until it finds a resource record - // set for which the endpoint is healthy. - // - // If your health checks specify the endpoint only by domain name, we recommend - // that you create a separate health check for each endpoint. For example, create - // a health check for each HTTP server that is serving content for www.example.com. - // For the value of FullyQualifiedDomainName, specify the domain name of the - // server (such as us-east-2-www.example.com), not the name of the resource - // record sets (example.com). - // - // n this configuration, if you create a health check for which the value of - // FullyQualifiedDomainName matches the name of the resource record sets and - // then associate the health check with those resource record sets, health check - // results will be unpredictable. - // - // For more information, see the following topics in the Amazon Route 53 Developer - // Guide: - // - // * Amazon Route 53 Health Checks and DNS Failover (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover.html) - // - // * Configuring Failover in a Private Hosted Zone (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-private-hosted-zones.html) - HealthCheckId *string `type:"string"` - - // Multivalue answer resource record sets only: To route traffic approximately - // randomly to multiple resources, such as web servers, create one multivalue - // answer record for each resource and specify true for MultiValueAnswer. Note - // the following: - // - // * If you associate a health check with a multivalue answer resource record - // set, Amazon Route 53 responds to DNS queries with the corresponding IP - // address only when the health check is healthy. - // - // * If you don't associate a health check with a multivalue answer record, - // Amazon Route 53 always considers the record to be healthy. - // - // * Amazon Route 53 responds to DNS queries with up to eight healthy records; - // if you have eight or fewer healthy records, Amazon Route 53 responds to - // all DNS queries with all the healthy records. - // - // * If you have more than eight healthy records, Amazon Route 53 responds - // to different DNS resolvers with different combinations of healthy records. - // - // * When all records are unhealthy, Amazon Route 53 responds to DNS queries - // with up to eight unhealthy records. - // - // * If a resource becomes unavailable after a resolver caches a response, - // client software typically tries another of the IP addresses in the response. - // - // You can't create multivalue answer alias records. - MultiValueAnswer *bool `type:"boolean"` - - // The name of the domain you want to perform the action on. - // - // Enter a fully qualified domain name, for example, www.example.com. You can - // optionally include a trailing dot. If you omit the trailing dot, Amazon Route - // 53 still assumes that the domain name that you specify is fully qualified. - // This means that Amazon Route 53 treats www.example.com (without a trailing - // dot) and www.example.com. (with a trailing dot) as identical. - // - // For information about how to specify characters other than a-z, 0-9, and - // - (hyphen) and how to specify internationalized domain names, see DNS Domain - // Name Format (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DomainNameFormat.html) - // in the Amazon Route 53 Developer Guide. - // - // You can use the asterisk (*) wildcard to replace the leftmost label in a - // domain name, for example, *.example.com. Note the following: - // - // * The * must replace the entire label. For example, you can't specify - // *prod.example.com or prod*.example.com. - // - // * The * can't replace any of the middle labels, for example, marketing.*.example.com. - // - // * If you include * in any position other than the leftmost label in a - // domain name, DNS treats it as an * character (ASCII 42), not as a wildcard. - // - // You can't use the * wildcard for resource records sets that have a type of - // NS. - // - // You can use the * wildcard as the leftmost label in a domain name, for example, - // *.example.com. You can't use an * for one of the middle labels, for example, - // marketing.*.example.com. In addition, the * must replace the entire label; - // for example, you can't specify prod*.example.com. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // Latency-based resource record sets only: The Amazon EC2 Region where you - // created the resource that this resource record set refers to. The resource - // typically is an AWS resource, such as an EC2 instance or an ELB load balancer, - // and is referred to by an IP address or a DNS domain name, depending on the - // record type. - // - // Creating latency and latency alias resource record sets in private hosted - // zones is not supported. - // - // When Amazon Route 53 receives a DNS query for a domain name and type for - // which you have created latency resource record sets, Amazon Route 53 selects - // the latency resource record set that has the lowest latency between the end - // user and the associated Amazon EC2 Region. Amazon Route 53 then returns the - // value that is associated with the selected resource record set. - // - // Note the following: - // - // * You can only specify one ResourceRecord per latency resource record - // set. - // - // * You can only create one latency resource record set for each Amazon - // EC2 Region. - // - // * You aren't required to create latency resource record sets for all Amazon - // EC2 Regions. Amazon Route 53 will choose the region with the best latency - // from among the regions that you create latency resource record sets for. - // - // * You can't create non-latency resource record sets that have the same - // values for the Name and Type elements as latency resource record sets. - Region *string `min:"1" type:"string" enum:"ResourceRecordSetRegion"` - - // Information about the resource records to act upon. - // - // If you're creating an alias resource record set, omit ResourceRecords. - ResourceRecords []*ResourceRecord `locationNameList:"ResourceRecord" min:"1" type:"list"` - - // Weighted, Latency, Geo, and Failover resource record sets only: An identifier - // that differentiates among multiple resource record sets that have the same - // combination of DNS name and type. The value of SetIdentifier must be unique - // for each resource record set that has the same combination of DNS name and - // type. Omit SetIdentifier for any other types of record sets. - SetIdentifier *string `min:"1" type:"string"` - - // The resource record cache time to live (TTL), in seconds. Note the following: - // - // * If you're creating or updating an alias resource record set, omit TTL. - // Amazon Route 53 uses the value of TTL for the alias target. - // - // * If you're associating this resource record set with a health check (if - // you're adding a HealthCheckId element), we recommend that you specify - // a TTL of 60 seconds or less so clients respond quickly to changes in health - // status. - // - // * All of the resource record sets in a group of weighted resource record - // sets must have the same value for TTL. - // - // * If a group of weighted resource record sets includes one or more weighted - // alias resource record sets for which the alias target is an ELB load balancer, - // we recommend that you specify a TTL of 60 seconds for all of the non-alias - // weighted resource record sets that have the same name and type. Values - // other than 60 seconds (the TTL for load balancers) will change the effect - // of the values that you specify for Weight. - TTL *int64 `type:"long"` - - // When you create a traffic policy instance, Amazon Route 53 automatically - // creates a resource record set. TrafficPolicyInstanceId is the ID of the traffic - // policy instance that Amazon Route 53 created this resource record set for. - // - // To delete the resource record set that is associated with a traffic policy - // instance, use DeleteTrafficPolicyInstance. Amazon Route 53 will delete the - // resource record set automatically. If you delete the resource record set - // by using ChangeResourceRecordSets, Amazon Route 53 doesn't automatically - // delete the traffic policy instance, and you'll continue to be charged for - // it even though it's no longer in use. - TrafficPolicyInstanceId *string `min:"1" type:"string"` - - // The DNS record type. For information about different record types and how - // data is encoded for them, see Supported DNS Resource Record Types (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html) - // in the Amazon Route 53 Developer Guide. - // - // Valid values for basic resource record sets: A | AAAA | CAA | CNAME | MX - // | NAPTR | NS | PTR | SOA | SPF | SRV | TXT - // - // Values for weighted, latency, geolocation, and failover resource record sets: - // A | AAAA | CAA | CNAME | MX | NAPTR | PTR | SPF | SRV | TXT. When creating - // a group of weighted, latency, geolocation, or failover resource record sets, - // specify the same value for all of the resource record sets in the group. - // - // Valid values for multivalue answer resource record sets: A | AAAA | MX | - // NAPTR | PTR | SPF | SRV | TXT - // - // SPF records were formerly used to verify the identity of the sender of email - // messages. However, we no longer recommend that you create resource record - // sets for which the value of Type is SPF. RFC 7208, Sender Policy Framework - // (SPF) for Authorizing Use of Domains in Email, Version 1, has been updated - // to say, "...[I]ts existence and mechanism defined in [RFC4408] have led to - // some interoperability issues. Accordingly, its use is no longer appropriate - // for SPF version 1; implementations are not to use it." In RFC 7208, see section - // 14.1, The SPF DNS Record Type (http://tools.ietf.org/html/rfc7208#section-14.1). - // - // Values for alias resource record sets: - // - // * CloudFront distributions:A - // - // If IPv6 is enabled for the distribution, create two resource record sets - // to route traffic to your distribution, one with a value of A and one with - // a value of AAAA. - // - // * AWS Elastic Beanstalk environment that has a regionalized subdomain: - // A - // - // * ELB load balancers:A | AAAA - // - // * Amazon S3 buckets:A - // - // * Another resource record set in this hosted zone: Specify the type of - // the resource record set that you're creating the alias for. All values - // are supported except NS and SOA. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` - - // Weighted resource record sets only: Among resource record sets that have - // the same combination of DNS name and type, a value that determines the proportion - // of DNS queries that Amazon Route 53 responds to using the current resource - // record set. Amazon Route 53 calculates the sum of the weights for the resource - // record sets that have the same combination of DNS name and type. Amazon Route - // 53 then responds to queries based on the ratio of a resource's weight to - // the total. Note the following: - // - // * You must specify a value for the Weight element for every weighted resource - // record set. - // - // * You can only specify one ResourceRecord per weighted resource record - // set. - // - // * You can't create latency, failover, or geolocation resource record sets - // that have the same values for the Name and Type elements as weighted resource - // record sets. - // - // * You can create a maximum of 100 weighted resource record sets that have - // the same values for the Name and Type elements. - // - // * For weighted (but not weighted alias) resource record sets, if you set - // Weight to 0 for a resource record set, Amazon Route 53 never responds - // to queries with the applicable value for that resource record set. However, - // if you set Weight to 0 for all resource record sets that have the same - // combination of DNS name and type, traffic is routed to all resources with - // equal probability. - // - // The effect of setting Weight to 0 is different when you associate health - // checks with weighted resource record sets. For more information, see Options - // for Configuring Amazon Route 53 Active-Active and Active-Passive Failover - // (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring-options.html) - // in the Amazon Route 53 Developer Guide. - Weight *int64 `type:"long"` -} - -// String returns the string representation -func (s ResourceRecordSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceRecordSet) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *ResourceRecordSet) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "ResourceRecordSet"} - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Region != nil && len(*s.Region) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Region", 1)) - } - if s.ResourceRecords != nil && len(s.ResourceRecords) < 1 { - invalidParams.Add(request.NewErrParamMinLen("ResourceRecords", 1)) - } - if s.SetIdentifier != nil && len(*s.SetIdentifier) < 1 { - invalidParams.Add(request.NewErrParamMinLen("SetIdentifier", 1)) - } - if s.TrafficPolicyInstanceId != nil && len(*s.TrafficPolicyInstanceId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyInstanceId", 1)) - } - if s.Type == nil { - invalidParams.Add(request.NewErrParamRequired("Type")) - } - if s.AliasTarget != nil { - if err := s.AliasTarget.Validate(); err != nil { - invalidParams.AddNested("AliasTarget", err.(request.ErrInvalidParams)) - } - } - if s.GeoLocation != nil { - if err := s.GeoLocation.Validate(); err != nil { - invalidParams.AddNested("GeoLocation", err.(request.ErrInvalidParams)) - } - } - if s.ResourceRecords != nil { - for i, v := range s.ResourceRecords { - if v == nil { - continue - } - if err := v.Validate(); err != nil { - invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ResourceRecords", i), err.(request.ErrInvalidParams)) - } - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAliasTarget sets the AliasTarget field's value. -func (s *ResourceRecordSet) SetAliasTarget(v *AliasTarget) *ResourceRecordSet { - s.AliasTarget = v - return s -} - -// SetFailover sets the Failover field's value. -func (s *ResourceRecordSet) SetFailover(v string) *ResourceRecordSet { - s.Failover = &v - return s -} - -// SetGeoLocation sets the GeoLocation field's value. -func (s *ResourceRecordSet) SetGeoLocation(v *GeoLocation) *ResourceRecordSet { - s.GeoLocation = v - return s -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *ResourceRecordSet) SetHealthCheckId(v string) *ResourceRecordSet { - s.HealthCheckId = &v - return s -} - -// SetMultiValueAnswer sets the MultiValueAnswer field's value. -func (s *ResourceRecordSet) SetMultiValueAnswer(v bool) *ResourceRecordSet { - s.MultiValueAnswer = &v - return s -} - -// SetName sets the Name field's value. -func (s *ResourceRecordSet) SetName(v string) *ResourceRecordSet { - s.Name = &v - return s -} - -// SetRegion sets the Region field's value. -func (s *ResourceRecordSet) SetRegion(v string) *ResourceRecordSet { - s.Region = &v - return s -} - -// SetResourceRecords sets the ResourceRecords field's value. -func (s *ResourceRecordSet) SetResourceRecords(v []*ResourceRecord) *ResourceRecordSet { - s.ResourceRecords = v - return s -} - -// SetSetIdentifier sets the SetIdentifier field's value. -func (s *ResourceRecordSet) SetSetIdentifier(v string) *ResourceRecordSet { - s.SetIdentifier = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *ResourceRecordSet) SetTTL(v int64) *ResourceRecordSet { - s.TTL = &v - return s -} - -// SetTrafficPolicyInstanceId sets the TrafficPolicyInstanceId field's value. -func (s *ResourceRecordSet) SetTrafficPolicyInstanceId(v string) *ResourceRecordSet { - s.TrafficPolicyInstanceId = &v - return s -} - -// SetType sets the Type field's value. -func (s *ResourceRecordSet) SetType(v string) *ResourceRecordSet { - s.Type = &v - return s -} - -// SetWeight sets the Weight field's value. -func (s *ResourceRecordSet) SetWeight(v int64) *ResourceRecordSet { - s.Weight = &v - return s -} - -// A complex type containing a resource and its associated tags. -type ResourceTagSet struct { - _ struct{} `type:"structure"` - - // The ID for the specified resource. - ResourceId *string `type:"string"` - - // The type of the resource. - // - // * The resource type for health checks is healthcheck. - // - // * The resource type for hosted zones is hostedzone. - ResourceType *string `type:"string" enum:"TagResourceType"` - - // The tags associated with the specified resource. - Tags []*Tag `locationNameList:"Tag" min:"1" type:"list"` -} - -// String returns the string representation -func (s ResourceTagSet) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ResourceTagSet) GoString() string { - return s.String() -} - -// SetResourceId sets the ResourceId field's value. -func (s *ResourceTagSet) SetResourceId(v string) *ResourceTagSet { - s.ResourceId = &v - return s -} - -// SetResourceType sets the ResourceType field's value. -func (s *ResourceTagSet) SetResourceType(v string) *ResourceTagSet { - s.ResourceType = &v - return s -} - -// SetTags sets the Tags field's value. -func (s *ResourceTagSet) SetTags(v []*Tag) *ResourceTagSet { - s.Tags = v - return s -} - -// A complex type that contains the type of limit that you specified in the -// request and the current value for that limit. -type ReusableDelegationSetLimit struct { - _ struct{} `type:"structure"` - - // The limit that you requested: MAX_ZONES_BY_REUSABLE_DELEGATION_SET, the maximum - // number of hosted zones that you can associate with the specified reusable - // delegation set. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"ReusableDelegationSetLimitType"` - - // The current value for the MAX_ZONES_BY_REUSABLE_DELEGATION_SET limit. - // - // Value is a required field - Value *int64 `min:"1" type:"long" required:"true"` -} - -// String returns the string representation -func (s ReusableDelegationSetLimit) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s ReusableDelegationSetLimit) GoString() string { - return s.String() -} - -// SetType sets the Type field's value. -func (s *ReusableDelegationSetLimit) SetType(v string) *ReusableDelegationSetLimit { - s.Type = &v - return s -} - -// SetValue sets the Value field's value. -func (s *ReusableDelegationSetLimit) SetValue(v int64) *ReusableDelegationSetLimit { - s.Value = &v - return s -} - -// A complex type that contains the status that one Amazon Route 53 health checker -// reports and the time of the health check. -type StatusReport struct { - _ struct{} `type:"structure"` - - // The date and time that the health checker performed the health check in ISO - // 8601 format (https://en.wikipedia.org/wiki/ISO_8601) and Coordinated Universal - // Time (UTC). For example, the value 2017-03-27T17:48:16.751Z represents March - // 27, 2017 at 17:48:16.751 UTC. - CheckedTime *time.Time `type:"timestamp" timestampFormat:"iso8601"` - - // A description of the status of the health check endpoint as reported by one - // of the Amazon Route 53 health checkers. - Status *string `type:"string"` -} - -// String returns the string representation -func (s StatusReport) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s StatusReport) GoString() string { - return s.String() -} - -// SetCheckedTime sets the CheckedTime field's value. -func (s *StatusReport) SetCheckedTime(v time.Time) *StatusReport { - s.CheckedTime = &v - return s -} - -// SetStatus sets the Status field's value. -func (s *StatusReport) SetStatus(v string) *StatusReport { - s.Status = &v - return s -} - -// A complex type that contains information about a tag that you want to add -// or edit for the specified health check or hosted zone. -type Tag struct { - _ struct{} `type:"structure"` - - // The value of Key depends on the operation that you want to perform: - // - // * Add a tag to a health check or hosted zone: Key is the name that you - // want to give the new tag. - // - // * Edit a tag: Key is the name of the tag that you want to change the Value - // for. - // - // * Delete a key: Key is the name of the tag you want to remove. - // - // * Give a name to a health check: Edit the default Name tag. In the Amazon - // Route 53 console, the list of your health checks includes a Name column - // that lets you see the name that you've given to each health check. - Key *string `type:"string"` - - // The value of Value depends on the operation that you want to perform: - // - // * Add a tag to a health check or hosted zone: Value is the value that - // you want to give the new tag. - // - // * Edit a tag: Value is the new value that you want to assign the tag. - Value *string `type:"string"` -} - -// String returns the string representation -func (s Tag) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Tag) GoString() string { - return s.String() -} - -// SetKey sets the Key field's value. -func (s *Tag) SetKey(v string) *Tag { - s.Key = &v - return s -} - -// SetValue sets the Value field's value. -func (s *Tag) SetValue(v string) *Tag { - s.Value = &v - return s -} - -// Gets the value that Amazon Route 53 returns in response to a DNS request -// for a specified record name and type. You can optionally specify the IP address -// of a DNS resolver, an EDNS0 client subnet IP address, and a subnet mask. -type TestDNSAnswerInput struct { - _ struct{} `type:"structure"` - - // If the resolver that you specified for resolverip supports EDNS0, specify - // the IPv4 or IPv6 address of a client in the applicable location, for example, - // 192.0.2.44 or 2001:db8:85a3::8a2e:370:7334. - EDNS0ClientSubnetIP *string `location:"querystring" locationName:"edns0clientsubnetip" type:"string"` - - // If you specify an IP address for edns0clientsubnetip, you can optionally - // specify the number of bits of the IP address that you want the checking tool - // to include in the DNS query. For example, if you specify 192.0.2.44 for edns0clientsubnetip - // and 24 for edns0clientsubnetmask, the checking tool will simulate a request - // from 192.0.2.0/24. The default value is 24 bits for IPv4 addresses and 64 - // bits for IPv6 addresses. - EDNS0ClientSubnetMask *string `location:"querystring" locationName:"edns0clientsubnetmask" type:"string"` - - // The ID of the hosted zone that you want Amazon Route 53 to simulate a query - // for. - // - // HostedZoneId is a required field - HostedZoneId *string `location:"querystring" locationName:"hostedzoneid" type:"string" required:"true"` - - // The name of the resource record set that you want Amazon Route 53 to simulate - // a query for. - // - // RecordName is a required field - RecordName *string `location:"querystring" locationName:"recordname" type:"string" required:"true"` - - // The type of the resource record set. - // - // RecordType is a required field - RecordType *string `location:"querystring" locationName:"recordtype" type:"string" required:"true" enum:"RRType"` - - // If you want to simulate a request from a specific DNS resolver, specify the - // IP address for that resolver. If you omit this value, TestDnsAnswer uses - // the IP address of a DNS resolver in the AWS US East (N. Virginia) Region - // (us-east-1). - ResolverIP *string `location:"querystring" locationName:"resolverip" type:"string"` -} - -// String returns the string representation -func (s TestDNSAnswerInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TestDNSAnswerInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *TestDNSAnswerInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "TestDNSAnswerInput"} - if s.HostedZoneId == nil { - invalidParams.Add(request.NewErrParamRequired("HostedZoneId")) - } - if s.RecordName == nil { - invalidParams.Add(request.NewErrParamRequired("RecordName")) - } - if s.RecordType == nil { - invalidParams.Add(request.NewErrParamRequired("RecordType")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEDNS0ClientSubnetIP sets the EDNS0ClientSubnetIP field's value. -func (s *TestDNSAnswerInput) SetEDNS0ClientSubnetIP(v string) *TestDNSAnswerInput { - s.EDNS0ClientSubnetIP = &v - return s -} - -// SetEDNS0ClientSubnetMask sets the EDNS0ClientSubnetMask field's value. -func (s *TestDNSAnswerInput) SetEDNS0ClientSubnetMask(v string) *TestDNSAnswerInput { - s.EDNS0ClientSubnetMask = &v - return s -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *TestDNSAnswerInput) SetHostedZoneId(v string) *TestDNSAnswerInput { - s.HostedZoneId = &v - return s -} - -// SetRecordName sets the RecordName field's value. -func (s *TestDNSAnswerInput) SetRecordName(v string) *TestDNSAnswerInput { - s.RecordName = &v - return s -} - -// SetRecordType sets the RecordType field's value. -func (s *TestDNSAnswerInput) SetRecordType(v string) *TestDNSAnswerInput { - s.RecordType = &v - return s -} - -// SetResolverIP sets the ResolverIP field's value. -func (s *TestDNSAnswerInput) SetResolverIP(v string) *TestDNSAnswerInput { - s.ResolverIP = &v - return s -} - -// A complex type that contains the response to a TestDNSAnswer request. -type TestDNSAnswerOutput struct { - _ struct{} `type:"structure"` - - // The Amazon Route 53 name server used to respond to the request. - // - // Nameserver is a required field - Nameserver *string `type:"string" required:"true"` - - // The protocol that Amazon Route 53 used to respond to the request, either - // UDP or TCP. - // - // Protocol is a required field - Protocol *string `type:"string" required:"true"` - - // A list that contains values that Amazon Route 53 returned for this resource - // record set. - // - // RecordData is a required field - RecordData []*string `locationNameList:"RecordDataEntry" type:"list" required:"true"` - - // The name of the resource record set that you submitted a request for. - // - // RecordName is a required field - RecordName *string `type:"string" required:"true"` - - // The type of the resource record set that you submitted a request for. - // - // RecordType is a required field - RecordType *string `type:"string" required:"true" enum:"RRType"` - - // A code that indicates whether the request is valid or not. The most common - // response code is NOERROR, meaning that the request is valid. If the response - // is not valid, Amazon Route 53 returns a response code that describes the - // error. For a list of possible response codes, see DNS RCODES (http://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-6) - // on the IANA website. - // - // ResponseCode is a required field - ResponseCode *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s TestDNSAnswerOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TestDNSAnswerOutput) GoString() string { - return s.String() -} - -// SetNameserver sets the Nameserver field's value. -func (s *TestDNSAnswerOutput) SetNameserver(v string) *TestDNSAnswerOutput { - s.Nameserver = &v - return s -} - -// SetProtocol sets the Protocol field's value. -func (s *TestDNSAnswerOutput) SetProtocol(v string) *TestDNSAnswerOutput { - s.Protocol = &v - return s -} - -// SetRecordData sets the RecordData field's value. -func (s *TestDNSAnswerOutput) SetRecordData(v []*string) *TestDNSAnswerOutput { - s.RecordData = v - return s -} - -// SetRecordName sets the RecordName field's value. -func (s *TestDNSAnswerOutput) SetRecordName(v string) *TestDNSAnswerOutput { - s.RecordName = &v - return s -} - -// SetRecordType sets the RecordType field's value. -func (s *TestDNSAnswerOutput) SetRecordType(v string) *TestDNSAnswerOutput { - s.RecordType = &v - return s -} - -// SetResponseCode sets the ResponseCode field's value. -func (s *TestDNSAnswerOutput) SetResponseCode(v string) *TestDNSAnswerOutput { - s.ResponseCode = &v - return s -} - -// A complex type that contains settings for a traffic policy. -type TrafficPolicy struct { - _ struct{} `type:"structure"` - - // The comment that you specify in the CreateTrafficPolicy request, if any. - Comment *string `type:"string"` - - // The definition of a traffic policy in JSON format. You specify the JSON document - // to use for a new traffic policy in the CreateTrafficPolicy request. For more - // information about the JSON format, see Traffic Policy Document Format (http://docs.aws.amazon.com/Route53/latest/APIReference/api-policies-traffic-policy-document-format.html). - // - // Document is a required field - Document *string `type:"string" required:"true"` - - // The ID that Amazon Route 53 assigned to a traffic policy when you created - // it. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // The name that you specified when you created the traffic policy. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The DNS type of the resource record sets that Amazon Route 53 creates when - // you use a traffic policy to create a traffic policy instance. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` - - // The version number that Amazon Route 53 assigns to a traffic policy. For - // a new traffic policy, the value of Version is always 1. - // - // Version is a required field - Version *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s TrafficPolicy) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicy) GoString() string { - return s.String() -} - -// SetComment sets the Comment field's value. -func (s *TrafficPolicy) SetComment(v string) *TrafficPolicy { - s.Comment = &v - return s -} - -// SetDocument sets the Document field's value. -func (s *TrafficPolicy) SetDocument(v string) *TrafficPolicy { - s.Document = &v - return s -} - -// SetId sets the Id field's value. -func (s *TrafficPolicy) SetId(v string) *TrafficPolicy { - s.Id = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicy) SetName(v string) *TrafficPolicy { - s.Name = &v - return s -} - -// SetType sets the Type field's value. -func (s *TrafficPolicy) SetType(v string) *TrafficPolicy { - s.Type = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *TrafficPolicy) SetVersion(v int64) *TrafficPolicy { - s.Version = &v - return s -} - -// A complex type that contains settings for the new traffic policy instance. -type TrafficPolicyInstance struct { - _ struct{} `type:"structure"` - - // The ID of the hosted zone that Amazon Route 53 created resource record sets - // in. - // - // HostedZoneId is a required field - HostedZoneId *string `type:"string" required:"true"` - - // The ID that Amazon Route 53 assigned to the new traffic policy instance. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // If State is Failed, an explanation of the reason for the failure. If State - // is another value, Message is empty. - // - // Message is a required field - Message *string `type:"string" required:"true"` - - // The DNS name, such as www.example.com, for which Amazon Route 53 responds - // to queries by using the resource record sets that are associated with this - // traffic policy instance. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The value of State is one of the following values: - // - // AppliedAmazon Route 53 has finished creating resource record sets, and changes - // have propagated to all Amazon Route 53 edge locations. - // - // CreatingAmazon Route 53 is creating the resource record sets. Use GetTrafficPolicyInstance - // to confirm that the CreateTrafficPolicyInstance request completed successfully. - // - // FailedAmazon Route 53 wasn't able to create or update the resource record - // sets. When the value of State is Failed, see Message for an explanation of - // what caused the request to fail. - // - // State is a required field - State *string `type:"string" required:"true"` - - // The TTL that Amazon Route 53 assigned to all of the resource record sets - // that it created in the specified hosted zone. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that Amazon Route 53 used to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The DNS type that Amazon Route 53 assigned to all of the resource record - // sets that it created for this traffic policy instance. - // - // TrafficPolicyType is a required field - TrafficPolicyType *string `type:"string" required:"true" enum:"RRType"` - - // The version of the traffic policy that Amazon Route 53 used to create resource - // record sets in the specified hosted zone. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s TrafficPolicyInstance) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicyInstance) GoString() string { - return s.String() -} - -// SetHostedZoneId sets the HostedZoneId field's value. -func (s *TrafficPolicyInstance) SetHostedZoneId(v string) *TrafficPolicyInstance { - s.HostedZoneId = &v - return s -} - -// SetId sets the Id field's value. -func (s *TrafficPolicyInstance) SetId(v string) *TrafficPolicyInstance { - s.Id = &v - return s -} - -// SetMessage sets the Message field's value. -func (s *TrafficPolicyInstance) SetMessage(v string) *TrafficPolicyInstance { - s.Message = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicyInstance) SetName(v string) *TrafficPolicyInstance { - s.Name = &v - return s -} - -// SetState sets the State field's value. -func (s *TrafficPolicyInstance) SetState(v string) *TrafficPolicyInstance { - s.State = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *TrafficPolicyInstance) SetTTL(v int64) *TrafficPolicyInstance { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyId(v string) *TrafficPolicyInstance { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyType sets the TrafficPolicyType field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyType(v string) *TrafficPolicyInstance { - s.TrafficPolicyType = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *TrafficPolicyInstance) SetTrafficPolicyVersion(v int64) *TrafficPolicyInstance { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains information about the latest version of one -// traffic policy that is associated with the current AWS account. -type TrafficPolicySummary struct { - _ struct{} `type:"structure"` - - // The ID that Amazon Route 53 assigned to the traffic policy when you created - // it. - // - // Id is a required field - Id *string `min:"1" type:"string" required:"true"` - - // The version number of the latest version of the traffic policy. - // - // LatestVersion is a required field - LatestVersion *int64 `min:"1" type:"integer" required:"true"` - - // The name that you specified for the traffic policy when you created it. - // - // Name is a required field - Name *string `type:"string" required:"true"` - - // The number of traffic policies that are associated with the current AWS account. - // - // TrafficPolicyCount is a required field - TrafficPolicyCount *int64 `min:"1" type:"integer" required:"true"` - - // The DNS type of the resource record sets that Amazon Route 53 creates when - // you use a traffic policy to create a traffic policy instance. - // - // Type is a required field - Type *string `type:"string" required:"true" enum:"RRType"` -} - -// String returns the string representation -func (s TrafficPolicySummary) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s TrafficPolicySummary) GoString() string { - return s.String() -} - -// SetId sets the Id field's value. -func (s *TrafficPolicySummary) SetId(v string) *TrafficPolicySummary { - s.Id = &v - return s -} - -// SetLatestVersion sets the LatestVersion field's value. -func (s *TrafficPolicySummary) SetLatestVersion(v int64) *TrafficPolicySummary { - s.LatestVersion = &v - return s -} - -// SetName sets the Name field's value. -func (s *TrafficPolicySummary) SetName(v string) *TrafficPolicySummary { - s.Name = &v - return s -} - -// SetTrafficPolicyCount sets the TrafficPolicyCount field's value. -func (s *TrafficPolicySummary) SetTrafficPolicyCount(v int64) *TrafficPolicySummary { - s.TrafficPolicyCount = &v - return s -} - -// SetType sets the Type field's value. -func (s *TrafficPolicySummary) SetType(v string) *TrafficPolicySummary { - s.Type = &v - return s -} - -// A complex type that contains information about a request to update a health -// check. -type UpdateHealthCheckInput struct { - _ struct{} `locationName:"UpdateHealthCheckRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // A complex type that identifies the CloudWatch alarm that you want Amazon - // Route 53 health checkers to use to determine whether this health check is - // healthy. - AlarmIdentifier *AlarmIdentifier `type:"structure"` - - // A complex type that contains one ChildHealthCheck element for each health - // check that you want to associate with a CALCULATED health check. - ChildHealthChecks []*string `locationNameList:"ChildHealthCheck" type:"list"` - - // Specify whether you want Amazon Route 53 to send the value of FullyQualifiedDomainName - // to the endpoint in the client_hello message during TLS negotiation. This - // allows the endpoint to respond to HTTPS health check requests with the applicable - // SSL/TLS certificate. - // - // Some endpoints require that HTTPS requests include the host name in the client_hello - // message. If you don't enable SNI, the status of the health check will be - // SSL alert handshake_failure. A health check can also have that status for - // other reasons. If SNI is enabled and you're still getting the error, check - // the SSL/TLS configuration on your endpoint and confirm that your certificate - // is valid. - // - // The SSL/TLS certificate on your endpoint includes a domain name in the Common - // Name field and possibly several more in the Subject Alternative Names field. - // One of the domain names in the certificate should match the value that you - // specify for FullyQualifiedDomainName. If the endpoint responds to the client_hello - // message with a certificate that does not include the domain name that you - // specified in FullyQualifiedDomainName, a health checker will retry the handshake. - // In the second attempt, the health checker will omit FullyQualifiedDomainName - // from the client_hello message. - EnableSNI *bool `type:"boolean"` - - // The number of consecutive health checks that an endpoint must pass or fail - // for Amazon Route 53 to change the current status of the endpoint from unhealthy - // to healthy or vice versa. For more information, see How Amazon Route 53 Determines - // Whether an Endpoint Is Healthy (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html) - // in the Amazon Route 53 Developer Guide. - // - // If you don't specify a value for FailureThreshold, the default value is three - // health checks. - FailureThreshold *int64 `min:"1" type:"integer"` - - // Amazon Route 53 behavior depends on whether you specify a value for IPAddress. - // - // If a health check already has a value for IPAddress, you can change the value. - // However, you can't update an existing health check to add or remove the value - // of IPAddress. - // - // If you specify a value forIPAddress: - // - // Amazon Route 53 sends health check requests to the specified IPv4 or IPv6 - // address and passes the value of FullyQualifiedDomainName in the Host header - // for all health checks except TCP health checks. This is typically the fully - // qualified DNS name of the endpoint on which you want Amazon Route 53 to perform - // health checks. - // - // When Amazon Route 53 checks the health of an endpoint, here is how it constructs - // the Host header: - // - // * If you specify a value of 80 for Port and HTTP or HTTP_STR_MATCH for - // Type, Amazon Route 53 passes the value of FullyQualifiedDomainName to - // the endpoint in the Host header. - // - // * If you specify a value of 443 for Port and HTTPS or HTTPS_STR_MATCH - // for Type, Amazon Route 53 passes the value of FullyQualifiedDomainName - // to the endpoint in the Host header. - // - // * If you specify another value for Port and any value except TCP for Type, - // Amazon Route 53 passes FullyQualifiedDomainName:Port to the endpoint in - // the Host header. - // - // If you don't specify a value for FullyQualifiedDomainName, Amazon Route 53 - // substitutes the value of IPAddress in the Host header in each of the above - // cases. - // - // If you don't specify a value forIPAddress: - // - // If you don't specify a value for IPAddress, Amazon Route 53 sends a DNS request - // to the domain that you specify in FullyQualifiedDomainName at the interval - // you specify in RequestInterval. Using an IPv4 address that is returned by - // DNS, Amazon Route 53 then checks the health of the endpoint. - // - // If you don't specify a value for IPAddress, Amazon Route 53 uses only IPv4 - // to send health checks to the endpoint. If there's no resource record set - // with a type of A for the name that you specify for FullyQualifiedDomainName, - // the health check fails with a "DNS resolution failed" error. - // - // If you want to check the health of weighted, latency, or failover resource - // record sets and you choose to specify the endpoint only by FullyQualifiedDomainName, - // we recommend that you create a separate health check for each endpoint. For - // example, create a health check for each HTTP server that is serving content - // for www.example.com. For the value of FullyQualifiedDomainName, specify the - // domain name of the server (such as us-east-2-www.example.com), not the name - // of the resource record sets (www.example.com). - // - // In this configuration, if the value of FullyQualifiedDomainName matches the - // name of the resource record sets and you then associate the health check - // with those resource record sets, health check results will be unpredictable. - // - // In addition, if the value of Type is HTTP, HTTPS, HTTP_STR_MATCH, or HTTPS_STR_MATCH, - // Amazon Route 53 passes the value of FullyQualifiedDomainName in the Host - // header, as it does when you specify a value for IPAddress. If the value of - // Type is TCP, Amazon Route 53 doesn't pass a Host header. - FullyQualifiedDomainName *string `type:"string"` - - // The ID for the health check for which you want detailed information. When - // you created the health check, CreateHealthCheck returned the ID in the response, - // in the HealthCheckId element. - // - // HealthCheckId is a required field - HealthCheckId *string `location:"uri" locationName:"HealthCheckId" type:"string" required:"true"` - - // A sequential counter that Amazon Route 53 sets to 1 when you create a health - // check and increments by 1 each time you update settings for the health check. - // - // We recommend that you use GetHealthCheck or ListHealthChecks to get the current - // value of HealthCheckVersion for the health check that you want to update, - // and that you include that value in your UpdateHealthCheck request. This prevents - // Amazon Route 53 from overwriting an intervening update: - // - // * If the value in the UpdateHealthCheck request matches the value of HealthCheckVersion - // in the health check, Amazon Route 53 updates the health check with the - // new settings. - // - // * If the value of HealthCheckVersion in the health check is greater, the - // health check was changed after you got the version number. Amazon Route - // 53 does not update the health check, and it returns a HealthCheckVersionMismatch - // error. - HealthCheckVersion *int64 `min:"1" type:"long"` - - // The number of child health checks that are associated with a CALCULATED health - // that Amazon Route 53 must consider healthy for the CALCULATED health check - // to be considered healthy. To specify the child health checks that you want - // to associate with a CALCULATED health check, use the ChildHealthChecks and - // ChildHealthCheck elements. - // - // Note the following: - // - // * If you specify a number greater than the number of child health checks, - // Amazon Route 53 always considers this health check to be unhealthy. - // - // * If you specify 0, Amazon Route 53 always considers this health check - // to be healthy. - HealthThreshold *int64 `type:"integer"` - - // The IPv4 or IPv6 IP address for the endpoint that you want Amazon Route 53 - // to perform health checks on. If you don't specify a value for IPAddress, - // Amazon Route 53 sends a DNS request to resolve the domain name that you specify - // in FullyQualifiedDomainName at the interval that you specify in RequestInterval. - // Using an IP address that is returned by DNS, Amazon Route 53 then checks - // the health of the endpoint. - // - // Use one of the following formats for the value of IPAddress: - // - // * IPv4 address: four values between 0 and 255, separated by periods (.), - // for example, 192.0.2.44. - // - // * IPv6 address: eight groups of four hexadecimal values, separated by - // colons (:), for example, 2001:0db8:85a3:0000:0000:abcd:0001:2345. You - // can also shorten IPv6 addresses as described in RFC 5952, for example, - // 2001:db8:85a3::abcd:1:2345. - // - // If the endpoint is an EC2 instance, we recommend that you create an Elastic - // IP address, associate it with your EC2 instance, and specify the Elastic - // IP address for IPAddress. This ensures that the IP address of your instance - // never changes. For more information, see the applicable documentation: - // - // * Linux: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html) - // in the Amazon EC2 User Guide for Linux Instances - // - // * Windows: Elastic IP Addresses (EIP) (http://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/elastic-ip-addresses-eip.html) - // in the Amazon EC2 User Guide for Windows Instances - // - // If a health check already has a value for IPAddress, you can change the value. - // However, you can't update an existing health check to add or remove the value - // of IPAddress. - // - // For more information, see UpdateHealthCheckRequest$FullyQualifiedDomainName. - // - // Constraints: Amazon Route 53 can't check the health of endpoints for which - // the IP address is in local, private, non-routable, or multicast ranges. For - // more information about IP addresses for which you can't create health checks, - // see the following documents: - // - // * RFC 5735, Special Use IPv4 Addresses (https://tools.ietf.org/html/rfc5735) - // - // * RFC 6598, IANA-Reserved IPv4 Prefix for Shared Address Space (https://tools.ietf.org/html/rfc6598) - // - // * RFC 5156, Special-Use IPv6 Addresses (https://tools.ietf.org/html/rfc5156) - IPAddress *string `type:"string"` - - // When CloudWatch has insufficient data about the metric to determine the alarm - // state, the status that you want Amazon Route 53 to assign to the health check: - // - // * Healthy: Amazon Route 53 considers the health check to be healthy. - // - // * Unhealthy: Amazon Route 53 considers the health check to be unhealthy. - // - // * LastKnownStatus: Amazon Route 53 uses the status of the health check - // from the last time CloudWatch had sufficient data to determine the alarm - // state. For new health checks that have no last known status, the default - // status for the health check is healthy. - InsufficientDataHealthStatus *string `type:"string" enum:"InsufficientDataHealthStatus"` - - // Specify whether you want Amazon Route 53 to invert the status of a health - // check, for example, to consider a health check unhealthy when it otherwise - // would be considered healthy. - Inverted *bool `type:"boolean"` - - // The port on the endpoint on which you want Amazon Route 53 to perform health - // checks. - Port *int64 `min:"1" type:"integer"` - - // A complex type that contains one Region element for each region that you - // want Amazon Route 53 health checkers to check the specified endpoint from. - Regions []*string `locationNameList:"Region" min:"3" type:"list"` - - // A complex type that contains one ResettableElementName element for each element - // that you want to reset to the default value. Valid values for ResettableElementName - // include the following: - // - // * ChildHealthChecks: Amazon Route 53 resets HealthCheckConfig$ChildHealthChecks - // to null. - // - // * FullyQualifiedDomainName: Amazon Route 53 resets HealthCheckConfig$FullyQualifiedDomainName - // to null. - // - // * Regions: Amazon Route 53 resets the HealthCheckConfig$Regions list to - // the default set of regions. - // - // * ResourcePath: Amazon Route 53 resets HealthCheckConfig$ResourcePath - // to null. - ResetElements []*string `locationNameList:"ResettableElementName" type:"list"` - - // The path that you want Amazon Route 53 to request when performing health - // checks. The path can be any value for which your endpoint will return an - // HTTP status code of 2xx or 3xx when the endpoint is healthy, for example - // the file /docs/route53-health-check.html. - // - // Specify this value only if you want to change it. - ResourcePath *string `type:"string"` - - // If the value of Type is HTTP_STR_MATCH or HTTP_STR_MATCH, the string that - // you want Amazon Route 53 to search for in the response body from the specified - // resource. If the string appears in the response body, Amazon Route 53 considers - // the resource healthy. (You can't change the value of Type when you update - // a health check.) - SearchString *string `type:"string"` -} - -// String returns the string representation -func (s UpdateHealthCheckInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHealthCheckInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateHealthCheckInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateHealthCheckInput"} - if s.FailureThreshold != nil && *s.FailureThreshold < 1 { - invalidParams.Add(request.NewErrParamMinValue("FailureThreshold", 1)) - } - if s.HealthCheckId == nil { - invalidParams.Add(request.NewErrParamRequired("HealthCheckId")) - } - if s.HealthCheckVersion != nil && *s.HealthCheckVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("HealthCheckVersion", 1)) - } - if s.Port != nil && *s.Port < 1 { - invalidParams.Add(request.NewErrParamMinValue("Port", 1)) - } - if s.Regions != nil && len(s.Regions) < 3 { - invalidParams.Add(request.NewErrParamMinLen("Regions", 3)) - } - if s.AlarmIdentifier != nil { - if err := s.AlarmIdentifier.Validate(); err != nil { - invalidParams.AddNested("AlarmIdentifier", err.(request.ErrInvalidParams)) - } - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetAlarmIdentifier sets the AlarmIdentifier field's value. -func (s *UpdateHealthCheckInput) SetAlarmIdentifier(v *AlarmIdentifier) *UpdateHealthCheckInput { - s.AlarmIdentifier = v - return s -} - -// SetChildHealthChecks sets the ChildHealthChecks field's value. -func (s *UpdateHealthCheckInput) SetChildHealthChecks(v []*string) *UpdateHealthCheckInput { - s.ChildHealthChecks = v - return s -} - -// SetEnableSNI sets the EnableSNI field's value. -func (s *UpdateHealthCheckInput) SetEnableSNI(v bool) *UpdateHealthCheckInput { - s.EnableSNI = &v - return s -} - -// SetFailureThreshold sets the FailureThreshold field's value. -func (s *UpdateHealthCheckInput) SetFailureThreshold(v int64) *UpdateHealthCheckInput { - s.FailureThreshold = &v - return s -} - -// SetFullyQualifiedDomainName sets the FullyQualifiedDomainName field's value. -func (s *UpdateHealthCheckInput) SetFullyQualifiedDomainName(v string) *UpdateHealthCheckInput { - s.FullyQualifiedDomainName = &v - return s -} - -// SetHealthCheckId sets the HealthCheckId field's value. -func (s *UpdateHealthCheckInput) SetHealthCheckId(v string) *UpdateHealthCheckInput { - s.HealthCheckId = &v - return s -} - -// SetHealthCheckVersion sets the HealthCheckVersion field's value. -func (s *UpdateHealthCheckInput) SetHealthCheckVersion(v int64) *UpdateHealthCheckInput { - s.HealthCheckVersion = &v - return s -} - -// SetHealthThreshold sets the HealthThreshold field's value. -func (s *UpdateHealthCheckInput) SetHealthThreshold(v int64) *UpdateHealthCheckInput { - s.HealthThreshold = &v - return s -} - -// SetIPAddress sets the IPAddress field's value. -func (s *UpdateHealthCheckInput) SetIPAddress(v string) *UpdateHealthCheckInput { - s.IPAddress = &v - return s -} - -// SetInsufficientDataHealthStatus sets the InsufficientDataHealthStatus field's value. -func (s *UpdateHealthCheckInput) SetInsufficientDataHealthStatus(v string) *UpdateHealthCheckInput { - s.InsufficientDataHealthStatus = &v - return s -} - -// SetInverted sets the Inverted field's value. -func (s *UpdateHealthCheckInput) SetInverted(v bool) *UpdateHealthCheckInput { - s.Inverted = &v - return s -} - -// SetPort sets the Port field's value. -func (s *UpdateHealthCheckInput) SetPort(v int64) *UpdateHealthCheckInput { - s.Port = &v - return s -} - -// SetRegions sets the Regions field's value. -func (s *UpdateHealthCheckInput) SetRegions(v []*string) *UpdateHealthCheckInput { - s.Regions = v - return s -} - -// SetResetElements sets the ResetElements field's value. -func (s *UpdateHealthCheckInput) SetResetElements(v []*string) *UpdateHealthCheckInput { - s.ResetElements = v - return s -} - -// SetResourcePath sets the ResourcePath field's value. -func (s *UpdateHealthCheckInput) SetResourcePath(v string) *UpdateHealthCheckInput { - s.ResourcePath = &v - return s -} - -// SetSearchString sets the SearchString field's value. -func (s *UpdateHealthCheckInput) SetSearchString(v string) *UpdateHealthCheckInput { - s.SearchString = &v - return s -} - -type UpdateHealthCheckOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains information about one health check that is associated - // with the current AWS account. - // - // HealthCheck is a required field - HealthCheck *HealthCheck `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateHealthCheckOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHealthCheckOutput) GoString() string { - return s.String() -} - -// SetHealthCheck sets the HealthCheck field's value. -func (s *UpdateHealthCheckOutput) SetHealthCheck(v *HealthCheck) *UpdateHealthCheckOutput { - s.HealthCheck = v - return s -} - -// A request to update the comment for a hosted zone. -type UpdateHostedZoneCommentInput struct { - _ struct{} `locationName:"UpdateHostedZoneCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The new comment for the hosted zone. If you don't specify a value for Comment, - // Amazon Route 53 deletes the existing value of the Comment element, if any. - Comment *string `type:"string"` - - // The ID for the hosted zone that you want to update the comment for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" type:"string" required:"true"` -} - -// String returns the string representation -func (s UpdateHostedZoneCommentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHostedZoneCommentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateHostedZoneCommentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateHostedZoneCommentInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *UpdateHostedZoneCommentInput) SetComment(v string) *UpdateHostedZoneCommentInput { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *UpdateHostedZoneCommentInput) SetId(v string) *UpdateHostedZoneCommentInput { - s.Id = &v - return s -} - -// A complex type that contains the response to the UpdateHostedZoneComment -// request. -type UpdateHostedZoneCommentOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains general information about the hosted zone. - // - // HostedZone is a required field - HostedZone *HostedZone `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateHostedZoneCommentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateHostedZoneCommentOutput) GoString() string { - return s.String() -} - -// SetHostedZone sets the HostedZone field's value. -func (s *UpdateHostedZoneCommentOutput) SetHostedZone(v *HostedZone) *UpdateHostedZoneCommentOutput { - s.HostedZone = v - return s -} - -// A complex type that contains information about the traffic policy that you -// want to update the comment for. -type UpdateTrafficPolicyCommentInput struct { - _ struct{} `locationName:"UpdateTrafficPolicyCommentRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The new comment for the specified traffic policy and version. - // - // Comment is a required field - Comment *string `type:"string" required:"true"` - - // The value of Id for the traffic policy that you want to update the comment - // for. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The value of Version for the traffic policy that you want to update the comment - // for. - // - // Version is a required field - Version *int64 `location:"uri" locationName:"Version" min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyCommentInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyCommentInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTrafficPolicyCommentInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTrafficPolicyCommentInput"} - if s.Comment == nil { - invalidParams.Add(request.NewErrParamRequired("Comment")) - } - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.Version == nil { - invalidParams.Add(request.NewErrParamRequired("Version")) - } - if s.Version != nil && *s.Version < 1 { - invalidParams.Add(request.NewErrParamMinValue("Version", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetComment sets the Comment field's value. -func (s *UpdateTrafficPolicyCommentInput) SetComment(v string) *UpdateTrafficPolicyCommentInput { - s.Comment = &v - return s -} - -// SetId sets the Id field's value. -func (s *UpdateTrafficPolicyCommentInput) SetId(v string) *UpdateTrafficPolicyCommentInput { - s.Id = &v - return s -} - -// SetVersion sets the Version field's value. -func (s *UpdateTrafficPolicyCommentInput) SetVersion(v int64) *UpdateTrafficPolicyCommentInput { - s.Version = &v - return s -} - -// A complex type that contains the response information for the traffic policy. -type UpdateTrafficPolicyCommentOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the specified traffic policy. - // - // TrafficPolicy is a required field - TrafficPolicy *TrafficPolicy `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyCommentOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyCommentOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicy sets the TrafficPolicy field's value. -func (s *UpdateTrafficPolicyCommentOutput) SetTrafficPolicy(v *TrafficPolicy) *UpdateTrafficPolicyCommentOutput { - s.TrafficPolicy = v - return s -} - -// A complex type that contains information about the resource record sets that -// you want to update based on a specified traffic policy instance. -type UpdateTrafficPolicyInstanceInput struct { - _ struct{} `locationName:"UpdateTrafficPolicyInstanceRequest" type:"structure" xmlURI:"https://route53.amazonaws.com/doc/2013-04-01/"` - - // The ID of the traffic policy instance that you want to update. - // - // Id is a required field - Id *string `location:"uri" locationName:"Id" min:"1" type:"string" required:"true"` - - // The TTL that you want Amazon Route 53 to assign to all of the updated resource - // record sets. - // - // TTL is a required field - TTL *int64 `type:"long" required:"true"` - - // The ID of the traffic policy that you want Amazon Route 53 to use to update - // resource record sets for the specified traffic policy instance. - // - // TrafficPolicyId is a required field - TrafficPolicyId *string `min:"1" type:"string" required:"true"` - - // The version of the traffic policy that you want Amazon Route 53 to use to - // update resource record sets for the specified traffic policy instance. - // - // TrafficPolicyVersion is a required field - TrafficPolicyVersion *int64 `min:"1" type:"integer" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyInstanceInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyInstanceInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *UpdateTrafficPolicyInstanceInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "UpdateTrafficPolicyInstanceInput"} - if s.Id == nil { - invalidParams.Add(request.NewErrParamRequired("Id")) - } - if s.Id != nil && len(*s.Id) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Id", 1)) - } - if s.TTL == nil { - invalidParams.Add(request.NewErrParamRequired("TTL")) - } - if s.TrafficPolicyId == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyId")) - } - if s.TrafficPolicyId != nil && len(*s.TrafficPolicyId) < 1 { - invalidParams.Add(request.NewErrParamMinLen("TrafficPolicyId", 1)) - } - if s.TrafficPolicyVersion == nil { - invalidParams.Add(request.NewErrParamRequired("TrafficPolicyVersion")) - } - if s.TrafficPolicyVersion != nil && *s.TrafficPolicyVersion < 1 { - invalidParams.Add(request.NewErrParamMinValue("TrafficPolicyVersion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetId sets the Id field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetId(v string) *UpdateTrafficPolicyInstanceInput { - s.Id = &v - return s -} - -// SetTTL sets the TTL field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTTL(v int64) *UpdateTrafficPolicyInstanceInput { - s.TTL = &v - return s -} - -// SetTrafficPolicyId sets the TrafficPolicyId field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTrafficPolicyId(v string) *UpdateTrafficPolicyInstanceInput { - s.TrafficPolicyId = &v - return s -} - -// SetTrafficPolicyVersion sets the TrafficPolicyVersion field's value. -func (s *UpdateTrafficPolicyInstanceInput) SetTrafficPolicyVersion(v int64) *UpdateTrafficPolicyInstanceInput { - s.TrafficPolicyVersion = &v - return s -} - -// A complex type that contains information about the resource record sets that -// Amazon Route 53 created based on a specified traffic policy. -type UpdateTrafficPolicyInstanceOutput struct { - _ struct{} `type:"structure"` - - // A complex type that contains settings for the updated traffic policy instance. - // - // TrafficPolicyInstance is a required field - TrafficPolicyInstance *TrafficPolicyInstance `type:"structure" required:"true"` -} - -// String returns the string representation -func (s UpdateTrafficPolicyInstanceOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s UpdateTrafficPolicyInstanceOutput) GoString() string { - return s.String() -} - -// SetTrafficPolicyInstance sets the TrafficPolicyInstance field's value. -func (s *UpdateTrafficPolicyInstanceOutput) SetTrafficPolicyInstance(v *TrafficPolicyInstance) *UpdateTrafficPolicyInstanceOutput { - s.TrafficPolicyInstance = v - return s -} - -// (Private hosted zones only) A complex type that contains information about -// an Amazon VPC. -type VPC struct { - _ struct{} `type:"structure"` - - // (Private hosted zones only) The ID of an Amazon VPC. - VPCId *string `type:"string"` - - // (Private hosted zones only) The region in which you created an Amazon VPC. - VPCRegion *string `min:"1" type:"string" enum:"VPCRegion"` -} - -// String returns the string representation -func (s VPC) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s VPC) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *VPC) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "VPC"} - if s.VPCRegion != nil && len(*s.VPCRegion) < 1 { - invalidParams.Add(request.NewErrParamMinLen("VPCRegion", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetVPCId sets the VPCId field's value. -func (s *VPC) SetVPCId(v string) *VPC { - s.VPCId = &v - return s -} - -// SetVPCRegion sets the VPCRegion field's value. -func (s *VPC) SetVPCRegion(v string) *VPC { - s.VPCRegion = &v - return s -} - -const ( - // AccountLimitTypeMaxHealthChecksByOwner is a AccountLimitType enum value - AccountLimitTypeMaxHealthChecksByOwner = "MAX_HEALTH_CHECKS_BY_OWNER" - - // AccountLimitTypeMaxHostedZonesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxHostedZonesByOwner = "MAX_HOSTED_ZONES_BY_OWNER" - - // AccountLimitTypeMaxTrafficPolicyInstancesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxTrafficPolicyInstancesByOwner = "MAX_TRAFFIC_POLICY_INSTANCES_BY_OWNER" - - // AccountLimitTypeMaxReusableDelegationSetsByOwner is a AccountLimitType enum value - AccountLimitTypeMaxReusableDelegationSetsByOwner = "MAX_REUSABLE_DELEGATION_SETS_BY_OWNER" - - // AccountLimitTypeMaxTrafficPoliciesByOwner is a AccountLimitType enum value - AccountLimitTypeMaxTrafficPoliciesByOwner = "MAX_TRAFFIC_POLICIES_BY_OWNER" -) - -const ( - // ChangeActionCreate is a ChangeAction enum value - ChangeActionCreate = "CREATE" - - // ChangeActionDelete is a ChangeAction enum value - ChangeActionDelete = "DELETE" - - // ChangeActionUpsert is a ChangeAction enum value - ChangeActionUpsert = "UPSERT" -) - -const ( - // ChangeStatusPending is a ChangeStatus enum value - ChangeStatusPending = "PENDING" - - // ChangeStatusInsync is a ChangeStatus enum value - ChangeStatusInsync = "INSYNC" -) - -const ( - // CloudWatchRegionUsEast1 is a CloudWatchRegion enum value - CloudWatchRegionUsEast1 = "us-east-1" - - // CloudWatchRegionUsEast2 is a CloudWatchRegion enum value - CloudWatchRegionUsEast2 = "us-east-2" - - // CloudWatchRegionUsWest1 is a CloudWatchRegion enum value - CloudWatchRegionUsWest1 = "us-west-1" - - // CloudWatchRegionUsWest2 is a CloudWatchRegion enum value - CloudWatchRegionUsWest2 = "us-west-2" - - // CloudWatchRegionCaCentral1 is a CloudWatchRegion enum value - CloudWatchRegionCaCentral1 = "ca-central-1" - - // CloudWatchRegionEuCentral1 is a CloudWatchRegion enum value - CloudWatchRegionEuCentral1 = "eu-central-1" - - // CloudWatchRegionEuWest1 is a CloudWatchRegion enum value - CloudWatchRegionEuWest1 = "eu-west-1" - - // CloudWatchRegionEuWest2 is a CloudWatchRegion enum value - CloudWatchRegionEuWest2 = "eu-west-2" - - // CloudWatchRegionEuWest3 is a CloudWatchRegion enum value - CloudWatchRegionEuWest3 = "eu-west-3" - - // CloudWatchRegionApSouth1 is a CloudWatchRegion enum value - CloudWatchRegionApSouth1 = "ap-south-1" - - // CloudWatchRegionApSoutheast1 is a CloudWatchRegion enum value - CloudWatchRegionApSoutheast1 = "ap-southeast-1" - - // CloudWatchRegionApSoutheast2 is a CloudWatchRegion enum value - CloudWatchRegionApSoutheast2 = "ap-southeast-2" - - // CloudWatchRegionApNortheast1 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast1 = "ap-northeast-1" - - // CloudWatchRegionApNortheast2 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast2 = "ap-northeast-2" - - // CloudWatchRegionApNortheast3 is a CloudWatchRegion enum value - CloudWatchRegionApNortheast3 = "ap-northeast-3" - - // CloudWatchRegionSaEast1 is a CloudWatchRegion enum value - CloudWatchRegionSaEast1 = "sa-east-1" -) - -const ( - // ComparisonOperatorGreaterThanOrEqualToThreshold is a ComparisonOperator enum value - ComparisonOperatorGreaterThanOrEqualToThreshold = "GreaterThanOrEqualToThreshold" - - // ComparisonOperatorGreaterThanThreshold is a ComparisonOperator enum value - ComparisonOperatorGreaterThanThreshold = "GreaterThanThreshold" - - // ComparisonOperatorLessThanThreshold is a ComparisonOperator enum value - ComparisonOperatorLessThanThreshold = "LessThanThreshold" - - // ComparisonOperatorLessThanOrEqualToThreshold is a ComparisonOperator enum value - ComparisonOperatorLessThanOrEqualToThreshold = "LessThanOrEqualToThreshold" -) - -const ( - // HealthCheckRegionUsEast1 is a HealthCheckRegion enum value - HealthCheckRegionUsEast1 = "us-east-1" - - // HealthCheckRegionUsWest1 is a HealthCheckRegion enum value - HealthCheckRegionUsWest1 = "us-west-1" - - // HealthCheckRegionUsWest2 is a HealthCheckRegion enum value - HealthCheckRegionUsWest2 = "us-west-2" - - // HealthCheckRegionEuWest1 is a HealthCheckRegion enum value - HealthCheckRegionEuWest1 = "eu-west-1" - - // HealthCheckRegionApSoutheast1 is a HealthCheckRegion enum value - HealthCheckRegionApSoutheast1 = "ap-southeast-1" - - // HealthCheckRegionApSoutheast2 is a HealthCheckRegion enum value - HealthCheckRegionApSoutheast2 = "ap-southeast-2" - - // HealthCheckRegionApNortheast1 is a HealthCheckRegion enum value - HealthCheckRegionApNortheast1 = "ap-northeast-1" - - // HealthCheckRegionSaEast1 is a HealthCheckRegion enum value - HealthCheckRegionSaEast1 = "sa-east-1" -) - -const ( - // HealthCheckTypeHttp is a HealthCheckType enum value - HealthCheckTypeHttp = "HTTP" - - // HealthCheckTypeHttps is a HealthCheckType enum value - HealthCheckTypeHttps = "HTTPS" - - // HealthCheckTypeHttpStrMatch is a HealthCheckType enum value - HealthCheckTypeHttpStrMatch = "HTTP_STR_MATCH" - - // HealthCheckTypeHttpsStrMatch is a HealthCheckType enum value - HealthCheckTypeHttpsStrMatch = "HTTPS_STR_MATCH" - - // HealthCheckTypeTcp is a HealthCheckType enum value - HealthCheckTypeTcp = "TCP" - - // HealthCheckTypeCalculated is a HealthCheckType enum value - HealthCheckTypeCalculated = "CALCULATED" - - // HealthCheckTypeCloudwatchMetric is a HealthCheckType enum value - HealthCheckTypeCloudwatchMetric = "CLOUDWATCH_METRIC" -) - -const ( - // HostedZoneLimitTypeMaxRrsetsByZone is a HostedZoneLimitType enum value - HostedZoneLimitTypeMaxRrsetsByZone = "MAX_RRSETS_BY_ZONE" - - // HostedZoneLimitTypeMaxVpcsAssociatedByZone is a HostedZoneLimitType enum value - HostedZoneLimitTypeMaxVpcsAssociatedByZone = "MAX_VPCS_ASSOCIATED_BY_ZONE" -) - -const ( - // InsufficientDataHealthStatusHealthy is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusHealthy = "Healthy" - - // InsufficientDataHealthStatusUnhealthy is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusUnhealthy = "Unhealthy" - - // InsufficientDataHealthStatusLastKnownStatus is a InsufficientDataHealthStatus enum value - InsufficientDataHealthStatusLastKnownStatus = "LastKnownStatus" -) - -const ( - // RRTypeSoa is a RRType enum value - RRTypeSoa = "SOA" - - // RRTypeA is a RRType enum value - RRTypeA = "A" - - // RRTypeTxt is a RRType enum value - RRTypeTxt = "TXT" - - // RRTypeNs is a RRType enum value - RRTypeNs = "NS" - - // RRTypeCname is a RRType enum value - RRTypeCname = "CNAME" - - // RRTypeMx is a RRType enum value - RRTypeMx = "MX" - - // RRTypeNaptr is a RRType enum value - RRTypeNaptr = "NAPTR" - - // RRTypePtr is a RRType enum value - RRTypePtr = "PTR" - - // RRTypeSrv is a RRType enum value - RRTypeSrv = "SRV" - - // RRTypeSpf is a RRType enum value - RRTypeSpf = "SPF" - - // RRTypeAaaa is a RRType enum value - RRTypeAaaa = "AAAA" - - // RRTypeCaa is a RRType enum value - RRTypeCaa = "CAA" -) - -const ( - // ResettableElementNameFullyQualifiedDomainName is a ResettableElementName enum value - ResettableElementNameFullyQualifiedDomainName = "FullyQualifiedDomainName" - - // ResettableElementNameRegions is a ResettableElementName enum value - ResettableElementNameRegions = "Regions" - - // ResettableElementNameResourcePath is a ResettableElementName enum value - ResettableElementNameResourcePath = "ResourcePath" - - // ResettableElementNameChildHealthChecks is a ResettableElementName enum value - ResettableElementNameChildHealthChecks = "ChildHealthChecks" -) - -const ( - // ResourceRecordSetFailoverPrimary is a ResourceRecordSetFailover enum value - ResourceRecordSetFailoverPrimary = "PRIMARY" - - // ResourceRecordSetFailoverSecondary is a ResourceRecordSetFailover enum value - ResourceRecordSetFailoverSecondary = "SECONDARY" -) - -const ( - // ResourceRecordSetRegionUsEast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsEast1 = "us-east-1" - - // ResourceRecordSetRegionUsEast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsEast2 = "us-east-2" - - // ResourceRecordSetRegionUsWest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsWest1 = "us-west-1" - - // ResourceRecordSetRegionUsWest2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionUsWest2 = "us-west-2" - - // ResourceRecordSetRegionCaCentral1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCaCentral1 = "ca-central-1" - - // ResourceRecordSetRegionEuWest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest1 = "eu-west-1" - - // ResourceRecordSetRegionEuWest2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest2 = "eu-west-2" - - // ResourceRecordSetRegionEuWest3 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuWest3 = "eu-west-3" - - // ResourceRecordSetRegionEuCentral1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionEuCentral1 = "eu-central-1" - - // ResourceRecordSetRegionApSoutheast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSoutheast1 = "ap-southeast-1" - - // ResourceRecordSetRegionApSoutheast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSoutheast2 = "ap-southeast-2" - - // ResourceRecordSetRegionApNortheast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast1 = "ap-northeast-1" - - // ResourceRecordSetRegionApNortheast2 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast2 = "ap-northeast-2" - - // ResourceRecordSetRegionApNortheast3 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApNortheast3 = "ap-northeast-3" - - // ResourceRecordSetRegionSaEast1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionSaEast1 = "sa-east-1" - - // ResourceRecordSetRegionCnNorth1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCnNorth1 = "cn-north-1" - - // ResourceRecordSetRegionCnNorthwest1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionCnNorthwest1 = "cn-northwest-1" - - // ResourceRecordSetRegionApSouth1 is a ResourceRecordSetRegion enum value - ResourceRecordSetRegionApSouth1 = "ap-south-1" -) - -const ( - // ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet is a ReusableDelegationSetLimitType enum value - ReusableDelegationSetLimitTypeMaxZonesByReusableDelegationSet = "MAX_ZONES_BY_REUSABLE_DELEGATION_SET" -) - -const ( - // StatisticAverage is a Statistic enum value - StatisticAverage = "Average" - - // StatisticSum is a Statistic enum value - StatisticSum = "Sum" - - // StatisticSampleCount is a Statistic enum value - StatisticSampleCount = "SampleCount" - - // StatisticMaximum is a Statistic enum value - StatisticMaximum = "Maximum" - - // StatisticMinimum is a Statistic enum value - StatisticMinimum = "Minimum" -) - -const ( - // TagResourceTypeHealthcheck is a TagResourceType enum value - TagResourceTypeHealthcheck = "healthcheck" - - // TagResourceTypeHostedzone is a TagResourceType enum value - TagResourceTypeHostedzone = "hostedzone" -) - -const ( - // VPCRegionUsEast1 is a VPCRegion enum value - VPCRegionUsEast1 = "us-east-1" - - // VPCRegionUsEast2 is a VPCRegion enum value - VPCRegionUsEast2 = "us-east-2" - - // VPCRegionUsWest1 is a VPCRegion enum value - VPCRegionUsWest1 = "us-west-1" - - // VPCRegionUsWest2 is a VPCRegion enum value - VPCRegionUsWest2 = "us-west-2" - - // VPCRegionEuWest1 is a VPCRegion enum value - VPCRegionEuWest1 = "eu-west-1" - - // VPCRegionEuWest2 is a VPCRegion enum value - VPCRegionEuWest2 = "eu-west-2" - - // VPCRegionEuWest3 is a VPCRegion enum value - VPCRegionEuWest3 = "eu-west-3" - - // VPCRegionEuCentral1 is a VPCRegion enum value - VPCRegionEuCentral1 = "eu-central-1" - - // VPCRegionApSoutheast1 is a VPCRegion enum value - VPCRegionApSoutheast1 = "ap-southeast-1" - - // VPCRegionApSoutheast2 is a VPCRegion enum value - VPCRegionApSoutheast2 = "ap-southeast-2" - - // VPCRegionApSouth1 is a VPCRegion enum value - VPCRegionApSouth1 = "ap-south-1" - - // VPCRegionApNortheast1 is a VPCRegion enum value - VPCRegionApNortheast1 = "ap-northeast-1" - - // VPCRegionApNortheast2 is a VPCRegion enum value - VPCRegionApNortheast2 = "ap-northeast-2" - - // VPCRegionApNortheast3 is a VPCRegion enum value - VPCRegionApNortheast3 = "ap-northeast-3" - - // VPCRegionSaEast1 is a VPCRegion enum value - VPCRegionSaEast1 = "sa-east-1" - - // VPCRegionCaCentral1 is a VPCRegion enum value - VPCRegionCaCentral1 = "ca-central-1" - - // VPCRegionCnNorth1 is a VPCRegion enum value - VPCRegionCnNorth1 = "cn-north-1" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go deleted file mode 100644 index efe2d6e7c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/customizations.go +++ /dev/null @@ -1,42 +0,0 @@ -package route53 - -import ( - "net/url" - "regexp" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -func init() { - initClient = func(c *client.Client) { - c.Handlers.Build.PushBack(sanitizeURL) - } - - initRequest = func(r *request.Request) { - switch r.Operation.Name { - case opChangeResourceRecordSets: - r.Handlers.UnmarshalError.Remove(restxml.UnmarshalErrorHandler) - r.Handlers.UnmarshalError.PushBack(unmarshalChangeResourceRecordSetsError) - } - } -} - -var reSanitizeURL = regexp.MustCompile(`\/%2F\w+%2F`) - -func sanitizeURL(r *request.Request) { - r.HTTPRequest.URL.RawPath = - reSanitizeURL.ReplaceAllString(r.HTTPRequest.URL.RawPath, "/") - - // Update Path so that it reflects the cleaned RawPath - updated, err := url.Parse(r.HTTPRequest.URL.RawPath) - if err != nil { - r.Error = awserr.New("SerializationError", "failed to clean Route53 URL", err) - return - } - - // Take the updated path so the requests's URL Path has parity with RawPath. - r.HTTPRequest.URL.Path = updated.Path -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go b/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go deleted file mode 100644 index 7965fea67..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/doc.go +++ /dev/null @@ -1,26 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package route53 provides the client and types for making API -// requests to Amazon Route 53. -// -// See https://docs.aws.amazon.com/goto/WebAPI/route53-2013-04-01 for more information on this service. -// -// See route53 package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/ -// -// Using the Client -// -// To contact Amazon Route 53 with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the Amazon Route 53 client Route53 for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/route53/#New -package route53 diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go b/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go deleted file mode 100644 index d37e10cde..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/errors.go +++ /dev/null @@ -1,436 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -const ( - - // ErrCodeConcurrentModification for service response error code - // "ConcurrentModification". - // - // Another user submitted a request to create, update, or delete the object - // at the same time that you did. Retry the request. - ErrCodeConcurrentModification = "ConcurrentModification" - - // ErrCodeConflictingDomainExists for service response error code - // "ConflictingDomainExists". - // - // The cause of this error depends on whether you're trying to create a public - // or a private hosted zone: - // - // * Public hosted zone: Two hosted zones that have the same name or that - // have a parent/child relationship (example.com and test.example.com) can't - // have any common name servers. You tried to create a hosted zone that has - // the same name as an existing hosted zone or that's the parent or child - // of an existing hosted zone, and you specified a delegation set that shares - // one or more name servers with the existing hosted zone. For more information, - // see CreateReusableDelegationSet. - // - // * Private hosted zone: You specified an Amazon VPC that you're already - // using for another hosted zone, and the domain that you specified for one - // of the hosted zones is a subdomain of the domain that you specified for - // the other hosted zone. For example, you can't use the same Amazon VPC - // for the hosted zones for example.com and test.example.com. - ErrCodeConflictingDomainExists = "ConflictingDomainExists" - - // ErrCodeConflictingTypes for service response error code - // "ConflictingTypes". - // - // You tried to update a traffic policy instance by using a traffic policy version - // that has a different DNS type than the current type for the instance. You - // specified the type in the JSON document in the CreateTrafficPolicy or CreateTrafficPolicyVersionrequest. - ErrCodeConflictingTypes = "ConflictingTypes" - - // ErrCodeDelegationSetAlreadyCreated for service response error code - // "DelegationSetAlreadyCreated". - // - // A delegation set with the same owner and caller reference combination has - // already been created. - ErrCodeDelegationSetAlreadyCreated = "DelegationSetAlreadyCreated" - - // ErrCodeDelegationSetAlreadyReusable for service response error code - // "DelegationSetAlreadyReusable". - // - // The specified delegation set has already been marked as reusable. - ErrCodeDelegationSetAlreadyReusable = "DelegationSetAlreadyReusable" - - // ErrCodeDelegationSetInUse for service response error code - // "DelegationSetInUse". - // - // The specified delegation contains associated hosted zones which must be deleted - // before the reusable delegation set can be deleted. - ErrCodeDelegationSetInUse = "DelegationSetInUse" - - // ErrCodeDelegationSetNotAvailable for service response error code - // "DelegationSetNotAvailable". - // - // You can create a hosted zone that has the same name as an existing hosted - // zone (example.com is common), but there is a limit to the number of hosted - // zones that have the same name. If you get this error, Amazon Route 53 has - // reached that limit. If you own the domain name and Amazon Route 53 generates - // this error, contact Customer Support. - ErrCodeDelegationSetNotAvailable = "DelegationSetNotAvailable" - - // ErrCodeDelegationSetNotReusable for service response error code - // "DelegationSetNotReusable". - // - // A reusable delegation set with the specified ID does not exist. - ErrCodeDelegationSetNotReusable = "DelegationSetNotReusable" - - // ErrCodeHealthCheckAlreadyExists for service response error code - // "HealthCheckAlreadyExists". - // - // The health check you're attempting to create already exists. Amazon Route - // 53 returns this error when you submit a request that has the following values: - // - // * The same value for CallerReference as an existing health check, and - // one or more values that differ from the existing health check that has - // the same caller reference. - // - // * The same value for CallerReference as a health check that you created - // and later deleted, regardless of the other settings in the request. - ErrCodeHealthCheckAlreadyExists = "HealthCheckAlreadyExists" - - // ErrCodeHealthCheckInUse for service response error code - // "HealthCheckInUse". - // - // This error code is not in use. - ErrCodeHealthCheckInUse = "HealthCheckInUse" - - // ErrCodeHealthCheckVersionMismatch for service response error code - // "HealthCheckVersionMismatch". - // - // The value of HealthCheckVersion in the request doesn't match the value of - // HealthCheckVersion in the health check. - ErrCodeHealthCheckVersionMismatch = "HealthCheckVersionMismatch" - - // ErrCodeHostedZoneAlreadyExists for service response error code - // "HostedZoneAlreadyExists". - // - // The hosted zone you're trying to create already exists. Amazon Route 53 returns - // this error when a hosted zone has already been created with the specified - // CallerReference. - ErrCodeHostedZoneAlreadyExists = "HostedZoneAlreadyExists" - - // ErrCodeHostedZoneNotEmpty for service response error code - // "HostedZoneNotEmpty". - // - // The hosted zone contains resource records that are not SOA or NS records. - ErrCodeHostedZoneNotEmpty = "HostedZoneNotEmpty" - - // ErrCodeHostedZoneNotFound for service response error code - // "HostedZoneNotFound". - // - // The specified HostedZone can't be found. - ErrCodeHostedZoneNotFound = "HostedZoneNotFound" - - // ErrCodeHostedZoneNotPrivate for service response error code - // "HostedZoneNotPrivate". - // - // The specified hosted zone is a public hosted zone, not a private hosted zone. - ErrCodeHostedZoneNotPrivate = "HostedZoneNotPrivate" - - // ErrCodeIncompatibleVersion for service response error code - // "IncompatibleVersion". - // - // The resource you're trying to access is unsupported on this Amazon Route - // 53 endpoint. - ErrCodeIncompatibleVersion = "IncompatibleVersion" - - // ErrCodeInsufficientCloudWatchLogsResourcePolicy for service response error code - // "InsufficientCloudWatchLogsResourcePolicy". - // - // Amazon Route 53 doesn't have the permissions required to create log streams - // and send query logs to log streams. Possible causes include the following: - // - // * There is no resource policy that specifies the log group ARN in the - // value for Resource. - // - // * The resource policy that includes the log group ARN in the value for - // Resource doesn't have the necessary permissions. - // - // * The resource policy hasn't finished propagating yet. - ErrCodeInsufficientCloudWatchLogsResourcePolicy = "InsufficientCloudWatchLogsResourcePolicy" - - // ErrCodeInvalidArgument for service response error code - // "InvalidArgument". - // - // Parameter name is invalid. - ErrCodeInvalidArgument = "InvalidArgument" - - // ErrCodeInvalidChangeBatch for service response error code - // "InvalidChangeBatch". - // - // This exception contains a list of messages that might contain one or more - // error messages. Each error message indicates one error in the change batch. - ErrCodeInvalidChangeBatch = "InvalidChangeBatch" - - // ErrCodeInvalidDomainName for service response error code - // "InvalidDomainName". - // - // The specified domain name is not valid. - ErrCodeInvalidDomainName = "InvalidDomainName" - - // ErrCodeInvalidInput for service response error code - // "InvalidInput". - // - // The input is not valid. - ErrCodeInvalidInput = "InvalidInput" - - // ErrCodeInvalidPaginationToken for service response error code - // "InvalidPaginationToken". - // - // The value that you specified to get the second or subsequent page of results - // is invalid. - ErrCodeInvalidPaginationToken = "InvalidPaginationToken" - - // ErrCodeInvalidTrafficPolicyDocument for service response error code - // "InvalidTrafficPolicyDocument". - // - // The format of the traffic policy document that you specified in the Document - // element is invalid. - ErrCodeInvalidTrafficPolicyDocument = "InvalidTrafficPolicyDocument" - - // ErrCodeInvalidVPCId for service response error code - // "InvalidVPCId". - // - // The VPC ID that you specified either isn't a valid ID or the current account - // is not authorized to access this VPC. - ErrCodeInvalidVPCId = "InvalidVPCId" - - // ErrCodeLastVPCAssociation for service response error code - // "LastVPCAssociation". - // - // The VPC that you're trying to disassociate from the private hosted zone is - // the last VPC that is associated with the hosted zone. Amazon Route 53 doesn't - // support disassociating the last VPC from a hosted zone. - ErrCodeLastVPCAssociation = "LastVPCAssociation" - - // ErrCodeLimitsExceeded for service response error code - // "LimitsExceeded". - // - // This operation can't be completed either because the current account has - // reached the limit on reusable delegation sets that it can create or because - // you've reached the limit on the number of Amazon VPCs that you can associate - // with a private hosted zone. To get the current limit on the number of reusable - // delegation sets, see GetAccountLimit. To get the current limit on the number - // of Amazon VPCs that you can associate with a private hosted zone, see GetHostedZoneLimit. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeLimitsExceeded = "LimitsExceeded" - - // ErrCodeNoSuchChange for service response error code - // "NoSuchChange". - // - // A change with the specified change ID does not exist. - ErrCodeNoSuchChange = "NoSuchChange" - - // ErrCodeNoSuchCloudWatchLogsLogGroup for service response error code - // "NoSuchCloudWatchLogsLogGroup". - // - // There is no CloudWatch Logs log group with the specified ARN. - ErrCodeNoSuchCloudWatchLogsLogGroup = "NoSuchCloudWatchLogsLogGroup" - - // ErrCodeNoSuchDelegationSet for service response error code - // "NoSuchDelegationSet". - // - // A reusable delegation set with the specified ID does not exist. - ErrCodeNoSuchDelegationSet = "NoSuchDelegationSet" - - // ErrCodeNoSuchGeoLocation for service response error code - // "NoSuchGeoLocation". - // - // Amazon Route 53 doesn't support the specified geolocation. - ErrCodeNoSuchGeoLocation = "NoSuchGeoLocation" - - // ErrCodeNoSuchHealthCheck for service response error code - // "NoSuchHealthCheck". - // - // No health check exists with the ID that you specified in the DeleteHealthCheck - // request. - ErrCodeNoSuchHealthCheck = "NoSuchHealthCheck" - - // ErrCodeNoSuchHostedZone for service response error code - // "NoSuchHostedZone". - // - // No hosted zone exists with the ID that you specified. - ErrCodeNoSuchHostedZone = "NoSuchHostedZone" - - // ErrCodeNoSuchQueryLoggingConfig for service response error code - // "NoSuchQueryLoggingConfig". - // - // There is no DNS query logging configuration with the specified ID. - ErrCodeNoSuchQueryLoggingConfig = "NoSuchQueryLoggingConfig" - - // ErrCodeNoSuchTrafficPolicy for service response error code - // "NoSuchTrafficPolicy". - // - // No traffic policy exists with the specified ID. - ErrCodeNoSuchTrafficPolicy = "NoSuchTrafficPolicy" - - // ErrCodeNoSuchTrafficPolicyInstance for service response error code - // "NoSuchTrafficPolicyInstance". - // - // No traffic policy instance exists with the specified ID. - ErrCodeNoSuchTrafficPolicyInstance = "NoSuchTrafficPolicyInstance" - - // ErrCodeNotAuthorizedException for service response error code - // "NotAuthorizedException". - // - // Associating the specified VPC with the specified hosted zone has not been - // authorized. - ErrCodeNotAuthorizedException = "NotAuthorizedException" - - // ErrCodePriorRequestNotComplete for service response error code - // "PriorRequestNotComplete". - // - // If Amazon Route 53 can't process a request before the next request arrives, - // it will reject subsequent requests for the same hosted zone and return an - // HTTP 400 error (Bad request). If Amazon Route 53 returns this error repeatedly - // for the same request, we recommend that you wait, in intervals of increasing - // duration, before you try the request again. - ErrCodePriorRequestNotComplete = "PriorRequestNotComplete" - - // ErrCodePublicZoneVPCAssociation for service response error code - // "PublicZoneVPCAssociation". - // - // You're trying to associate a VPC with a public hosted zone. Amazon Route - // 53 doesn't support associating a VPC with a public hosted zone. - ErrCodePublicZoneVPCAssociation = "PublicZoneVPCAssociation" - - // ErrCodeQueryLoggingConfigAlreadyExists for service response error code - // "QueryLoggingConfigAlreadyExists". - // - // You can create only one query logging configuration for a hosted zone, and - // a query logging configuration already exists for this hosted zone. - ErrCodeQueryLoggingConfigAlreadyExists = "QueryLoggingConfigAlreadyExists" - - // ErrCodeThrottlingException for service response error code - // "ThrottlingException". - // - // The limit on the number of requests per second was exceeded. - ErrCodeThrottlingException = "ThrottlingException" - - // ErrCodeTooManyHealthChecks for service response error code - // "TooManyHealthChecks". - // - // This health check can't be created because the current account has reached - // the limit on the number of active health checks. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // For information about how to get the current limit for an account, see GetAccountLimit. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - // - // You have reached the maximum number of active health checks for an AWS account. - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyHealthChecks = "TooManyHealthChecks" - - // ErrCodeTooManyHostedZones for service response error code - // "TooManyHostedZones". - // - // This operation can't be completed either because the current account has - // reached the limit on the number of hosted zones or because you've reached - // the limit on the number of hosted zones that can be associated with a reusable - // delegation set. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // To get the current limit on hosted zones that can be created by an account, - // see GetAccountLimit. - // - // To get the current limit on hosted zones that can be associated with a reusable - // delegation set, see GetReusableDelegationSetLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyHostedZones = "TooManyHostedZones" - - // ErrCodeTooManyTrafficPolicies for service response error code - // "TooManyTrafficPolicies". - // - // This traffic policy can't be created because the current account has reached - // the limit on the number of traffic policies. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // To get the current limit for an account, see GetAccountLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyTrafficPolicies = "TooManyTrafficPolicies" - - // ErrCodeTooManyTrafficPolicyInstances for service response error code - // "TooManyTrafficPolicyInstances". - // - // This traffic policy instance can't be created because the current account - // has reached the limit on the number of traffic policy instances. - // - // For information about default limits, see Limits (http://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html) - // in the Amazon Route 53 Developer Guide. - // - // For information about how to get the current limit for an account, see GetAccountLimit. - // - // To request a higher limit, create a case (http://aws.amazon.com/route53-request) - // with the AWS Support Center. - ErrCodeTooManyTrafficPolicyInstances = "TooManyTrafficPolicyInstances" - - // ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy for service response error code - // "TooManyTrafficPolicyVersionsForCurrentPolicy". - // - // This traffic policy version can't be created because you've reached the limit - // of 1000 on the number of versions that you can create for the current traffic - // policy. - // - // To create more traffic policy versions, you can use GetTrafficPolicy to get - // the traffic policy document for a specified traffic policy version, and then - // use CreateTrafficPolicy to create a new traffic policy using the traffic - // policy document. - ErrCodeTooManyTrafficPolicyVersionsForCurrentPolicy = "TooManyTrafficPolicyVersionsForCurrentPolicy" - - // ErrCodeTooManyVPCAssociationAuthorizations for service response error code - // "TooManyVPCAssociationAuthorizations". - // - // You've created the maximum number of authorizations that can be created for - // the specified hosted zone. To authorize another VPC to be associated with - // the hosted zone, submit a DeleteVPCAssociationAuthorization request to remove - // an existing authorization. To get a list of existing authorizations, submit - // a ListVPCAssociationAuthorizations request. - ErrCodeTooManyVPCAssociationAuthorizations = "TooManyVPCAssociationAuthorizations" - - // ErrCodeTrafficPolicyAlreadyExists for service response error code - // "TrafficPolicyAlreadyExists". - // - // A traffic policy that has the same value for Name already exists. - ErrCodeTrafficPolicyAlreadyExists = "TrafficPolicyAlreadyExists" - - // ErrCodeTrafficPolicyInUse for service response error code - // "TrafficPolicyInUse". - // - // One or more traffic policy instances were created by using the specified - // traffic policy. - ErrCodeTrafficPolicyInUse = "TrafficPolicyInUse" - - // ErrCodeTrafficPolicyInstanceAlreadyExists for service response error code - // "TrafficPolicyInstanceAlreadyExists". - // - // There is already a traffic policy instance with the specified ID. - ErrCodeTrafficPolicyInstanceAlreadyExists = "TrafficPolicyInstanceAlreadyExists" - - // ErrCodeVPCAssociationAuthorizationNotFound for service response error code - // "VPCAssociationAuthorizationNotFound". - // - // The VPC that you specified is not authorized to be associated with the hosted - // zone. - ErrCodeVPCAssociationAuthorizationNotFound = "VPCAssociationAuthorizationNotFound" - - // ErrCodeVPCAssociationNotFound for service response error code - // "VPCAssociationNotFound". - // - // The specified VPC and hosted zone are not currently associated. - ErrCodeVPCAssociationNotFound = "VPCAssociationNotFound" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/service.go b/vendor/github.com/aws/aws-sdk-go/service/route53/service.go deleted file mode 100644 index 98ba1c8f8..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/service.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -// Route53 provides the API operation methods for making requests to -// Amazon Route 53. See this package's package overview docs -// for details on the service. -// -// Route53 methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type Route53 struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "route53" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. -) - -// New creates a new instance of the Route53 client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a Route53 client from just a session. -// svc := route53.New(mySession) -// -// // Create a Route53 client with additional configuration -// svc := route53.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *Route53 { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *Route53 { - svc := &Route53{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2013-04-01", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(restxml.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(restxml.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(restxml.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(restxml.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a Route53 operation and runs any -// custom request initialization. -func (c *Route53) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go b/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go deleted file mode 100644 index 266e9a8ba..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/unmarshal_error.go +++ /dev/null @@ -1,77 +0,0 @@ -package route53 - -import ( - "bytes" - "encoding/xml" - "io/ioutil" - - "github.com/aws/aws-sdk-go/aws/awserr" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/private/protocol/restxml" -) - -type baseXMLErrorResponse struct { - XMLName xml.Name -} - -type standardXMLErrorResponse struct { - XMLName xml.Name `xml:"ErrorResponse"` - Code string `xml:"Error>Code"` - Message string `xml:"Error>Message"` - RequestID string `xml:"RequestId"` -} - -type invalidChangeBatchXMLErrorResponse struct { - XMLName xml.Name `xml:"InvalidChangeBatch"` - Messages []string `xml:"Messages>Message"` -} - -func unmarshalChangeResourceRecordSetsError(r *request.Request) { - defer r.HTTPResponse.Body.Close() - - responseBody, err := ioutil.ReadAll(r.HTTPResponse.Body) - - if err != nil { - r.Error = awserr.New("SerializationError", "failed to read Route53 XML error response", err) - return - } - - baseError := &baseXMLErrorResponse{} - - if err := xml.Unmarshal(responseBody, baseError); err != nil { - r.Error = awserr.New("SerializationError", "failed to decode Route53 XML error response", err) - return - } - - switch baseError.XMLName.Local { - case "InvalidChangeBatch": - unmarshalInvalidChangeBatchError(r, responseBody) - default: - r.HTTPResponse.Body = ioutil.NopCloser(bytes.NewReader(responseBody)) - restxml.UnmarshalError(r) - } -} - -func unmarshalInvalidChangeBatchError(r *request.Request, requestBody []byte) { - resp := &invalidChangeBatchXMLErrorResponse{} - err := xml.Unmarshal(requestBody, resp) - - if err != nil { - r.Error = awserr.New("SerializationError", "failed to decode query XML error response", err) - return - } - - const errorCode = "InvalidChangeBatch" - errors := []error{} - - for _, msg := range resp.Messages { - errors = append(errors, awserr.New(errorCode, msg, nil)) - } - - r.Error = awserr.NewRequestFailure( - awserr.NewBatchError(errorCode, "ChangeBatch errors occurred", errors), - r.HTTPResponse.StatusCode, - r.RequestID, - ) - -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go b/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go deleted file mode 100644 index 9bd7a9a71..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/route53/waiters.go +++ /dev/null @@ -1,56 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package route53 - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/request" -) - -// WaitUntilResourceRecordSetsChanged uses the Route 53 API operation -// GetChange to wait for a condition to be met before returning. -// If the condition is not met within the max attempt window, an error will -// be returned. -func (c *Route53) WaitUntilResourceRecordSetsChanged(input *GetChangeInput) error { - return c.WaitUntilResourceRecordSetsChangedWithContext(aws.BackgroundContext(), input) -} - -// WaitUntilResourceRecordSetsChangedWithContext is an extended version of WaitUntilResourceRecordSetsChanged. -// With the support for passing in a context and options to configure the -// Waiter and the underlying request options. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *Route53) WaitUntilResourceRecordSetsChangedWithContext(ctx aws.Context, input *GetChangeInput, opts ...request.WaiterOption) error { - w := request.Waiter{ - Name: "WaitUntilResourceRecordSetsChanged", - MaxAttempts: 60, - Delay: request.ConstantWaiterDelay(30 * time.Second), - Acceptors: []request.WaiterAcceptor{ - { - State: request.SuccessWaiterState, - Matcher: request.PathWaiterMatch, Argument: "ChangeInfo.Status", - Expected: "INSYNC", - }, - }, - Logger: c.Config.Logger, - NewRequest: func(opts []request.Option) (*request.Request, error) { - var inCpy *GetChangeInput - if input != nil { - tmp := *input - inCpy = &tmp - } - req, _ := c.GetChangeRequest(inCpy) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return req, nil - }, - } - w.ApplyOptions(opts...) - - return w.WaitWithContext(ctx) -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go b/vendor/github.com/aws/aws-sdk-go/service/sts/api.go deleted file mode 100644 index b46da12ca..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/api.go +++ /dev/null @@ -1,2398 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/awsutil" - "github.com/aws/aws-sdk-go/aws/request" -) - -const opAssumeRole = "AssumeRole" - -// AssumeRoleRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRole operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRole for more information on using the AssumeRole -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleRequest method. -// req, resp := client.AssumeRoleRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRoleRequest(input *AssumeRoleInput) (req *request.Request, output *AssumeRoleOutput) { - op := &request.Operation{ - Name: opAssumeRole, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleInput{} - } - - output = &AssumeRoleOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRole API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) that you can use to access -// AWS resources that you might not normally have access to. Typically, you -// use AssumeRole for cross-account access or federation. For a comparison of -// AssumeRole with the other APIs that produce temporary credentials, see Requesting -// Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// Important: You cannot call AssumeRole by using AWS root account credentials; -// access is denied. You must use credentials for an IAM user or an IAM role -// to call AssumeRole. -// -// For cross-account access, imagine that you own multiple accounts and need -// to access resources in each account. You could create long-term credentials -// in each account to access those resources. However, managing all those credentials -// and remembering which one can access which account can be time consuming. -// Instead, you can create one set of long-term credentials in one account and -// then use temporary security credentials to access all the other accounts -// by assuming roles in those accounts. For more information about roles, see -// IAM Roles (Delegation and Federation) (http://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html) -// in the IAM User Guide. -// -// For federation, you can, for example, grant single sign-on access to the -// AWS Management Console. If you already have an identity and authentication -// system in your corporate network, you don't have to recreate user identities -// in AWS in order to grant those user identities access to AWS. Instead, after -// a user has been authenticated, you call AssumeRole (and specify the role -// with the appropriate permissions) to get temporary security credentials for -// that user. With those temporary security credentials, you construct a sign-in -// URL that users can use to access the console. For more information, see Common -// Scenarios for Temporary Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html#sts-introduction) -// in the IAM User Guide. -// -// By default, the temporary security credentials created by AssumeRole 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 (http://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 operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRole can be used to make -// API calls to any AWS service with the following exception: you cannot call -// the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// To assume a role, your AWS 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 access to -// this account's role. -// -// The user who wants to access the role must also have permissions delegated -// from the role's administrator. If the user is in a different account than -// the role, then the user's administrator must attach a policy that allows -// the user to call AssumeRole on the ARN of the role in the other account. -// If the user is in the same account as the role, then you can either attach -// a policy to the user (identical to the previous different account user), -// or you can add the user as a principal directly in the role's trust policy. -// In this case, the trust policy acts as the only resource-based policy in -// IAM, and users in the same account as the role do not need explicit permission -// to assume the role. For more information about trust policies and resource-based -// policies, see IAM Policies (http://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) -// in the IAM User Guide. -// -// Using MFA with AssumeRole -// -// You can optionally include multi-factor authentication (MFA) information -// when you call AssumeRole. This is useful for cross-account scenarios in which -// you want to make sure that the user who is assuming the role has been authenticated -// using an AWS 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 (http://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 devices produces. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRole for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole -func (c *STS) AssumeRole(input *AssumeRoleInput) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - return out, req.Send() -} - -// AssumeRoleWithContext is the same as AssumeRole with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRole for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithContext(ctx aws.Context, input *AssumeRoleInput, opts ...request.Option) (*AssumeRoleOutput, error) { - req, out := c.AssumeRoleRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithSAML = "AssumeRoleWithSAML" - -// AssumeRoleWithSAMLRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithSAML operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithSAML for more information on using the AssumeRoleWithSAML -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleWithSAMLRequest method. -// req, resp := client.AssumeRoleWithSAMLRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAMLRequest(input *AssumeRoleWithSAMLInput) (req *request.Request, output *AssumeRoleWithSAMLOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithSAML, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithSAMLInput{} - } - - output = &AssumeRoleWithSAMLOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithSAML API operation for AWS Security Token Service. -// -// 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 AWS access -// without user-specific credentials or configuration. For a comparison of AssumeRoleWithSAML -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://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 AWS services. -// -// 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 (http://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 operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRoleWithSAML can be used -// to make API calls to any AWS service with the following exception: you cannot -// call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by the intersection of both the access policy -// of the role that is being assumed, and the policy that you pass. This means -// that both policies must grant the permission for the action to be allowed. -// This gives you a way to further restrict the permissions for the resulting -// temporary security credentials. You cannot use the passed policy to grant -// permissions that are in excess of those allowed by the access policy of the -// role that is being assumed. For more information, see Permissions for AssumeRole, -// AssumeRoleWithSAML, and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// Before your application can call AssumeRoleWithSAML, you must configure your -// SAML identity provider (IdP) to issue the claims required by AWS. Additionally, -// you must use AWS Identity and Access Management (IAM) to create a SAML provider -// entity in your AWS account that represents your identity provider, and create -// an IAM role that specifies this SAML provider in its trust policy. -// -// Calling AssumeRoleWithSAML does not require the use of AWS 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 AWS 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). -// -// For more information, see the following resources: -// -// * About SAML 2.0-based Federation (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) -// in the IAM User Guide. -// -// * Creating SAML Identity Providers (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) -// in the IAM User Guide. -// -// * Configuring a Relying Party and Claims (http://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 (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithSAML for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML -func (c *STS) AssumeRoleWithSAML(input *AssumeRoleWithSAMLInput) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - return out, req.Send() -} - -// AssumeRoleWithSAMLWithContext is the same as AssumeRoleWithSAML with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithSAML for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithSAMLWithContext(ctx aws.Context, input *AssumeRoleWithSAMLInput, opts ...request.Option) (*AssumeRoleWithSAMLOutput, error) { - req, out := c.AssumeRoleWithSAMLRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opAssumeRoleWithWebIdentity = "AssumeRoleWithWebIdentity" - -// AssumeRoleWithWebIdentityRequest generates a "aws/request.Request" representing the -// client's request for the AssumeRoleWithWebIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See AssumeRoleWithWebIdentity for more information on using the AssumeRoleWithWebIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the AssumeRoleWithWebIdentityRequest method. -// req, resp := client.AssumeRoleWithWebIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentityRequest(input *AssumeRoleWithWebIdentityInput) (req *request.Request, output *AssumeRoleWithWebIdentityOutput) { - op := &request.Operation{ - Name: opAssumeRoleWithWebIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &AssumeRoleWithWebIdentityInput{} - } - - output = &AssumeRoleWithWebIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// AssumeRoleWithWebIdentity API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials for users who have been authenticated -// in a mobile or web application with a web identity provider, such as Amazon -// Cognito, Login with Amazon, Facebook, Google, or any OpenID Connect-compatible -// identity provider. -// -// For mobile applications, we recommend that you use Amazon Cognito. You can -// use Amazon Cognito with the AWS SDK for iOS (http://aws.amazon.com/sdkforios/) -// and the AWS SDK for Android (http://aws.amazon.com/sdkforandroid/) to uniquely -// identify a user and supply the user with a consistent identity throughout -// the lifetime of an application. -// -// To learn more about Amazon Cognito, see Amazon Cognito Overview (http://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840) -// in the AWS SDK for Android Developer Guide guide and Amazon Cognito Overview -// (http://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664) -// in the AWS SDK for iOS Developer Guide. -// -// Calling AssumeRoleWithWebIdentity does not require the use of AWS security -// credentials. Therefore, you can distribute an application (for example, on -// mobile devices) that requests temporary security credentials without including -// long-term AWS credentials in the application, and without deploying server-based -// proxy services that use long-term AWS 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 APIs that produce -// temporary credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://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 AWS service APIs. -// -// 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 (http://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 operations but -// does not apply when you use those operations to create a console URL. For -// more information, see Using IAM Roles (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html) -// in the IAM User Guide. -// -// The temporary security credentials created by AssumeRoleWithWebIdentity can -// be used to make API calls to any AWS service with the following exception: -// you cannot call the STS service's GetFederationToken or GetSessionToken APIs. -// -// Optionally, you can pass an IAM access policy to this operation. If you choose -// not to pass a policy, the temporary security credentials that are returned -// by the operation have the permissions that are defined in the access policy -// of the role that is being assumed. If you pass a policy to this operation, -// the temporary security credentials that are returned by the operation have -// the permissions that are allowed by both the access policy of the role that -// is being assumed, and the policy that you pass. This gives you a way to further -// restrict the permissions for the resulting temporary security credentials. -// You cannot use the passed policy to grant permissions that are in excess -// of those allowed by the access policy of the role that is being assumed. -// For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, -// and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) -// in the IAM User Guide. -// -// 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 AWS 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 APIs for Mobile Apps (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html) -// and Federation Through a Web-based Identity Provider (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// -// * Web Identity Federation Playground (https://web-identity-federation-playground.s3.amazonaws.com/index.html). -// This interactive website lets you walk through the process of authenticating -// via Login with Amazon, Facebook, or Google, getting temporary security -// credentials, and then using those credentials to make a request to AWS. -// -// -// * AWS SDK for iOS (http://aws.amazon.com/sdkforios/) and AWS SDK for Android -// (http://aws.amazon.com/sdkforandroid/). These toolkits contain sample -// apps that show how to invoke the identity providers, and then 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. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation AssumeRoleWithWebIdentity for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeIDPRejectedClaimException "IDPRejectedClaim" -// The identity provider (IdP) reported that authentication failed. This might -// be because the claim is invalid. -// -// If this error is returned for the AssumeRoleWithWebIdentity operation, it -// can also mean that the claim has expired or has been explicitly revoked. -// -// * ErrCodeIDPCommunicationErrorException "IDPCommunicationError" -// The request could not be fulfilled because the non-AWS identity provider -// (IDP) that was asked to verify the incoming identity token could not be reached. -// This is often a transient error caused by network conditions. Retry the request -// a limited number of times so that you don't exceed the request rate. If the -// error persists, the non-AWS identity provider might be down or not responding. -// -// * ErrCodeInvalidIdentityTokenException "InvalidIdentityToken" -// The web identity token that was passed could not be validated by AWS. Get -// a new identity token from the identity provider and then retry the request. -// -// * ErrCodeExpiredTokenException "ExpiredTokenException" -// The web identity token that was passed is expired or is not valid. Get a -// new identity token from the identity provider and then retry the request. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity -func (c *STS) AssumeRoleWithWebIdentity(input *AssumeRoleWithWebIdentityInput) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - return out, req.Send() -} - -// AssumeRoleWithWebIdentityWithContext is the same as AssumeRoleWithWebIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See AssumeRoleWithWebIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) AssumeRoleWithWebIdentityWithContext(ctx aws.Context, input *AssumeRoleWithWebIdentityInput, opts ...request.Option) (*AssumeRoleWithWebIdentityOutput, error) { - req, out := c.AssumeRoleWithWebIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opDecodeAuthorizationMessage = "DecodeAuthorizationMessage" - -// DecodeAuthorizationMessageRequest generates a "aws/request.Request" representing the -// client's request for the DecodeAuthorizationMessage operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See DecodeAuthorizationMessage for more information on using the DecodeAuthorizationMessage -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the DecodeAuthorizationMessageRequest method. -// req, resp := client.DecodeAuthorizationMessageRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessageRequest(input *DecodeAuthorizationMessageInput) (req *request.Request, output *DecodeAuthorizationMessageOutput) { - op := &request.Operation{ - Name: opDecodeAuthorizationMessage, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &DecodeAuthorizationMessageInput{} - } - - output = &DecodeAuthorizationMessageOutput{} - req = c.newRequest(op, input, output) - return -} - -// DecodeAuthorizationMessage API operation for AWS Security Token Service. -// -// Decodes additional information about the authorization status of a request -// from an encoded message returned in response to an AWS request. -// -// For example, if a user is not authorized to perform an action that he or -// she has requested, the request returns a Client.UnauthorizedOperation response -// (an HTTP 403 response). Some AWS actions additionally return an encoded message -// that can provide details about this authorization failure. -// -// Only certain AWS actions return an encoded authorization message. The documentation -// for an individual action indicates whether that action returns an encoded -// message in addition to returning an HTTP code. -// -// The message is encoded because the details of the authorization status can -// constitute privileged information that the user who requested the action -// should not see. To decode an authorization status message, a user must be -// granted permissions via an IAM policy 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 (http://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. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation DecodeAuthorizationMessage for usage and error information. -// -// Returned Error Codes: -// * ErrCodeInvalidAuthorizationMessageException "InvalidAuthorizationMessageException" -// The error returned if the message passed to DecodeAuthorizationMessage was -// invalid. This can happen if the token contains invalid characters, such as -// linebreaks. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage -func (c *STS) DecodeAuthorizationMessage(input *DecodeAuthorizationMessageInput) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - return out, req.Send() -} - -// DecodeAuthorizationMessageWithContext is the same as DecodeAuthorizationMessage with the addition of -// the ability to pass a context and additional request options. -// -// See DecodeAuthorizationMessage for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) DecodeAuthorizationMessageWithContext(ctx aws.Context, input *DecodeAuthorizationMessageInput, opts ...request.Option) (*DecodeAuthorizationMessageOutput, error) { - req, out := c.DecodeAuthorizationMessageRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetCallerIdentity = "GetCallerIdentity" - -// GetCallerIdentityRequest generates a "aws/request.Request" representing the -// client's request for the GetCallerIdentity operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetCallerIdentity for more information on using the GetCallerIdentity -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetCallerIdentityRequest method. -// req, resp := client.GetCallerIdentityRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentityRequest(input *GetCallerIdentityInput) (req *request.Request, output *GetCallerIdentityOutput) { - op := &request.Operation{ - Name: opGetCallerIdentity, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetCallerIdentityInput{} - } - - output = &GetCallerIdentityOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetCallerIdentity API operation for AWS Security Token Service. -// -// Returns details about the IAM identity whose credentials are used to call -// the API. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetCallerIdentity for usage and error information. -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity -func (c *STS) GetCallerIdentity(input *GetCallerIdentityInput) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - return out, req.Send() -} - -// GetCallerIdentityWithContext is the same as GetCallerIdentity with the addition of -// the ability to pass a context and additional request options. -// -// See GetCallerIdentity for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetCallerIdentityWithContext(ctx aws.Context, input *GetCallerIdentityInput, opts ...request.Option) (*GetCallerIdentityOutput, error) { - req, out := c.GetCallerIdentityRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetFederationToken = "GetFederationToken" - -// GetFederationTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetFederationToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetFederationToken for more information on using the GetFederationToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetFederationTokenRequest method. -// req, resp := client.GetFederationTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationTokenRequest(input *GetFederationTokenInput) (req *request.Request, output *GetFederationTokenOutput) { - op := &request.Operation{ - Name: opGetFederationToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetFederationTokenInput{} - } - - output = &GetFederationTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetFederationToken API operation for AWS Security Token Service. -// -// Returns a set of temporary security credentials (consisting of an access -// key ID, a secret access key, and a security token) for a federated user. -// A typical use is in a proxy application that gets temporary security credentials -// on behalf of distributed applications inside a corporate network. Because -// you must call the GetFederationToken action using the long-term security -// credentials of an IAM user, this call is appropriate in contexts where those -// credentials can be safely stored, usually in a server-based application. -// For a comparison of GetFederationToken with the other APIs that produce temporary -// credentials, see Requesting Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// If you are creating 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, 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 -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity). -// -// The GetFederationToken action must be called by using the long-term AWS security -// credentials of an IAM user. You can also call GetFederationToken using the -// security credentials of an AWS root account, but we do not recommended it. -// Instead, we recommend that you create an IAM user for the purpose of the -// proxy application and then attach a policy to the IAM user that limits federated -// users to only the actions and resources that they need access to. For more -// information, see IAM Best Practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) -// in the IAM User Guide. -// -// The temporary security credentials that are obtained by using the long-term -// credentials of an IAM user are valid for the specified duration, from 900 -// seconds (15 minutes) up to a maximium of 129600 seconds (36 hours). The default -// is 43200 seconds (12 hours). Temporary credentials that are obtained by using -// AWS root account credentials have a maximum duration of 3600 seconds (1 hour). -// -// The temporary security credentials created by GetFederationToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot use these credentials to call any IAM APIs. -// -// * You cannot call any STS APIs except GetCallerIdentity. -// -// Permissions -// -// The permissions for the temporary security credentials returned by GetFederationToken -// are determined by a combination of the following: -// -// * The policy or policies that are attached to the IAM user whose credentials -// are used to call GetFederationToken. -// -// * The policy that is passed as a parameter in the call. -// -// The passed policy is attached to the temporary security credentials that -// result from the GetFederationToken API call--that is, to the federated user. -// When the federated user makes an AWS request, AWS evaluates the policy attached -// to the federated user in combination with the policy or policies attached -// to the IAM user whose credentials were used to call GetFederationToken. AWS -// allows the federated user's request only when both the federated user and -// the IAM user are explicitly allowed to perform the requested action. The -// passed policy cannot grant more permissions than those that are defined in -// the IAM user policy. -// -// A typical use case is that the permissions of the IAM user whose credentials -// are used to call GetFederationToken are designed to allow access to all the -// actions and resources that any federated user will need. Then, for individual -// users, you pass a policy to the operation that scopes down the permissions -// to a level that's appropriate to that individual user, using a policy that -// allows only a subset of permissions that are granted to the IAM user. -// -// If you do not pass a policy, the resulting temporary security credentials -// have no effective permissions. The only exception is when the temporary security -// credentials are used to access a resource that has a resource-based policy -// that specifically allows the federated user to access the resource. -// -// For more information about how permissions work, see Permissions for GetFederationToken -// (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). -// For information about using GetFederationToken to create temporary security -// credentials, see GetFederationToken—Federation Through a Custom Identity -// Broker (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken). -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetFederationToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeMalformedPolicyDocumentException "MalformedPolicyDocument" -// The request was rejected because the policy document was malformed. The error -// message describes the specific error. -// -// * ErrCodePackedPolicyTooLargeException "PackedPolicyTooLarge" -// The request was rejected because the policy document was too large. The error -// message describes how big the policy document is, in packed form, as a percentage -// of what the API allows. -// -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken -func (c *STS) GetFederationToken(input *GetFederationTokenInput) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - return out, req.Send() -} - -// GetFederationTokenWithContext is the same as GetFederationToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetFederationToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetFederationTokenWithContext(ctx aws.Context, input *GetFederationTokenInput, opts ...request.Option) (*GetFederationTokenOutput, error) { - req, out := c.GetFederationTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -const opGetSessionToken = "GetSessionToken" - -// GetSessionTokenRequest generates a "aws/request.Request" representing the -// client's request for the GetSessionToken operation. The "output" return -// value will be populated with the request's response once the request completes -// successfuly. -// -// Use "Send" method on the returned Request to send the API call to the service. -// the "output" return value is not valid until after Send returns without error. -// -// See GetSessionToken for more information on using the GetSessionToken -// API call, and error handling. -// -// This method is useful when you want to inject custom logic or configuration -// into the SDK's request lifecycle. Such as custom headers, or retry logic. -// -// -// // Example sending a request using the GetSessionTokenRequest method. -// req, resp := client.GetSessionTokenRequest(params) -// -// err := req.Send() -// if err == nil { // resp is now filled -// fmt.Println(resp) -// } -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionTokenRequest(input *GetSessionTokenInput) (req *request.Request, output *GetSessionTokenOutput) { - op := &request.Operation{ - Name: opGetSessionToken, - HTTPMethod: "POST", - HTTPPath: "/", - } - - if input == nil { - input = &GetSessionTokenInput{} - } - - output = &GetSessionTokenOutput{} - req = c.newRequest(op, input, output) - return -} - -// GetSessionToken API operation for AWS Security Token Service. -// -// Returns a set of temporary credentials for an AWS 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 AWS APIs like Amazon EC2 StopInstances. MFA-enabled -// IAM users would need to call GetSessionToken and submit an MFA code that -// is associated with their MFA device. Using the temporary security credentials -// that are returned from the call, IAM users can then make programmatic calls -// to APIs that require MFA authentication. If you do not supply a correct MFA -// code, then the API returns an access denied error. For a comparison of GetSessionToken -// with the other APIs that produce temporary credentials, see Requesting Temporary -// Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html) -// and Comparing the AWS STS APIs (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison) -// in the IAM User Guide. -// -// The GetSessionToken action must be called by using the long-term AWS security -// credentials of the AWS account or an IAM user. Credentials that are created -// by IAM users are valid for the duration that you specify, from 900 seconds -// (15 minutes) up to a maximum of 129600 seconds (36 hours), with a default -// of 43200 seconds (12 hours); credentials that are created by using account -// credentials can range from 900 seconds (15 minutes) up to a maximum of 3600 -// seconds (1 hour), with a default of 1 hour. -// -// The temporary security credentials created by GetSessionToken can be used -// to make API calls to any AWS service with the following exceptions: -// -// * You cannot call any IAM APIs unless MFA authentication information is -// included in the request. -// -// * You cannot call any STS API exceptAssumeRole or GetCallerIdentity. -// -// We recommend that you do not call GetSessionToken with root account credentials. -// Instead, follow our best practices (http://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users) -// by creating one or more IAM users, giving them the necessary permissions, -// and using IAM users for everyday interaction with AWS. -// -// The permissions associated with the temporary security credentials returned -// by GetSessionToken are based on the permissions associated with account or -// IAM user whose credentials are used to call the action. If GetSessionToken -// is called using root account credentials, the temporary credentials have -// root account permissions. Similarly, if GetSessionToken is called using the -// credentials of an IAM user, the temporary credentials have the same permissions -// as the IAM user. -// -// For more information about using GetSessionToken to create temporary credentials, -// go to Temporary Credentials for Users in Untrusted Environments (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken) -// in the IAM User Guide. -// -// Returns awserr.Error for service API and SDK errors. Use runtime type assertions -// with awserr.Error's Code and Message methods to get detailed information about -// the error. -// -// See the AWS API reference guide for AWS Security Token Service's -// API operation GetSessionToken for usage and error information. -// -// Returned Error Codes: -// * ErrCodeRegionDisabledException "RegionDisabledException" -// STS is not activated in the requested region for the account that is being -// asked to generate credentials. The account administrator must use the IAM -// console to activate STS in that region. For more information, see Activating -// and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// See also, https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken -func (c *STS) GetSessionToken(input *GetSessionTokenInput) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - return out, req.Send() -} - -// GetSessionTokenWithContext is the same as GetSessionToken with the addition of -// the ability to pass a context and additional request options. -// -// See GetSessionToken for details on how to use this API operation. -// -// The context must be non-nil and will be used for request cancellation. If -// the context is nil a panic will occur. In the future the SDK may create -// sub-contexts for http.Requests. See https://golang.org/pkg/context/ -// for more information on using Contexts. -func (c *STS) GetSessionTokenWithContext(ctx aws.Context, input *GetSessionTokenInput, opts ...request.Option) (*GetSessionTokenOutput, error) { - req, out := c.GetSessionTokenRequest(input) - req.SetContext(ctx) - req.ApplyOptions(opts...) - return out, req.Send() -} - -type AssumeRoleInput struct { - _ struct{} `type:"structure"` - - // 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 (http://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 - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // A unique identifier that is used by third parties when assuming roles in - // their customers' accounts. For each role that the third party can assume, - // they should instruct their customers to ensure the role's trust policy checks - // for the external ID that the third party generated. Each time the third party - // assumes the role, they should pass the customer's external ID. The external - // ID is useful in order to help third parties bind a role to the customer who - // created it. For more information about the external ID, see How to Use an - // External ID When Granting Access to Your AWS Resources to a Third Party (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html) - // in the IAM User Guide. - // - // The regex used to validated 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 `min:"2" type:"string"` - - // An IAM policy in JSON format. - // - // This parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both (the intersection of) the access policy of the role that - // is being assumed, and the policy that you pass. This gives you a way to further - // restrict the permissions for the resulting temporary security credentials. - // You cannot use the passed policy to grant permissions that are in excess - // of those allowed by the access policy of the role that is being assumed. - // For more information, see Permissions for AssumeRole, AssumeRoleWithSAML, - // and AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // 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 `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the role to assume. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // 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 using 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: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // 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 `min:"9" type:"string"` - - // The value provided by the MFA device, if the trust policy of the role being - // assumed requires MFA (that is, if the policy includes a condition that tests - // for MFA). If the role being assumed requires MFA and if the TokenCode value - // is missing or expired, the AssumeRole call returns an "access denied" error. - // - // The format for this parameter, as described by its regex pattern, is a sequence - // of six numeric digits. - TokenCode *string `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.ExternalId != nil && len(*s.ExternalId) < 2 { - invalidParams.Add(request.NewErrParamMinLen("ExternalId", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleInput) SetDurationSeconds(v int64) *AssumeRoleInput { - s.DurationSeconds = &v - return s -} - -// SetExternalId sets the ExternalId field's value. -func (s *AssumeRoleInput) SetExternalId(v string) *AssumeRoleInput { - s.ExternalId = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleInput) SetPolicy(v string) *AssumeRoleInput { - s.Policy = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleInput) SetRoleArn(v string) *AssumeRoleInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleInput) SetRoleSessionName(v string) *AssumeRoleInput { - s.RoleSessionName = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *AssumeRoleInput) SetSerialNumber(v string) *AssumeRoleInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *AssumeRoleInput) SetTokenCode(v string) *AssumeRoleInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful AssumeRole request, including temporary -// AWS credentials that can be used to make AWS requests. -type AssumeRoleOutput struct { - _ struct{} `type:"structure"` - - // 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 *AssumedRoleUser `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s AssumeRoleOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleOutput { - s.AssumedRoleUser = v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleOutput) SetCredentials(v *Credentials) *AssumeRoleOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleOutput) SetPackedPolicySize(v int64) *AssumeRoleOutput { - s.PackedPolicySize = &v - return s -} - -type AssumeRoleWithSAMLInput struct { - _ struct{} `type:"structure"` - - // 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 (http://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 - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // Permissions for AssumeRole, AssumeRoleWithSAML, and AssumeRoleWithWebIdentity - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // 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 `min:"1" type:"string"` - - // The Amazon Resource Name (ARN) of the SAML provider in IAM that describes - // the IdP. - // - // PrincipalArn is a required field - PrincipalArn *string `min:"20" type:"string" required:"true"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // The base-64 encoded SAML authentication response provided by the IdP. - // - // For more information, see Configuring a Relying Party and Adding Claims (http://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html) - // in the Using IAM guide. - // - // SAMLAssertion is a required field - SAMLAssertion *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithSAMLInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithSAMLInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.PrincipalArn == nil { - invalidParams.Add(request.NewErrParamRequired("PrincipalArn")) - } - if s.PrincipalArn != nil && len(*s.PrincipalArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("PrincipalArn", 20)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.SAMLAssertion == nil { - invalidParams.Add(request.NewErrParamRequired("SAMLAssertion")) - } - if s.SAMLAssertion != nil && len(*s.SAMLAssertion) < 4 { - invalidParams.Add(request.NewErrParamMinLen("SAMLAssertion", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithSAMLInput) SetDurationSeconds(v int64) *AssumeRoleWithSAMLInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithSAMLInput) SetPolicy(v string) *AssumeRoleWithSAMLInput { - s.Policy = &v - return s -} - -// SetPrincipalArn sets the PrincipalArn field's value. -func (s *AssumeRoleWithSAMLInput) SetPrincipalArn(v string) *AssumeRoleWithSAMLInput { - s.PrincipalArn = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithSAMLInput) SetRoleArn(v string) *AssumeRoleWithSAMLInput { - s.RoleArn = &v - return s -} - -// SetSAMLAssertion sets the SAMLAssertion field's value. -func (s *AssumeRoleWithSAMLInput) SetSAMLAssertion(v string) *AssumeRoleWithSAMLInput { - s.SAMLAssertion = &v - return s -} - -// Contains the response to a successful AssumeRoleWithSAML request, including -// temporary AWS credentials that can be used to make AWS requests. -type AssumeRoleWithSAMLOutput struct { - _ struct{} `type:"structure"` - - // The identifiers for the temporary security credentials that the operation - // returns. - AssumedRoleUser *AssumedRoleUser `type:"structure"` - - // The value of the Recipient attribute of the SubjectConfirmationData element - // of the SAML assertion. - Audience *string `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // The value of the Issuer element of the SAML assertion. - Issuer *string `type:"string"` - - // A hash value based on the concatenation of the Issuer response value, the - // AWS account ID, and 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 federated user. - // - // The following pseudocode shows how the hash value is calculated: - // - // BASE64 ( SHA1 ( "https://example.com/saml" + "123456789012" + "/MySAMLIdP" - // ) ) - NameQualifier *string `type:"string"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // The value of the NameID element in the Subject element of the SAML assertion. - Subject *string `type:"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 `type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithSAMLOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithSAMLOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithSAMLOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithSAMLOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithSAMLOutput) SetAudience(v string) *AssumeRoleWithSAMLOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithSAMLOutput) SetCredentials(v *Credentials) *AssumeRoleWithSAMLOutput { - s.Credentials = v - return s -} - -// SetIssuer sets the Issuer field's value. -func (s *AssumeRoleWithSAMLOutput) SetIssuer(v string) *AssumeRoleWithSAMLOutput { - s.Issuer = &v - return s -} - -// SetNameQualifier sets the NameQualifier field's value. -func (s *AssumeRoleWithSAMLOutput) SetNameQualifier(v string) *AssumeRoleWithSAMLOutput { - s.NameQualifier = &v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithSAMLOutput) SetPackedPolicySize(v int64) *AssumeRoleWithSAMLOutput { - s.PackedPolicySize = &v - return s -} - -// SetSubject sets the Subject field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubject(v string) *AssumeRoleWithSAMLOutput { - s.Subject = &v - return s -} - -// SetSubjectType sets the SubjectType field's value. -func (s *AssumeRoleWithSAMLOutput) SetSubjectType(v string) *AssumeRoleWithSAMLOutput { - s.SubjectType = &v - return s -} - -type AssumeRoleWithWebIdentityInput struct { - _ struct{} `type:"structure"` - - // 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 (http://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 - // AWS Management Console (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html) - // in the IAM User Guide. - DurationSeconds *int64 `min:"900" type:"integer"` - - // An IAM policy in JSON format. - // - // The policy parameter is optional. If you pass a policy, the temporary security - // credentials that are returned by the operation have the permissions that - // are allowed by both the access policy of the role that is being assumed, - // and the policy that you pass. This gives you a way to further restrict the - // permissions for the resulting temporary security credentials. You cannot - // use the passed policy to grant permissions that are in excess of those allowed - // by the access policy of the role that is being assumed. For more information, - // see Permissions for AssumeRoleWithWebIdentity (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_assumerole.html) - // in the IAM User Guide. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // 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 `min:"1" type:"string"` - - // The fully qualified host component of the domain name of the identity provider. - // - // Specify this value only for OAuth 2.0 access tokens. 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 `min:"4" type:"string"` - - // The Amazon Resource Name (ARN) of the role that the caller is assuming. - // - // RoleArn is a required field - RoleArn *string `min:"20" type:"string" required:"true"` - - // 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: =,.@- - // - // RoleSessionName is a required field - RoleSessionName *string `min:"2" type:"string" required:"true"` - - // 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. - // - // WebIdentityToken is a required field - WebIdentityToken *string `min:"4" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *AssumeRoleWithWebIdentityInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "AssumeRoleWithWebIdentityInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - if s.ProviderId != nil && len(*s.ProviderId) < 4 { - invalidParams.Add(request.NewErrParamMinLen("ProviderId", 4)) - } - if s.RoleArn == nil { - invalidParams.Add(request.NewErrParamRequired("RoleArn")) - } - if s.RoleArn != nil && len(*s.RoleArn) < 20 { - invalidParams.Add(request.NewErrParamMinLen("RoleArn", 20)) - } - if s.RoleSessionName == nil { - invalidParams.Add(request.NewErrParamRequired("RoleSessionName")) - } - if s.RoleSessionName != nil && len(*s.RoleSessionName) < 2 { - invalidParams.Add(request.NewErrParamMinLen("RoleSessionName", 2)) - } - if s.WebIdentityToken == nil { - invalidParams.Add(request.NewErrParamRequired("WebIdentityToken")) - } - if s.WebIdentityToken != nil && len(*s.WebIdentityToken) < 4 { - invalidParams.Add(request.NewErrParamMinLen("WebIdentityToken", 4)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *AssumeRoleWithWebIdentityInput) SetDurationSeconds(v int64) *AssumeRoleWithWebIdentityInput { - s.DurationSeconds = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *AssumeRoleWithWebIdentityInput) SetPolicy(v string) *AssumeRoleWithWebIdentityInput { - s.Policy = &v - return s -} - -// SetProviderId sets the ProviderId field's value. -func (s *AssumeRoleWithWebIdentityInput) SetProviderId(v string) *AssumeRoleWithWebIdentityInput { - s.ProviderId = &v - return s -} - -// SetRoleArn sets the RoleArn field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleArn(v string) *AssumeRoleWithWebIdentityInput { - s.RoleArn = &v - return s -} - -// SetRoleSessionName sets the RoleSessionName field's value. -func (s *AssumeRoleWithWebIdentityInput) SetRoleSessionName(v string) *AssumeRoleWithWebIdentityInput { - s.RoleSessionName = &v - return s -} - -// SetWebIdentityToken sets the WebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityInput) SetWebIdentityToken(v string) *AssumeRoleWithWebIdentityInput { - s.WebIdentityToken = &v - return s -} - -// Contains the response to a successful AssumeRoleWithWebIdentity request, -// including temporary AWS credentials that can be used to make AWS requests. -type AssumeRoleWithWebIdentityOutput struct { - _ struct{} `type:"structure"` - - // 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 *AssumedRoleUser `type:"structure"` - - // 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 `type:"string"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // A percentage value that indicates the size of the policy in packed form. - // The service rejects any policy with a packed size greater than 100 percent, - // which means the policy exceeded the allowed space. - PackedPolicySize *int64 `type:"integer"` - - // 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 `type:"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 `min:"6" type:"string"` -} - -// String returns the string representation -func (s AssumeRoleWithWebIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumeRoleWithWebIdentityOutput) GoString() string { - return s.String() -} - -// SetAssumedRoleUser sets the AssumedRoleUser field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAssumedRoleUser(v *AssumedRoleUser) *AssumeRoleWithWebIdentityOutput { - s.AssumedRoleUser = v - return s -} - -// SetAudience sets the Audience field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetAudience(v string) *AssumeRoleWithWebIdentityOutput { - s.Audience = &v - return s -} - -// SetCredentials sets the Credentials field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetCredentials(v *Credentials) *AssumeRoleWithWebIdentityOutput { - s.Credentials = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetPackedPolicySize(v int64) *AssumeRoleWithWebIdentityOutput { - s.PackedPolicySize = &v - return s -} - -// SetProvider sets the Provider field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetProvider(v string) *AssumeRoleWithWebIdentityOutput { - s.Provider = &v - return s -} - -// SetSubjectFromWebIdentityToken sets the SubjectFromWebIdentityToken field's value. -func (s *AssumeRoleWithWebIdentityOutput) SetSubjectFromWebIdentityToken(v string) *AssumeRoleWithWebIdentityOutput { - s.SubjectFromWebIdentityToken = &v - return s -} - -// The identifiers for the temporary security credentials that the operation -// returns. -type AssumedRoleUser struct { - _ struct{} `type:"structure"` - - // 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 (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // 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 AWS when the - // role is created. - // - // AssumedRoleId is a required field - AssumedRoleId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s AssumedRoleUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s AssumedRoleUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *AssumedRoleUser) SetArn(v string) *AssumedRoleUser { - s.Arn = &v - return s -} - -// SetAssumedRoleId sets the AssumedRoleId field's value. -func (s *AssumedRoleUser) SetAssumedRoleId(v string) *AssumedRoleUser { - s.AssumedRoleId = &v - return s -} - -// AWS credentials for API authentication. -type Credentials struct { - _ struct{} `type:"structure"` - - // The access key ID that identifies the temporary security credentials. - // - // AccessKeyId is a required field - AccessKeyId *string `min:"16" type:"string" required:"true"` - - // The date on which the current credentials expire. - // - // Expiration is a required field - Expiration *time.Time `type:"timestamp" timestampFormat:"iso8601" required:"true"` - - // The secret access key that can be used to sign requests. - // - // SecretAccessKey is a required field - SecretAccessKey *string `type:"string" required:"true"` - - // The token that users must pass to the service API to use the temporary credentials. - // - // SessionToken is a required field - SessionToken *string `type:"string" required:"true"` -} - -// String returns the string representation -func (s Credentials) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s Credentials) GoString() string { - return s.String() -} - -// SetAccessKeyId sets the AccessKeyId field's value. -func (s *Credentials) SetAccessKeyId(v string) *Credentials { - s.AccessKeyId = &v - return s -} - -// SetExpiration sets the Expiration field's value. -func (s *Credentials) SetExpiration(v time.Time) *Credentials { - s.Expiration = &v - return s -} - -// SetSecretAccessKey sets the SecretAccessKey field's value. -func (s *Credentials) SetSecretAccessKey(v string) *Credentials { - s.SecretAccessKey = &v - return s -} - -// SetSessionToken sets the SessionToken field's value. -func (s *Credentials) SetSessionToken(v string) *Credentials { - s.SessionToken = &v - return s -} - -type DecodeAuthorizationMessageInput struct { - _ struct{} `type:"structure"` - - // The encoded message that was returned with the response. - // - // EncodedMessage is a required field - EncodedMessage *string `min:"1" type:"string" required:"true"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *DecodeAuthorizationMessageInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "DecodeAuthorizationMessageInput"} - if s.EncodedMessage == nil { - invalidParams.Add(request.NewErrParamRequired("EncodedMessage")) - } - if s.EncodedMessage != nil && len(*s.EncodedMessage) < 1 { - invalidParams.Add(request.NewErrParamMinLen("EncodedMessage", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetEncodedMessage sets the EncodedMessage field's value. -func (s *DecodeAuthorizationMessageInput) SetEncodedMessage(v string) *DecodeAuthorizationMessageInput { - s.EncodedMessage = &v - return s -} - -// A document that contains additional information about the authorization status -// of a request from an encoded message that is returned in response to an AWS -// request. -type DecodeAuthorizationMessageOutput struct { - _ struct{} `type:"structure"` - - // An XML document that contains the decoded message. - DecodedMessage *string `type:"string"` -} - -// String returns the string representation -func (s DecodeAuthorizationMessageOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s DecodeAuthorizationMessageOutput) GoString() string { - return s.String() -} - -// SetDecodedMessage sets the DecodedMessage field's value. -func (s *DecodeAuthorizationMessageOutput) SetDecodedMessage(v string) *DecodeAuthorizationMessageOutput { - s.DecodedMessage = &v - return s -} - -// Identifiers for the federated user that is associated with the credentials. -type FederatedUser struct { - _ struct{} `type:"structure"` - - // 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 (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html) - // in Using IAM. - // - // Arn is a required field - Arn *string `min:"20" type:"string" required:"true"` - - // The string that identifies the federated user associated with the credentials, - // similar to the unique ID of an IAM user. - // - // FederatedUserId is a required field - FederatedUserId *string `min:"2" type:"string" required:"true"` -} - -// String returns the string representation -func (s FederatedUser) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s FederatedUser) GoString() string { - return s.String() -} - -// SetArn sets the Arn field's value. -func (s *FederatedUser) SetArn(v string) *FederatedUser { - s.Arn = &v - return s -} - -// SetFederatedUserId sets the FederatedUserId field's value. -func (s *FederatedUser) SetFederatedUserId(v string) *FederatedUser { - s.FederatedUserId = &v - return s -} - -type GetCallerIdentityInput struct { - _ struct{} `type:"structure"` -} - -// String returns the string representation -func (s GetCallerIdentityInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityInput) GoString() string { - return s.String() -} - -// Contains the response to a successful GetCallerIdentity request, including -// information about the entity making the request. -type GetCallerIdentityOutput struct { - _ struct{} `type:"structure"` - - // The AWS account ID number of the account that owns or contains the calling - // entity. - Account *string `type:"string"` - - // The AWS ARN associated with the calling entity. - Arn *string `min:"20" type:"string"` - - // The unique identifier of the calling entity. The exact value depends on the - // type of entity making the call. The values returned are those listed in the - // aws:userid column in the Principal table (http://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 `type:"string"` -} - -// String returns the string representation -func (s GetCallerIdentityOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetCallerIdentityOutput) GoString() string { - return s.String() -} - -// SetAccount sets the Account field's value. -func (s *GetCallerIdentityOutput) SetAccount(v string) *GetCallerIdentityOutput { - s.Account = &v - return s -} - -// SetArn sets the Arn field's value. -func (s *GetCallerIdentityOutput) SetArn(v string) *GetCallerIdentityOutput { - s.Arn = &v - return s -} - -// SetUserId sets the UserId field's value. -func (s *GetCallerIdentityOutput) SetUserId(v string) *GetCallerIdentityOutput { - s.UserId = &v - return s -} - -type GetFederationTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the session should last. Acceptable durations - // for federation sessions range from 900 seconds (15 minutes) to 129600 seconds - // (36 hours), with 43200 seconds (12 hours) as the default. Sessions obtained - // using AWS account (root) credentials are restricted to a maximum of 3600 - // seconds (one hour). If the specified duration is longer than one hour, the - // session obtained by using AWS account (root) credentials defaults to one - // hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // 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: =,.@- - // - // Name is a required field - Name *string `min:"2" type:"string" required:"true"` - - // An IAM policy in JSON format that is passed with the GetFederationToken call - // and evaluated along with the policy or policies that are attached to the - // IAM user whose credentials are used to call GetFederationToken. The passed - // policy is used to scope down the permissions that are available to the IAM - // user, by allowing only a subset of the permissions that are granted to the - // IAM user. The passed policy cannot grant more permissions than those granted - // to the IAM user. The final permissions for the federated user are the most - // restrictive set based on the intersection of the passed policy and the IAM - // user policy. - // - // If you do not pass a policy, the resulting temporary security credentials - // have no effective permissions. The only exception is when the temporary security - // credentials are used to access a resource that has a resource-based policy - // that specifically allows the federated user to access the resource. - // - // The format for this parameter, as described by its regex pattern, is a string - // of characters up to 2048 characters in length. The characters can be any - // ASCII character from the space character to the end of the valid character - // list (\u0020-\u00FF). It can also include the tab (\u0009), linefeed (\u000A), - // and carriage return (\u000D) characters. - // - // 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. - // - // For more information about how permissions work, see Permissions for GetFederationToken - // (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_getfederationtoken.html). - Policy *string `min:"1" type:"string"` -} - -// String returns the string representation -func (s GetFederationTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetFederationTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetFederationTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.Name == nil { - invalidParams.Add(request.NewErrParamRequired("Name")) - } - if s.Name != nil && len(*s.Name) < 2 { - invalidParams.Add(request.NewErrParamMinLen("Name", 2)) - } - if s.Policy != nil && len(*s.Policy) < 1 { - invalidParams.Add(request.NewErrParamMinLen("Policy", 1)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetFederationTokenInput) SetDurationSeconds(v int64) *GetFederationTokenInput { - s.DurationSeconds = &v - return s -} - -// SetName sets the Name field's value. -func (s *GetFederationTokenInput) SetName(v string) *GetFederationTokenInput { - s.Name = &v - return s -} - -// SetPolicy sets the Policy field's value. -func (s *GetFederationTokenInput) SetPolicy(v string) *GetFederationTokenInput { - s.Policy = &v - return s -} - -// Contains the response to a successful GetFederationToken request, including -// temporary AWS credentials that can be used to make AWS requests. -type GetFederationTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` - - // 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 *FederatedUser `type:"structure"` - - // A percentage value indicating the size of the policy in packed form. The - // service rejects policies for which the packed size is greater than 100 percent - // of the allowed value. - PackedPolicySize *int64 `type:"integer"` -} - -// String returns the string representation -func (s GetFederationTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetFederationTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetFederationTokenOutput) SetCredentials(v *Credentials) *GetFederationTokenOutput { - s.Credentials = v - return s -} - -// SetFederatedUser sets the FederatedUser field's value. -func (s *GetFederationTokenOutput) SetFederatedUser(v *FederatedUser) *GetFederationTokenOutput { - s.FederatedUser = v - return s -} - -// SetPackedPolicySize sets the PackedPolicySize field's value. -func (s *GetFederationTokenOutput) SetPackedPolicySize(v int64) *GetFederationTokenOutput { - s.PackedPolicySize = &v - return s -} - -type GetSessionTokenInput struct { - _ struct{} `type:"structure"` - - // The duration, in seconds, that the credentials should remain valid. Acceptable - // durations for IAM user sessions range from 900 seconds (15 minutes) to 129600 - // seconds (36 hours), with 43200 seconds (12 hours) as the default. Sessions - // for AWS account owners are restricted to a maximum of 3600 seconds (one hour). - // If the duration is longer than one hour, the session for AWS account owners - // defaults to one hour. - DurationSeconds *int64 `min:"900" type:"integer"` - - // 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 AWS Management Console - // and viewing the user's security credentials. - // - // The regex used to validated 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 `min:"9" type:"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, and the user does not provide a code when requesting a set of - // temporary security credentials, the user will receive 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 `min:"6" type:"string"` -} - -// String returns the string representation -func (s GetSessionTokenInput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenInput) GoString() string { - return s.String() -} - -// Validate inspects the fields of the type to determine if they are valid. -func (s *GetSessionTokenInput) Validate() error { - invalidParams := request.ErrInvalidParams{Context: "GetSessionTokenInput"} - if s.DurationSeconds != nil && *s.DurationSeconds < 900 { - invalidParams.Add(request.NewErrParamMinValue("DurationSeconds", 900)) - } - if s.SerialNumber != nil && len(*s.SerialNumber) < 9 { - invalidParams.Add(request.NewErrParamMinLen("SerialNumber", 9)) - } - if s.TokenCode != nil && len(*s.TokenCode) < 6 { - invalidParams.Add(request.NewErrParamMinLen("TokenCode", 6)) - } - - if invalidParams.Len() > 0 { - return invalidParams - } - return nil -} - -// SetDurationSeconds sets the DurationSeconds field's value. -func (s *GetSessionTokenInput) SetDurationSeconds(v int64) *GetSessionTokenInput { - s.DurationSeconds = &v - return s -} - -// SetSerialNumber sets the SerialNumber field's value. -func (s *GetSessionTokenInput) SetSerialNumber(v string) *GetSessionTokenInput { - s.SerialNumber = &v - return s -} - -// SetTokenCode sets the TokenCode field's value. -func (s *GetSessionTokenInput) SetTokenCode(v string) *GetSessionTokenInput { - s.TokenCode = &v - return s -} - -// Contains the response to a successful GetSessionToken request, including -// temporary AWS credentials that can be used to make AWS requests. -type GetSessionTokenOutput struct { - _ struct{} `type:"structure"` - - // The temporary security credentials, which include an access key ID, a secret - // access key, and a security (or session) token. - // - // Note: The size of the security token that STS APIs return is not fixed. We - // strongly recommend that you make no assumptions about the maximum size. As - // of this writing, the typical size is less than 4096 bytes, but that can vary. - // Also, future updates to AWS might require larger sizes. - Credentials *Credentials `type:"structure"` -} - -// String returns the string representation -func (s GetSessionTokenOutput) String() string { - return awsutil.Prettify(s) -} - -// GoString returns the string representation -func (s GetSessionTokenOutput) GoString() string { - return s.String() -} - -// SetCredentials sets the Credentials field's value. -func (s *GetSessionTokenOutput) SetCredentials(v *Credentials) *GetSessionTokenOutput { - s.Credentials = v - return s -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go b/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go deleted file mode 100644 index 4010cc7fa..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/customizations.go +++ /dev/null @@ -1,12 +0,0 @@ -package sts - -import "github.com/aws/aws-sdk-go/aws/request" - -func init() { - initRequest = func(r *request.Request) { - switch r.Operation.Name { - case opAssumeRoleWithSAML, opAssumeRoleWithWebIdentity: - r.Handlers.Sign.Clear() // these operations are unsigned - } - } -} diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go b/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go deleted file mode 100644 index ef681ab0c..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/doc.go +++ /dev/null @@ -1,72 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -// Package sts provides the client and types for making API -// requests to AWS Security Token Service. -// -// The AWS Security Token Service (STS) is a web service that enables you to -// request temporary, limited-privilege credentials for AWS Identity and Access -// Management (IAM) users or for users that you authenticate (federated users). -// This guide provides descriptions of the STS API. For more detailed information -// about using this service, go to Temporary Security Credentials (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp.html). -// -// As an alternative to using the API, you can use one of the AWS SDKs, which -// consist of libraries and sample code for various programming languages and -// platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs provide a convenient -// way to create programmatic access to STS. For example, the SDKs take care -// of cryptographically signing requests, managing errors, and retrying requests -// automatically. For information about the AWS SDKs, including how to download -// and install them, see the Tools for Amazon Web Services page (http://aws.amazon.com/tools/). -// -// For information about setting up signatures and authorization through the -// API, go to Signing AWS API Requests (http://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) -// in the AWS General Reference. For general information about the Query API, -// go to Making Query Requests (http://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html) -// in Using IAM. For information about using security tokens with other AWS -// products, go to AWS Services That Work with IAM (http://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html) -// in the IAM User Guide. -// -// If you're new to AWS and need additional technical information about a specific -// AWS product, you can find the product's technical documentation at http://aws.amazon.com/documentation/ -// (http://aws.amazon.com/documentation/). -// -// Endpoints -// -// The AWS Security Token Service (STS) has a default endpoint of https://sts.amazonaws.com -// that maps to the US East (N. Virginia) region. Additional regions are available -// and are activated by default. For more information, see Activating and Deactivating -// AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) -// in the IAM User Guide. -// -// For information about STS endpoints, see Regions and Endpoints (http://docs.aws.amazon.com/general/latest/gr/rande.html#sts_region) -// in the AWS General Reference. -// -// Recording API requests -// -// STS supports AWS CloudTrail, which is a service that records AWS calls for -// your AWS account and delivers log files to an Amazon S3 bucket. By using -// information collected by CloudTrail, you can determine what requests were -// successfully made to STS, who made the request, when it was made, and so -// on. To learn more about CloudTrail, including how to turn it on and find -// your log files, see the AWS CloudTrail User Guide (http://docs.aws.amazon.com/awscloudtrail/latest/userguide/what_is_cloud_trail_top_level.html). -// -// See https://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15 for more information on this service. -// -// See sts package documentation for more information. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/ -// -// Using the Client -// -// To contact AWS Security Token Service with the SDK use the New function to create -// a new service client. With that client you can make API requests to the service. -// These clients are safe to use concurrently. -// -// See the SDK's documentation for more information on how to use the SDK. -// https://docs.aws.amazon.com/sdk-for-go/api/ -// -// See aws.Config documentation for more information on configuring SDK clients. -// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config -// -// See the AWS Security Token Service client STS for more -// information on creating client for this service. -// https://docs.aws.amazon.com/sdk-for-go/api/service/sts/#New -package sts diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go b/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go deleted file mode 100644 index e24884ef3..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/errors.go +++ /dev/null @@ -1,73 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -const ( - - // ErrCodeExpiredTokenException for service response error code - // "ExpiredTokenException". - // - // The web identity token that was passed is expired or is not valid. Get a - // new identity token from the identity provider and then retry the request. - ErrCodeExpiredTokenException = "ExpiredTokenException" - - // ErrCodeIDPCommunicationErrorException for service response error code - // "IDPCommunicationError". - // - // The request could not be fulfilled because the non-AWS identity provider - // (IDP) that was asked to verify the incoming identity token could not be reached. - // This is often a transient error caused by network conditions. Retry the request - // a limited number of times so that you don't exceed the request rate. If the - // error persists, the non-AWS identity provider might be down or not responding. - ErrCodeIDPCommunicationErrorException = "IDPCommunicationError" - - // ErrCodeIDPRejectedClaimException for service response error code - // "IDPRejectedClaim". - // - // The identity provider (IdP) reported that authentication failed. This might - // be because the claim is invalid. - // - // If this error is returned for the AssumeRoleWithWebIdentity operation, it - // can also mean that the claim has expired or has been explicitly revoked. - ErrCodeIDPRejectedClaimException = "IDPRejectedClaim" - - // ErrCodeInvalidAuthorizationMessageException for service response error code - // "InvalidAuthorizationMessageException". - // - // The error returned if the message passed to DecodeAuthorizationMessage was - // invalid. This can happen if the token contains invalid characters, such as - // linebreaks. - ErrCodeInvalidAuthorizationMessageException = "InvalidAuthorizationMessageException" - - // ErrCodeInvalidIdentityTokenException for service response error code - // "InvalidIdentityToken". - // - // The web identity token that was passed could not be validated by AWS. Get - // a new identity token from the identity provider and then retry the request. - ErrCodeInvalidIdentityTokenException = "InvalidIdentityToken" - - // ErrCodeMalformedPolicyDocumentException for service response error code - // "MalformedPolicyDocument". - // - // The request was rejected because the policy document was malformed. The error - // message describes the specific error. - ErrCodeMalformedPolicyDocumentException = "MalformedPolicyDocument" - - // ErrCodePackedPolicyTooLargeException for service response error code - // "PackedPolicyTooLarge". - // - // The request was rejected because the policy document was too large. The error - // message describes how big the policy document is, in packed form, as a percentage - // of what the API allows. - ErrCodePackedPolicyTooLargeException = "PackedPolicyTooLarge" - - // ErrCodeRegionDisabledException for service response error code - // "RegionDisabledException". - // - // STS is not activated in the requested region for the account that is being - // asked to generate credentials. The account administrator must use the IAM - // console to activate STS in that region. For more information, see Activating - // and Deactivating AWS STS in an AWS Region (http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_enable-regions.html) - // in the IAM User Guide. - ErrCodeRegionDisabledException = "RegionDisabledException" -) diff --git a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go b/vendor/github.com/aws/aws-sdk-go/service/sts/service.go deleted file mode 100644 index 1ee5839e0..000000000 --- a/vendor/github.com/aws/aws-sdk-go/service/sts/service.go +++ /dev/null @@ -1,93 +0,0 @@ -// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. - -package sts - -import ( - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/client/metadata" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/signer/v4" - "github.com/aws/aws-sdk-go/private/protocol/query" -) - -// STS provides the API operation methods for making requests to -// AWS Security Token Service. See this package's package overview docs -// for details on the service. -// -// STS methods are safe to use concurrently. It is not safe to -// modify mutate any of the struct's properties though. -type STS struct { - *client.Client -} - -// Used for custom client initialization logic -var initClient func(*client.Client) - -// Used for custom request initialization logic -var initRequest func(*request.Request) - -// Service information constants -const ( - ServiceName = "sts" // Service endpoint prefix API calls made to. - EndpointsID = ServiceName // Service ID for Regions and Endpoints metadata. -) - -// New creates a new instance of the STS client with a session. -// If additional configuration is needed for the client instance use the optional -// aws.Config parameter to add your extra config. -// -// Example: -// // Create a STS client from just a session. -// svc := sts.New(mySession) -// -// // Create a STS client with additional configuration -// svc := sts.New(mySession, aws.NewConfig().WithRegion("us-west-2")) -func New(p client.ConfigProvider, cfgs ...*aws.Config) *STS { - c := p.ClientConfig(EndpointsID, cfgs...) - return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) -} - -// newClient creates, initializes and returns a new service client instance. -func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *STS { - svc := &STS{ - Client: client.New( - cfg, - metadata.ClientInfo{ - ServiceName: ServiceName, - SigningName: signingName, - SigningRegion: signingRegion, - Endpoint: endpoint, - APIVersion: "2011-06-15", - }, - handlers, - ), - } - - // Handlers - svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler) - svc.Handlers.Build.PushBackNamed(query.BuildHandler) - svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler) - svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler) - svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler) - - // Run custom client initialization if present - if initClient != nil { - initClient(svc.Client) - } - - return svc -} - -// newRequest creates a new request for a STS operation and runs any -// custom request initialization. -func (c *STS) newRequest(op *request.Operation, params, data interface{}) *request.Request { - req := c.NewRequest(op, params, data) - - // Run custom request initialization if present - if initRequest != nil { - initRequest(req) - } - - return req -} diff --git a/vendor/github.com/beorn7/perks/LICENSE b/vendor/github.com/beorn7/perks/LICENSE deleted file mode 100644 index 339177be6..000000000 --- a/vendor/github.com/beorn7/perks/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (C) 2013 Blake Mizerany - -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/beorn7/perks/quantile/stream.go b/vendor/github.com/beorn7/perks/quantile/stream.go deleted file mode 100644 index f4cabd669..000000000 --- a/vendor/github.com/beorn7/perks/quantile/stream.go +++ /dev/null @@ -1,292 +0,0 @@ -// Package quantile computes approximate quantiles over an unbounded data -// stream within low memory and CPU bounds. -// -// A small amount of accuracy is traded to achieve the above properties. -// -// Multiple streams can be merged before calling Query to generate a single set -// of results. This is meaningful when the streams represent the same type of -// data. See Merge and Samples. -// -// For more detailed information about the algorithm used, see: -// -// Effective Computation of Biased Quantiles over Data Streams -// -// http://www.cs.rutgers.edu/~muthu/bquant.pdf -package quantile - -import ( - "math" - "sort" -) - -// Sample holds an observed value and meta information for compression. JSON -// tags have been added for convenience. -type Sample struct { - Value float64 `json:",string"` - Width float64 `json:",string"` - Delta float64 `json:",string"` -} - -// Samples represents a slice of samples. It implements sort.Interface. -type Samples []Sample - -func (a Samples) Len() int { return len(a) } -func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value } -func (a Samples) Swap(i, j int) { a[i], a[j] = a[j], a[i] } - -type invariant func(s *stream, r float64) float64 - -// NewLowBiased returns an initialized Stream for low-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the lower ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within (1±Epsilon)*Quantile. -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewLowBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * r - } - return newStream(ƒ) -} - -// NewHighBiased returns an initialized Stream for high-biased quantiles -// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but -// error guarantees can still be given even for the higher ranks of the data -// distribution. -// -// The provided epsilon is a relative error, i.e. the true quantile of a value -// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error -// properties. -func NewHighBiased(epsilon float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - return 2 * epsilon * (s.n - r) - } - return newStream(ƒ) -} - -// NewTargeted returns an initialized Stream concerned with a particular set of -// quantile values that are supplied a priori. Knowing these a priori reduces -// space and computation time. The targets map maps the desired quantiles to -// their absolute errors, i.e. the true quantile of a value returned by a query -// is guaranteed to be within (Quantile±Epsilon). -// -// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties. -func NewTargeted(targets map[float64]float64) *Stream { - ƒ := func(s *stream, r float64) float64 { - var m = math.MaxFloat64 - var f float64 - for quantile, epsilon := range targets { - if quantile*s.n <= r { - f = (2 * epsilon * r) / quantile - } else { - f = (2 * epsilon * (s.n - r)) / (1 - quantile) - } - if f < m { - m = f - } - } - return m - } - return newStream(ƒ) -} - -// Stream computes quantiles for a stream of float64s. It is not thread-safe by -// design. Take care when using across multiple goroutines. -type Stream struct { - *stream - b Samples - sorted bool -} - -func newStream(ƒ invariant) *Stream { - x := &stream{ƒ: ƒ} - return &Stream{x, make(Samples, 0, 500), true} -} - -// Insert inserts v into the stream. -func (s *Stream) Insert(v float64) { - s.insert(Sample{Value: v, Width: 1}) -} - -func (s *Stream) insert(sample Sample) { - s.b = append(s.b, sample) - s.sorted = false - if len(s.b) == cap(s.b) { - s.flush() - } -} - -// Query returns the computed qth percentiles value. If s was created with -// NewTargeted, and q is not in the set of quantiles provided a priori, Query -// will return an unspecified result. -func (s *Stream) Query(q float64) float64 { - if !s.flushed() { - // Fast path when there hasn't been enough data for a flush; - // this also yields better accuracy for small sets of data. - l := len(s.b) - if l == 0 { - return 0 - } - i := int(math.Ceil(float64(l) * q)) - if i > 0 { - i -= 1 - } - s.maybeSort() - return s.b[i].Value - } - s.flush() - return s.stream.query(q) -} - -// Merge merges samples into the underlying streams samples. This is handy when -// merging multiple streams from separate threads, database shards, etc. -// -// ATTENTION: This method is broken and does not yield correct results. The -// underlying algorithm is not capable of merging streams correctly. -func (s *Stream) Merge(samples Samples) { - sort.Sort(samples) - s.stream.merge(samples) -} - -// Reset reinitializes and clears the list reusing the samples buffer memory. -func (s *Stream) Reset() { - s.stream.reset() - s.b = s.b[:0] -} - -// Samples returns stream samples held by s. -func (s *Stream) Samples() Samples { - if !s.flushed() { - return s.b - } - s.flush() - return s.stream.samples() -} - -// Count returns the total number of samples observed in the stream -// since initialization. -func (s *Stream) Count() int { - return len(s.b) + s.stream.count() -} - -func (s *Stream) flush() { - s.maybeSort() - s.stream.merge(s.b) - s.b = s.b[:0] -} - -func (s *Stream) maybeSort() { - if !s.sorted { - s.sorted = true - sort.Sort(s.b) - } -} - -func (s *Stream) flushed() bool { - return len(s.stream.l) > 0 -} - -type stream struct { - n float64 - l []Sample - ƒ invariant -} - -func (s *stream) reset() { - s.l = s.l[:0] - s.n = 0 -} - -func (s *stream) insert(v float64) { - s.merge(Samples{{v, 1, 0}}) -} - -func (s *stream) merge(samples Samples) { - // TODO(beorn7): This tries to merge not only individual samples, but - // whole summaries. The paper doesn't mention merging summaries at - // all. Unittests show that the merging is inaccurate. Find out how to - // do merges properly. - var r float64 - i := 0 - for _, sample := range samples { - for ; i < len(s.l); i++ { - c := s.l[i] - if c.Value > sample.Value { - // Insert at position i. - s.l = append(s.l, Sample{}) - copy(s.l[i+1:], s.l[i:]) - s.l[i] = Sample{ - sample.Value, - sample.Width, - math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1), - // TODO(beorn7): How to calculate delta correctly? - } - i++ - goto inserted - } - r += c.Width - } - s.l = append(s.l, Sample{sample.Value, sample.Width, 0}) - i++ - inserted: - s.n += sample.Width - r += sample.Width - } - s.compress() -} - -func (s *stream) count() int { - return int(s.n) -} - -func (s *stream) query(q float64) float64 { - t := math.Ceil(q * s.n) - t += math.Ceil(s.ƒ(s, t) / 2) - p := s.l[0] - var r float64 - for _, c := range s.l[1:] { - r += p.Width - if r+c.Width+c.Delta > t { - return p.Value - } - p = c - } - return p.Value -} - -func (s *stream) compress() { - if len(s.l) < 2 { - return - } - x := s.l[len(s.l)-1] - xi := len(s.l) - 1 - r := s.n - 1 - x.Width - - for i := len(s.l) - 2; i >= 0; i-- { - c := s.l[i] - if c.Width+x.Width+x.Delta <= s.ƒ(s, r) { - x.Width += c.Width - s.l[xi] = x - // Remove element at i. - copy(s.l[i:], s.l[i+1:]) - s.l = s.l[:len(s.l)-1] - xi -= 1 - } else { - x = c - xi = i - } - r -= c.Width - } -} - -func (s *stream) samples() Samples { - samples := make(Samples, len(s.l)) - copy(samples, s.l) - return samples -} diff --git a/vendor/github.com/cenkalti/backoff/LICENSE b/vendor/github.com/cenkalti/backoff/LICENSE deleted file mode 100644 index 89b817996..000000000 --- a/vendor/github.com/cenkalti/backoff/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Cenk Altı - -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/cenkalti/backoff/backoff.go b/vendor/github.com/cenkalti/backoff/backoff.go deleted file mode 100644 index 3676ee405..000000000 --- a/vendor/github.com/cenkalti/backoff/backoff.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package backoff implements backoff algorithms for retrying operations. -// -// Use Retry function for retrying operations that may fail. -// If Retry does not meet your needs, -// copy/paste the function into your project and modify as you wish. -// -// There is also Ticker type similar to time.Ticker. -// You can use it if you need to work with channels. -// -// See Examples section below for usage examples. -package backoff - -import "time" - -// BackOff is a backoff policy for retrying an operation. -type BackOff interface { - // NextBackOff returns the duration to wait before retrying the operation, - // or backoff. Stop to indicate that no more retries should be made. - // - // Example usage: - // - // duration := backoff.NextBackOff(); - // if (duration == backoff.Stop) { - // // Do not retry operation. - // } else { - // // Sleep for duration and retry operation. - // } - // - NextBackOff() time.Duration - - // Reset to initial state. - Reset() -} - -// Stop indicates that no more retries should be made for use in NextBackOff(). -const Stop time.Duration = -1 - -// ZeroBackOff is a fixed backoff policy whose backoff time is always zero, -// meaning that the operation is retried immediately without waiting, indefinitely. -type ZeroBackOff struct{} - -func (b *ZeroBackOff) Reset() {} - -func (b *ZeroBackOff) NextBackOff() time.Duration { return 0 } - -// StopBackOff is a fixed backoff policy that always returns backoff.Stop for -// NextBackOff(), meaning that the operation should never be retried. -type StopBackOff struct{} - -func (b *StopBackOff) Reset() {} - -func (b *StopBackOff) NextBackOff() time.Duration { return Stop } - -// ConstantBackOff is a backoff policy that always returns the same backoff delay. -// This is in contrast to an exponential backoff policy, -// which returns a delay that grows longer as you call NextBackOff() over and over again. -type ConstantBackOff struct { - Interval time.Duration -} - -func (b *ConstantBackOff) Reset() {} -func (b *ConstantBackOff) NextBackOff() time.Duration { return b.Interval } - -func NewConstantBackOff(d time.Duration) *ConstantBackOff { - return &ConstantBackOff{Interval: d} -} diff --git a/vendor/github.com/cenkalti/backoff/context.go b/vendor/github.com/cenkalti/backoff/context.go deleted file mode 100644 index 7706faa2b..000000000 --- a/vendor/github.com/cenkalti/backoff/context.go +++ /dev/null @@ -1,63 +0,0 @@ -package backoff - -import ( - "context" - "time" -) - -// BackOffContext is a backoff policy that stops retrying after the context -// is canceled. -type BackOffContext interface { - BackOff - Context() context.Context -} - -type backOffContext struct { - BackOff - ctx context.Context -} - -// WithContext returns a BackOffContext with context ctx -// -// ctx must not be nil -func WithContext(b BackOff, ctx context.Context) BackOffContext { - if ctx == nil { - panic("nil context") - } - - if b, ok := b.(*backOffContext); ok { - return &backOffContext{ - BackOff: b.BackOff, - ctx: ctx, - } - } - - return &backOffContext{ - BackOff: b, - ctx: ctx, - } -} - -func ensureContext(b BackOff) BackOffContext { - if cb, ok := b.(BackOffContext); ok { - return cb - } - return WithContext(b, context.Background()) -} - -func (b *backOffContext) Context() context.Context { - return b.ctx -} - -func (b *backOffContext) NextBackOff() time.Duration { - select { - case <-b.ctx.Done(): - return Stop - default: - } - next := b.BackOff.NextBackOff() - if deadline, ok := b.ctx.Deadline(); ok && deadline.Sub(time.Now()) < next { - return Stop - } - return next -} diff --git a/vendor/github.com/cenkalti/backoff/exponential.go b/vendor/github.com/cenkalti/backoff/exponential.go deleted file mode 100644 index a031a6597..000000000 --- a/vendor/github.com/cenkalti/backoff/exponential.go +++ /dev/null @@ -1,153 +0,0 @@ -package backoff - -import ( - "math/rand" - "time" -) - -/* -ExponentialBackOff is a backoff implementation that increases the backoff -period for each retry attempt using a randomization function that grows exponentially. - -NextBackOff() is calculated using the following formula: - - randomized interval = - RetryInterval * (random value in range [1 - RandomizationFactor, 1 + RandomizationFactor]) - -In other words NextBackOff() will range between the randomization factor -percentage below and above the retry interval. - -For example, given the following parameters: - - RetryInterval = 2 - RandomizationFactor = 0.5 - Multiplier = 2 - -the actual backoff period used in the next retry attempt will range between 1 and 3 seconds, -multiplied by the exponential, that is, between 2 and 6 seconds. - -Note: MaxInterval caps the RetryInterval and not the randomized interval. - -If the time elapsed since an ExponentialBackOff instance is created goes past the -MaxElapsedTime, then the method NextBackOff() starts returning backoff.Stop. - -The elapsed time can be reset by calling Reset(). - -Example: Given the following default arguments, for 10 tries the sequence will be, -and assuming we go over the MaxElapsedTime on the 10th try: - - Request # RetryInterval (seconds) Randomized Interval (seconds) - - 1 0.5 [0.25, 0.75] - 2 0.75 [0.375, 1.125] - 3 1.125 [0.562, 1.687] - 4 1.687 [0.8435, 2.53] - 5 2.53 [1.265, 3.795] - 6 3.795 [1.897, 5.692] - 7 5.692 [2.846, 8.538] - 8 8.538 [4.269, 12.807] - 9 12.807 [6.403, 19.210] - 10 19.210 backoff.Stop - -Note: Implementation is not thread-safe. -*/ -type ExponentialBackOff struct { - InitialInterval time.Duration - RandomizationFactor float64 - Multiplier float64 - MaxInterval time.Duration - // After MaxElapsedTime the ExponentialBackOff stops. - // It never stops if MaxElapsedTime == 0. - MaxElapsedTime time.Duration - Clock Clock - - currentInterval time.Duration - startTime time.Time -} - -// Clock is an interface that returns current time for BackOff. -type Clock interface { - Now() time.Time -} - -// Default values for ExponentialBackOff. -const ( - DefaultInitialInterval = 500 * time.Millisecond - DefaultRandomizationFactor = 0.5 - DefaultMultiplier = 1.5 - DefaultMaxInterval = 60 * time.Second - DefaultMaxElapsedTime = 15 * time.Minute -) - -// NewExponentialBackOff creates an instance of ExponentialBackOff using default values. -func NewExponentialBackOff() *ExponentialBackOff { - b := &ExponentialBackOff{ - InitialInterval: DefaultInitialInterval, - RandomizationFactor: DefaultRandomizationFactor, - Multiplier: DefaultMultiplier, - MaxInterval: DefaultMaxInterval, - MaxElapsedTime: DefaultMaxElapsedTime, - Clock: SystemClock, - } - b.Reset() - return b -} - -type systemClock struct{} - -func (t systemClock) Now() time.Time { - return time.Now() -} - -// SystemClock implements Clock interface that uses time.Now(). -var SystemClock = systemClock{} - -// Reset the interval back to the initial retry interval and restarts the timer. -func (b *ExponentialBackOff) Reset() { - b.currentInterval = b.InitialInterval - b.startTime = b.Clock.Now() -} - -// NextBackOff calculates the next backoff interval using the formula: -// Randomized interval = RetryInterval +/- (RandomizationFactor * RetryInterval) -func (b *ExponentialBackOff) NextBackOff() time.Duration { - // Make sure we have not gone over the maximum elapsed time. - if b.MaxElapsedTime != 0 && b.GetElapsedTime() > b.MaxElapsedTime { - return Stop - } - defer b.incrementCurrentInterval() - return getRandomValueFromInterval(b.RandomizationFactor, rand.Float64(), b.currentInterval) -} - -// GetElapsedTime returns the elapsed time since an ExponentialBackOff instance -// is created and is reset when Reset() is called. -// -// The elapsed time is computed using time.Now().UnixNano(). It is -// safe to call even while the backoff policy is used by a running -// ticker. -func (b *ExponentialBackOff) GetElapsedTime() time.Duration { - return b.Clock.Now().Sub(b.startTime) -} - -// Increments the current interval by multiplying it with the multiplier. -func (b *ExponentialBackOff) incrementCurrentInterval() { - // Check for overflow, if overflow is detected set the current interval to the max interval. - if float64(b.currentInterval) >= float64(b.MaxInterval)/b.Multiplier { - b.currentInterval = b.MaxInterval - } else { - b.currentInterval = time.Duration(float64(b.currentInterval) * b.Multiplier) - } -} - -// Returns a random value from the following interval: -// [randomizationFactor * currentInterval, randomizationFactor * currentInterval]. -func getRandomValueFromInterval(randomizationFactor, random float64, currentInterval time.Duration) time.Duration { - var delta = randomizationFactor * float64(currentInterval) - var minInterval = float64(currentInterval) - delta - var maxInterval = float64(currentInterval) + delta - - // Get a random value from the range [minInterval, maxInterval]. - // The formula used below has a +1 because if the minInterval is 1 and the maxInterval is 3 then - // we want a 33% chance for selecting either 1, 2 or 3. - return time.Duration(minInterval + (random * (maxInterval - minInterval + 1))) -} diff --git a/vendor/github.com/cenkalti/backoff/retry.go b/vendor/github.com/cenkalti/backoff/retry.go deleted file mode 100644 index e936a506f..000000000 --- a/vendor/github.com/cenkalti/backoff/retry.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import "time" - -// An Operation is executing by Retry() or RetryNotify(). -// The operation will be retried using a backoff policy if it returns an error. -type Operation func() error - -// Notify is a notify-on-error function. It receives an operation error and -// backoff delay if the operation failed (with an error). -// -// NOTE that if the backoff policy stated to stop retrying, -// the notify function isn't called. -type Notify func(error, time.Duration) - -// Retry the operation o until it does not return error or BackOff stops. -// o is guaranteed to be run at least once. -// -// If o returns a *PermanentError, the operation is not retried, and the -// wrapped error is returned. -// -// Retry sleeps the goroutine for the duration returned by BackOff after a -// failed operation returns. -func Retry(o Operation, b BackOff) error { return RetryNotify(o, b, nil) } - -// RetryNotify calls notify function with the error and wait duration -// for each failed attempt before sleep. -func RetryNotify(operation Operation, b BackOff, notify Notify) error { - var err error - var next time.Duration - var t *time.Timer - - cb := ensureContext(b) - - b.Reset() - for { - if err = operation(); err == nil { - return nil - } - - if permanent, ok := err.(*PermanentError); ok { - return permanent.Err - } - - if next = cb.NextBackOff(); next == Stop { - return err - } - - if notify != nil { - notify(err, next) - } - - if t == nil { - t = time.NewTimer(next) - defer t.Stop() - } else { - t.Reset(next) - } - - select { - case <-cb.Context().Done(): - return err - case <-t.C: - } - } -} - -// PermanentError signals that the operation should not be retried. -type PermanentError struct { - Err error -} - -func (e *PermanentError) Error() string { - return e.Err.Error() -} - -// Permanent wraps the given err in a *PermanentError. -func Permanent(err error) *PermanentError { - return &PermanentError{ - Err: err, - } -} diff --git a/vendor/github.com/cenkalti/backoff/ticker.go b/vendor/github.com/cenkalti/backoff/ticker.go deleted file mode 100644 index e41084b0e..000000000 --- a/vendor/github.com/cenkalti/backoff/ticker.go +++ /dev/null @@ -1,82 +0,0 @@ -package backoff - -import ( - "sync" - "time" -) - -// Ticker holds a channel that delivers `ticks' of a clock at times reported by a BackOff. -// -// Ticks will continue to arrive when the previous operation is still running, -// so operations that take a while to fail could run in quick succession. -type Ticker struct { - C <-chan time.Time - c chan time.Time - b BackOffContext - stop chan struct{} - stopOnce sync.Once -} - -// NewTicker returns a new Ticker containing a channel that will send -// the time at times specified by the BackOff argument. Ticker is -// guaranteed to tick at least once. The channel is closed when Stop -// method is called or BackOff stops. It is not safe to manipulate the -// provided backoff policy (notably calling NextBackOff or Reset) -// while the ticker is running. -func NewTicker(b BackOff) *Ticker { - c := make(chan time.Time) - t := &Ticker{ - C: c, - c: c, - b: ensureContext(b), - stop: make(chan struct{}), - } - t.b.Reset() - go t.run() - return t -} - -// Stop turns off a ticker. After Stop, no more ticks will be sent. -func (t *Ticker) Stop() { - t.stopOnce.Do(func() { close(t.stop) }) -} - -func (t *Ticker) run() { - c := t.c - defer close(c) - - // Ticker is guaranteed to tick at least once. - afterC := t.send(time.Now()) - - for { - if afterC == nil { - return - } - - select { - case tick := <-afterC: - afterC = t.send(tick) - case <-t.stop: - t.c = nil // Prevent future ticks from being sent to the channel. - return - case <-t.b.Context().Done(): - return - } - } -} - -func (t *Ticker) send(tick time.Time) <-chan time.Time { - select { - case t.c <- tick: - case <-t.stop: - return nil - } - - next := t.b.NextBackOff() - if next == Stop { - t.Stop() - return nil - } - - return time.After(next) -} diff --git a/vendor/github.com/cenkalti/backoff/tries.go b/vendor/github.com/cenkalti/backoff/tries.go deleted file mode 100644 index cfeefd9b7..000000000 --- a/vendor/github.com/cenkalti/backoff/tries.go +++ /dev/null @@ -1,35 +0,0 @@ -package backoff - -import "time" - -/* -WithMaxRetries creates a wrapper around another BackOff, which will -return Stop if NextBackOff() has been called too many times since -the last time Reset() was called - -Note: Implementation is not thread-safe. -*/ -func WithMaxRetries(b BackOff, max uint64) BackOff { - return &backOffTries{delegate: b, maxTries: max} -} - -type backOffTries struct { - delegate BackOff - maxTries uint64 - numTries uint64 -} - -func (b *backOffTries) NextBackOff() time.Duration { - if b.maxTries > 0 { - if b.maxTries <= b.numTries { - return Stop - } - b.numTries++ - } - return b.delegate.NextBackOff() -} - -func (b *backOffTries) Reset() { - b.numTries = 0 - b.delegate.Reset() -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/LICENSE b/vendor/github.com/cloudflare/cloudflare-go/LICENSE deleted file mode 100644 index c035bb48d..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/LICENSE +++ /dev/null @@ -1,26 +0,0 @@ -Copyright (c) 2015-2016, Cloudflare. All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this -list of conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation and/or -other materials provided with the distribution. - -3. Neither the name of the copyright holder nor the names of its contributors -may be used to endorse or promote products derived from this software without -specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go b/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go deleted file mode 100644 index 818cdf8ae..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/cloudflare.go +++ /dev/null @@ -1,318 +0,0 @@ -// Package cloudflare implements the Cloudflare v4 API. -package cloudflare - -import ( - "bytes" - "context" - "encoding/json" - "io" - "io/ioutil" - "log" - "math" - "net/http" - "strings" - "time" - - "github.com/pkg/errors" - "golang.org/x/time/rate" -) - -const apiURL = "https://api.cloudflare.com/client/v4" -const ( - // AuthKeyEmail specifies that we should authenticate with API key and email address - AuthKeyEmail = 1 << iota - // AuthUserService specifies that we should authenticate with a User-Service key - AuthUserService -) - -// API holds the configuration for the current API client. A client should not -// be modified concurrently. -type API struct { - APIKey string - APIEmail string - APIUserServiceKey string - BaseURL string - organizationID string - headers http.Header - httpClient *http.Client - authType int - rateLimiter *rate.Limiter - retryPolicy RetryPolicy - logger Logger -} - -// New creates a new Cloudflare v4 API client. -func New(key, email string, opts ...Option) (*API, error) { - if key == "" || email == "" { - return nil, errors.New(errEmptyCredentials) - } - - silentLogger := log.New(ioutil.Discard, "", log.LstdFlags) - - api := &API{ - APIKey: key, - APIEmail: email, - BaseURL: apiURL, - headers: make(http.Header), - authType: AuthKeyEmail, - rateLimiter: rate.NewLimiter(rate.Limit(4), 1), // 4rps equates to default api limit (1200 req/5 min) - retryPolicy: RetryPolicy{ - MaxRetries: 3, - MinRetryDelay: time.Duration(1) * time.Second, - MaxRetryDelay: time.Duration(30) * time.Second, - }, - logger: silentLogger, - } - - err := api.parseOptions(opts...) - if err != nil { - return nil, errors.Wrap(err, "options parsing failed") - } - - // Fall back to http.DefaultClient if the package user does not provide - // their own. - if api.httpClient == nil { - api.httpClient = http.DefaultClient - } - - return api, nil -} - -// SetAuthType sets the authentication method (AuthyKeyEmail or AuthUserService). -func (api *API) SetAuthType(authType int) { - api.authType = authType -} - -// ZoneIDByName retrieves a zone's ID from the name. -func (api *API) ZoneIDByName(zoneName string) (string, error) { - res, err := api.ListZones(zoneName) - if err != nil { - return "", errors.Wrap(err, "ListZones command failed") - } - for _, zone := range res { - if zone.Name == zoneName { - return zone.ID, nil - } - } - return "", errors.New("Zone could not be found") -} - -// makeRequest makes a HTTP request and returns the body as a byte slice, -// closing it before returnng. params will be serialized to JSON. -func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) { - return api.makeRequestWithAuthType(method, uri, params, api.authType) -} - -func (api *API) makeRequestWithAuthType(method, uri string, params interface{}, authType int) ([]byte, error) { - // Replace nil with a JSON object if needed - var jsonBody []byte - var err error - if params != nil { - jsonBody, err = json.Marshal(params) - if err != nil { - return nil, errors.Wrap(err, "error marshalling params to JSON") - } - } else { - jsonBody = nil - } - - var resp *http.Response - var respErr error - var reqBody io.Reader - var respBody []byte - for i := 0; i <= api.retryPolicy.MaxRetries; i++ { - if jsonBody != nil { - reqBody = bytes.NewReader(jsonBody) - } - - if i > 0 { - // expect the backoff introduced here on errored requests to dominate the effect of rate limiting - // dont need a random component here as the rate limiter should do something similar - // nb time duration could truncate an arbitrary float. Since our inputs are all ints, we should be ok - sleepDuration := time.Duration(math.Pow(2, float64(i-1)) * float64(api.retryPolicy.MinRetryDelay)) - - if sleepDuration > api.retryPolicy.MaxRetryDelay { - sleepDuration = api.retryPolicy.MaxRetryDelay - } - // useful to do some simple logging here, maybe introduce levels later - api.logger.Printf("Sleeping %s before retry attempt number %d for request %s %s", sleepDuration.String(), i, method, uri) - time.Sleep(sleepDuration) - } - api.rateLimiter.Wait(context.TODO()) - if err != nil { - return nil, errors.Wrap(err, "Error caused by request rate limiting") - } - resp, respErr = api.request(method, uri, reqBody, authType) - - // retry if the server is rate limiting us or if it failed - // assumes server operations are rolled back on failure - if respErr != nil || resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500 { - // if we got a valid http response, try to read body so we can reuse the connection - // see https://golang.org/pkg/net/http/#Client.Do - if respErr == nil { - respBody, err = ioutil.ReadAll(resp.Body) - resp.Body.Close() - - respErr = errors.Wrap(err, "could not read response body") - - api.logger.Printf("Request: %s %s got an error response %d: %s\n", method, uri, resp.StatusCode, - strings.Replace(strings.Replace(string(respBody), "\n", "", -1), "\t", "", -1)) - } else { - api.logger.Printf("Error performing request: %s %s : %s \n", method, uri, respErr.Error()) - } - continue - } else { - respBody, err = ioutil.ReadAll(resp.Body) - defer resp.Body.Close() - if err != nil { - return nil, errors.Wrap(err, "could not read response body") - } - break - } - } - if respErr != nil { - return nil, respErr - } - - switch { - case resp.StatusCode >= http.StatusOK && resp.StatusCode < http.StatusMultipleChoices: - case resp.StatusCode == http.StatusUnauthorized: - return nil, errors.Errorf("HTTP status %d: invalid credentials", resp.StatusCode) - case resp.StatusCode == http.StatusForbidden: - return nil, errors.Errorf("HTTP status %d: insufficient permissions", resp.StatusCode) - case resp.StatusCode == http.StatusServiceUnavailable, - resp.StatusCode == http.StatusBadGateway, - resp.StatusCode == http.StatusGatewayTimeout, - resp.StatusCode == 522, - resp.StatusCode == 523, - resp.StatusCode == 524: - return nil, errors.Errorf("HTTP status %d: service failure", resp.StatusCode) - default: - var s string - if respBody != nil { - s = string(respBody) - } - return nil, errors.Errorf("HTTP status %d: content %q", resp.StatusCode, s) - } - - return respBody, nil -} - -// request makes a HTTP request to the given API endpoint, returning the raw -// *http.Response, or an error if one occurred. The caller is responsible for -// closing the response body. -func (api *API) request(method, uri string, reqBody io.Reader, authType int) (*http.Response, error) { - req, err := http.NewRequest(method, api.BaseURL+uri, reqBody) - if err != nil { - return nil, errors.Wrap(err, "HTTP request creation failed") - } - - // Apply any user-defined headers first. - req.Header = cloneHeader(api.headers) - if authType&AuthKeyEmail != 0 { - req.Header.Set("X-Auth-Key", api.APIKey) - req.Header.Set("X-Auth-Email", api.APIEmail) - } - if authType&AuthUserService != 0 { - req.Header.Set("X-Auth-User-Service-Key", api.APIUserServiceKey) - } - - if req.Header.Get("Content-Type") == "" { - req.Header.Set("Content-Type", "application/json") - } - - resp, err := api.httpClient.Do(req) - if err != nil { - return nil, errors.Wrap(err, "HTTP request failed") - } - - return resp, nil -} - -// Returns the base URL to use for API endpoints that exist for both accounts and organizations. -// If an Organization option was used when creating the API instance, returns the org URL. -// -// accountBase is the base URL for endpoints referring to the current user. It exists as a -// parameter because it is not consistent across APIs. -func (api *API) userBaseURL(accountBase string) string { - if api.organizationID != "" { - return "/organizations/" + api.organizationID - } - return accountBase -} - -// cloneHeader returns a shallow copy of the header. -// copied from https://godoc.org/github.com/golang/gddo/httputil/header#Copy -func cloneHeader(header http.Header) http.Header { - h := make(http.Header) - for k, vs := range header { - h[k] = vs - } - return h -} - -// ResponseInfo contains a code and message returned by the API as errors or -// informational messages inside the response. -type ResponseInfo struct { - Code int `json:"code"` - Message string `json:"message"` -} - -// Response is a template. There will also be a result struct. There will be a -// unique response type for each response, which will include this type. -type Response struct { - Success bool `json:"success"` - Errors []ResponseInfo `json:"errors"` - Messages []ResponseInfo `json:"messages"` -} - -// ResultInfo contains metadata about the Response. -type ResultInfo struct { - Page int `json:"page"` - PerPage int `json:"per_page"` - TotalPages int `json:"total_pages"` - Count int `json:"count"` - Total int `json:"total_count"` -} - -// RawResponse keeps the result as JSON form -type RawResponse struct { - Response - Result json.RawMessage `json:"result"` -} - -// Raw makes a HTTP request with user provided params and returns the -// result as untouched JSON. -func (api *API) Raw(method, endpoint string, data interface{}) (json.RawMessage, error) { - res, err := api.makeRequest(method, endpoint, data) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var r RawResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PaginationOptions can be passed to a list request to configure paging -// These values will be defaulted if omitted, and PerPage has min/max limits set by resource -type PaginationOptions struct { - Page int `json:"page,omitempty"` - PerPage int `json:"per_page,omitempty"` -} - -// RetryPolicy specifies number of retries and min/max retry delays -// This config is used when the client exponentially backs off after errored requests -type RetryPolicy struct { - MaxRetries int - MinRetryDelay time.Duration - MaxRetryDelay time.Duration -} - -// Logger defines the interface this library needs to use logging -// This is a subset of the methods implemented in the log package -type Logger interface { - Printf(format string, v ...interface{}) -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/cpage.go b/vendor/github.com/cloudflare/cloudflare-go/cpage.go deleted file mode 100644 index 87e50ce84..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/cpage.go +++ /dev/null @@ -1,29 +0,0 @@ -package cloudflare - -import "time" - -// CustomPage represents a custom page configuration. -type CustomPage struct { - CreatedOn string `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - URL string `json:"url"` - State string `json:"state"` - RequiredTokens []string `json:"required_tokens"` - PreviewTarget string `json:"preview_target"` - Description string `json:"description"` -} - -// CustomPageResponse represents the response from the custom pages endpoint. -type CustomPageResponse struct { - Response - Result []CustomPage `json:"result"` -} - -// https://api.cloudflare.com/#custom-pages-for-a-zone-available-custom-pages -// GET /zones/:zone_identifier/custom_pages - -// https://api.cloudflare.com/#custom-pages-for-a-zone-custom-page-details -// GET /zones/:zone_identifier/custom_pages/:identifier - -// https://api.cloudflare.com/#custom-pages-for-a-zone-update-custom-page-url -// PUT /zones/:zone_identifier/custom_pages/:identifier diff --git a/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go b/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go deleted file mode 100644 index 44dbc4068..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/custom_hostname.go +++ /dev/null @@ -1,149 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// CustomHostnameSSL represents the SSL section in a given custom hostname. -type CustomHostnameSSL struct { - Status string `json:"status,omitempty"` - Method string `json:"method,omitempty"` - Type string `json:"type,omitempty"` - CnameTarget string `json:"cname_target,omitempty"` - CnameName string `json:"cname_name,omitempty"` -} - -// CustomMetadata defines custom metadata for the hostname. This requires logic to be implemented by Cloudflare to act on the data provided. -type CustomMetadata map[string]interface{} - -// CustomHostname represents a custom hostname in a zone. -type CustomHostname struct { - ID string `json:"id,omitempty"` - Hostname string `json:"hostname,omitempty"` - SSL CustomHostnameSSL `json:"ssl,omitempty"` - CustomMetadata CustomMetadata `json:"custom_metadata,omitempty"` -} - -// CustomHostNameResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameResponse struct { - Result CustomHostname `json:"result"` - Response -} - -// CustomHostnameListResponse represents a response from the Custom Hostnames endpoints. -type CustomHostnameListResponse struct { - Result []CustomHostname `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// Modify SSL configuration for the given custom hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-update-custom-hostname-configuration -func (api *API) UpdateCustomHostnameSSL(zoneID string, customHostnameID string, ssl CustomHostnameSSL) (CustomHostname, error) { - return CustomHostname{}, errors.New("Not implemented") -} - -// Delete a custom hostname (and any issued SSL certificates) -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-delete-a-custom-hostname-and-any-issued-ssl-certificates- -func (api *API) DeleteCustomHostname(zoneID string, customHostnameID string) error { - uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// CreateCustomHostname creates a new custom hostname and requests that an SSL certificate be issued for it. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-create-custom-hostname -func (api *API) CreateCustomHostname(zoneID string, ch CustomHostname) (*CustomHostnameResponse, error) { - uri := "/zones/" + zoneID + "/custom_hostnames" - res, err := api.makeRequest("POST", uri, ch) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var response *CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// CustomHostnames fetches custom hostnames for the given zone, -// by applying filter.Hostname if not empty and scoping the result to page'th 50 items. -// -// The returned ResultInfo can be used to implement pagination. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-list-custom-hostnames -func (api *API) CustomHostnames(zoneID string, page int, filter CustomHostname) ([]CustomHostname, ResultInfo, error) { - v := url.Values{} - v.Set("per_page", "50") - v.Set("page", strconv.Itoa(page)) - if filter.Hostname != "" { - v.Set("hostname", filter.Hostname) - } - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/custom_hostnames" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []CustomHostname{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - var customHostnameListResponse CustomHostnameListResponse - err = json.Unmarshal(res, &customHostnameListResponse) - if err != nil { - return []CustomHostname{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - return customHostnameListResponse.Result, customHostnameListResponse.ResultInfo, nil -} - -// CustomHostname inspects the given custom hostname in the given zone. -// -// API reference: https://api.cloudflare.com/#custom-hostname-for-a-zone-custom-hostname-configuration-details -func (api *API) CustomHostname(zoneID string, customHostnameID string) (CustomHostname, error) { - uri := "/zones/" + zoneID + "/custom_hostnames/" + customHostnameID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return CustomHostname{}, errors.Wrap(err, errMakeRequestError) - } - - var response CustomHostnameResponse - err = json.Unmarshal(res, &response) - if err != nil { - return CustomHostname{}, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// CustomHostnameIDByName retrieves the ID for the given hostname in the given zone. -func (api *API) CustomHostnameIDByName(zoneID string, hostname string) (string, error) { - customHostnames, _, err := api.CustomHostnames(zoneID, 1, CustomHostname{Hostname: hostname}) - if err != nil { - return "", errors.Wrap(err, "CustomHostnames command failed") - } - for _, ch := range customHostnames { - if ch.Hostname == hostname { - return ch.ID, nil - } - } - return "", errors.New("CustomHostname could not be found") -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/dns.go b/vendor/github.com/cloudflare/cloudflare-go/dns.go deleted file mode 100644 index 3303e9d02..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/dns.go +++ /dev/null @@ -1,174 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// DNSRecord represents a DNS record in a zone. -type DNSRecord struct { - ID string `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Content string `json:"content,omitempty"` - Proxiable bool `json:"proxiable,omitempty"` - Proxied bool `json:"proxied,omitempty"` - TTL int `json:"ttl,omitempty"` - Locked bool `json:"locked,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - ZoneName string `json:"zone_name,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` - Data interface{} `json:"data,omitempty"` // data returned by: SRV, LOC - Meta interface{} `json:"meta,omitempty"` - Priority int `json:"priority,omitempty"` -} - -// DNSRecordResponse represents the response from the DNS endpoint. -type DNSRecordResponse struct { - Result DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// DNSListResponse represents the response from the list DNS records endpoint. -type DNSListResponse struct { - Result []DNSRecord `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateDNSRecord creates a DNS record for the zone identifier. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-create-dns-record -func (api *API) CreateDNSRecord(zoneID string, rr DNSRecord) (*DNSRecordResponse, error) { - uri := "/zones/" + zoneID + "/dns_records" - res, err := api.makeRequest("POST", uri, rr) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var recordResp *DNSRecordResponse - err = json.Unmarshal(res, &recordResp) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return recordResp, nil -} - -// DNSRecords returns a slice of DNS records for the given zone identifier. -// -// This takes a DNSRecord to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-list-dns-records -func (api *API) DNSRecords(zoneID string, rr DNSRecord) ([]DNSRecord, error) { - // Construct a query string - v := url.Values{} - // Request as many records as possible per page - API max is 50 - v.Set("per_page", "50") - if rr.Name != "" { - v.Set("name", rr.Name) - } - if rr.Type != "" { - v.Set("type", rr.Type) - } - if rr.Content != "" { - v.Set("content", rr.Content) - } - - var query string - var records []DNSRecord - page := 1 - - // Loop over makeRequest until what we've fetched all records - for { - v.Set("page", strconv.Itoa(page)) - query = "?" + v.Encode() - uri := "/zones/" + zoneID + "/dns_records" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []DNSRecord{}, errors.Wrap(err, errMakeRequestError) - } - var r DNSListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - records = append(records, r.Result...) - if r.ResultInfo.Page >= r.ResultInfo.TotalPages { - break - } - // Loop around and fetch the next page - page++ - } - return records, nil -} - -// DNSRecord returns a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-dns-record-details -func (api *API) DNSRecord(zoneID, recordID string) (DNSRecord, error) { - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return DNSRecord{}, errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return DNSRecord{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateDNSRecord updates a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-update-dns-record -func (api *API) UpdateDNSRecord(zoneID, recordID string, rr DNSRecord) error { - rec, err := api.DNSRecord(zoneID, recordID) - if err != nil { - return err - } - // Populate the record name from the existing one if the update didn't - // specify it. - if rr.Name == "" { - rr.Name = rec.Name - } - rr.Type = rec.Type - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("PUT", uri, rr) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeleteDNSRecord deletes a single DNS record for the given zone & record -// identifiers. -// -// API reference: https://api.cloudflare.com/#dns-records-for-a-zone-delete-dns-record -func (api *API) DeleteDNSRecord(zoneID, recordID string) error { - uri := "/zones/" + zoneID + "/dns_records/" + recordID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r DNSRecordResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/errors.go b/vendor/github.com/cloudflare/cloudflare-go/errors.go deleted file mode 100644 index 2fff3db30..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/errors.go +++ /dev/null @@ -1,48 +0,0 @@ -package cloudflare - -// Error messages -const ( - errEmptyCredentials = "invalid credentials: key & email must not be empty" - errMakeRequestError = "error from makeRequest" - errUnmarshalError = "error unmarshalling the JSON response" - errRequestNotSuccessful = "error reported by API" -) - -var _ Error = &UserError{} - -// Error represents an error returned from this library. -type Error interface { - error - // Raised when user credentials or configuration is invalid. - User() bool - // Raised when a parsing error (e.g. JSON) occurs. - Parse() bool - // Raised when a network error occurs. - Network() bool - // Contains the most recent error. -} - -// UserError represents a user-generated error. -type UserError struct { - Err error -} - -// User is a user-caused error. -func (e *UserError) User() bool { - return true -} - -// Network error. -func (e *UserError) Network() bool { - return false -} - -// Parse error. -func (e *UserError) Parse() bool { - return true -} - -// Error wraps the underlying error. -func (e *UserError) Error() string { - return e.Err.Error() -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/firewall.go b/vendor/github.com/cloudflare/cloudflare-go/firewall.go deleted file mode 100644 index 9246b7e65..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/firewall.go +++ /dev/null @@ -1,241 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - "time" - - "github.com/pkg/errors" -) - -// AccessRule represents a firewall access rule. -type AccessRule struct { - ID string `json:"id,omitempty"` - Notes string `json:"notes,omitempty"` - AllowedModes []string `json:"allowed_modes,omitempty"` - Mode string `json:"mode,omitempty"` - Configuration AccessRuleConfiguration `json:"configuration,omitempty"` - Scope AccessRuleScope `json:"scope,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` - ModifiedOn time.Time `json:"modified_on,omitempty"` -} - -// AccessRuleConfiguration represents the configuration of a firewall -// access rule. -type AccessRuleConfiguration struct { - Target string `json:"target,omitempty"` - Value string `json:"value,omitempty"` -} - -// AccessRuleScope represents the scope of a firewall access rule. -type AccessRuleScope struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` -} - -// AccessRuleResponse represents the response from the firewall access -// rule endpoint. -type AccessRuleResponse struct { - Result AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// AccessRuleListResponse represents the response from the list access rules -// endpoint. -type AccessRuleListResponse struct { - Result []AccessRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ListUserAccessRules returns a slice of access rules for the logged-in user. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules -func (api *API) ListUserAccessRules(accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/user", accessRule, page) -} - -// CreateUserAccessRule creates a firewall access rule for the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-create-access-rule -func (api *API) CreateUserAccessRule(accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/user", accessRule) -} - -// UpdateUserAccessRule updates a single access rule for the logged-in user & -// given access rule identifier. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) UpdateUserAccessRule(accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/user", accessRuleID, accessRule) -} - -// DeleteUserAccessRule deletes a single access rule for the logged-in user and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#user-level-firewall-access-rule-update-access-rule -func (api *API) DeleteUserAccessRule(accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/user", accessRuleID) -} - -// ListZoneAccessRules returns a slice of access rules for the given zone -// identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-list-access-rules -func (api *API) ListZoneAccessRules(zoneID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/zones/"+zoneID, accessRule, page) -} - -// CreateZoneAccessRule creates a firewall access rule for the given zone -// identifier. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-create-access-rule -func (api *API) CreateZoneAccessRule(zoneID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/zones/"+zoneID, accessRule) -} - -// UpdateZoneAccessRule updates a single access rule for the given zone & -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-update-access-rule -func (api *API) UpdateZoneAccessRule(zoneID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/zones/"+zoneID, accessRuleID, accessRule) -} - -// DeleteZoneAccessRule deletes a single access rule for the given zone and -// access rule identifiers. -// -// API reference: https://api.cloudflare.com/#firewall-access-rule-for-a-zone-delete-access-rule -func (api *API) DeleteZoneAccessRule(zoneID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/zones/"+zoneID, accessRuleID) -} - -// ListOrganizationAccessRules returns a slice of access rules for the given -// organization identifier. -// -// This takes an AccessRule to allow filtering of the results returned. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-list-access-rules -func (api *API) ListOrganizationAccessRules(organizationID string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - return api.listAccessRules("/organizations/"+organizationID, accessRule, page) -} - -// CreateOrganizationAccessRule creates a firewall access rule for the given -// organization identifier. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-create-access-rule -func (api *API) CreateOrganizationAccessRule(organizationID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.createAccessRule("/organizations/"+organizationID, accessRule) -} - -// UpdateOrganizationAccessRule updates a single access rule for the given -// organization & access rule identifiers. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-update-access-rule -func (api *API) UpdateOrganizationAccessRule(organizationID, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - return api.updateAccessRule("/organizations/"+organizationID, accessRuleID, accessRule) -} - -// DeleteOrganizationAccessRule deletes a single access rule for the given -// organization and access rule identifiers. -// -// API reference: https://api.cloudflare.com/#organization-level-firewall-access-rule-delete-access-rule -func (api *API) DeleteOrganizationAccessRule(organizationID, accessRuleID string) (*AccessRuleResponse, error) { - return api.deleteAccessRule("/organizations/"+organizationID, accessRuleID) -} - -func (api *API) listAccessRules(prefix string, accessRule AccessRule, page int) (*AccessRuleListResponse, error) { - // Construct a query string - v := url.Values{} - if page <= 0 { - page = 1 - } - v.Set("page", strconv.Itoa(page)) - // Request as many rules as possible per page - API max is 100 - v.Set("per_page", "100") - if accessRule.Notes != "" { - v.Set("notes", accessRule.Notes) - } - if accessRule.Mode != "" { - v.Set("mode", accessRule.Mode) - } - if accessRule.Scope.Type != "" { - v.Set("scope_type", accessRule.Scope.Type) - } - if accessRule.Configuration.Value != "" { - v.Set("configuration_value", accessRule.Configuration.Value) - } - if accessRule.Configuration.Target != "" { - v.Set("configuration_target", accessRule.Configuration.Target) - } - v.Set("page", strconv.Itoa(page)) - query := "?" + v.Encode() - - uri := prefix + "/firewall/access_rules/rules" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) createAccessRule(prefix string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules" - res, err := api.makeRequest("POST", uri, accessRule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -func (api *API) updateAccessRule(prefix, accessRuleID string, accessRule AccessRule) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("PATCH", uri, accessRule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return response, nil -} - -func (api *API) deleteAccessRule(prefix, accessRuleID string) (*AccessRuleResponse, error) { - uri := prefix + "/firewall/access_rules/rules/" + accessRuleID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &AccessRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ips.go b/vendor/github.com/cloudflare/cloudflare-go/ips.go deleted file mode 100644 index 72b5fcfbc..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ips.go +++ /dev/null @@ -1,44 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "io/ioutil" - "net/http" - - "github.com/pkg/errors" -) - -// IPRanges contains lists of IPv4 and IPv6 CIDRs. -type IPRanges struct { - IPv4CIDRs []string `json:"ipv4_cidrs"` - IPv6CIDRs []string `json:"ipv6_cidrs"` -} - -// IPsResponse is the API response containing a list of IPs. -type IPsResponse struct { - Response - Result IPRanges `json:"result"` -} - -// IPs gets a list of Cloudflare's IP ranges. -// -// This does not require logging in to the API. -// -// API reference: https://api.cloudflare.com/#cloudflare-ips -func IPs() (IPRanges, error) { - resp, err := http.Get(apiURL + "/ips") - if err != nil { - return IPRanges{}, errors.Wrap(err, "HTTP request failed") - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return IPRanges{}, errors.Wrap(err, "Response body could not be read") - } - var r IPsResponse - err = json.Unmarshal(body, &r) - if err != nil { - return IPRanges{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/keyless.go b/vendor/github.com/cloudflare/cloudflare-go/keyless.go deleted file mode 100644 index c5cc83914..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/keyless.go +++ /dev/null @@ -1,52 +0,0 @@ -package cloudflare - -import "time" - -// KeylessSSL represents Keyless SSL configuration. -type KeylessSSL struct { - ID string `json:"id"` - Name string `json:"name"` - Host string `json:"host"` - Port int `json:"port"` - Status string `json:"success"` - Enabled bool `json:"enabled"` - Permissions []string `json:"permissions"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modifed_on"` -} - -// KeylessSSLResponse represents the response from the Keyless SSL endpoint. -type KeylessSSLResponse struct { - Response - Result []KeylessSSL `json:"result"` -} - -// CreateKeyless creates a new Keyless SSL configuration for the zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-create-a-keyless-ssl-configuration -func (api *API) CreateKeyless() { -} - -// ListKeyless lists Keyless SSL configurations for a zone. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-list-keyless-ssls -func (api *API) ListKeyless() { -} - -// Keyless provides the configuration for a given Keyless SSL identifier. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-keyless-ssl-details -func (api *API) Keyless() { -} - -// UpdateKeyless updates an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-update-keyless-configuration -func (api *API) UpdateKeyless() { -} - -// DeleteKeyless deletes an existing Keyless SSL configuration. -// -// API reference: https://api.cloudflare.com/#keyless-ssl-for-a-zone-delete-keyless-configuration -func (api *API) DeleteKeyless() { -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go b/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go deleted file mode 100644 index e1af07b57..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/load_balancing.go +++ /dev/null @@ -1,330 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// LoadBalancerPool represents a load balancer pool's properties. -type LoadBalancerPool struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - MinimumOrigins int `json:"minimum_origins,omitempty"` - Monitor string `json:"monitor,omitempty"` - Origins []LoadBalancerOrigin `json:"origins"` - NotificationEmail string `json:"notification_email,omitempty"` - - // CheckRegions defines the geographic region(s) from where to run health-checks from - e.g. "WNAM", "WEU", "SAF", "SAM". - // Providing a null/empty value means "all regions", which may not be available to all plan types. - CheckRegions []string `json:"check_regions"` -} - -type LoadBalancerOrigin struct { - Name string `json:"name"` - Address string `json:"address"` - Enabled bool `json:"enabled"` - Weight float64 `json:"weight"` -} - -// LoadBalancerMonitor represents a load balancer monitor's properties. -type LoadBalancerMonitor struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Type string `json:"type"` - Description string `json:"description"` - Method string `json:"method"` - Path string `json:"path"` - Header map[string][]string `json:"header"` - Timeout int `json:"timeout"` - Retries int `json:"retries"` - Interval int `json:"interval"` - ExpectedBody string `json:"expected_body"` - ExpectedCodes string `json:"expected_codes"` -} - -// LoadBalancer represents a load balancer's properties. -type LoadBalancer struct { - ID string `json:"id,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - Description string `json:"description"` - Name string `json:"name"` - TTL int `json:"ttl,omitempty"` - FallbackPool string `json:"fallback_pool"` - DefaultPools []string `json:"default_pools"` - RegionPools map[string][]string `json:"region_pools"` - PopPools map[string][]string `json:"pop_pools"` - Proxied bool `json:"proxied"` - Persistence string `json:"session_affinity,omitempty"` -} - -// loadBalancerPoolResponse represents the response from the load balancer pool endpoints. -type loadBalancerPoolResponse struct { - Response - Result LoadBalancerPool `json:"result"` -} - -// loadBalancerPoolListResponse represents the response from the List Pools endpoint. -type loadBalancerPoolListResponse struct { - Response - Result []LoadBalancerPool `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerMonitorResponse represents the response from the load balancer monitor endpoints. -type loadBalancerMonitorResponse struct { - Response - Result LoadBalancerMonitor `json:"result"` -} - -// loadBalancerMonitorListResponse represents the response from the List Monitors endpoint. -type loadBalancerMonitorListResponse struct { - Response - Result []LoadBalancerMonitor `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// loadBalancerResponse represents the response from the load balancer endpoints. -type loadBalancerResponse struct { - Response - Result LoadBalancer `json:"result"` -} - -// loadBalancerListResponse represents the response from the List Load Balancers endpoint. -type loadBalancerListResponse struct { - Response - Result []LoadBalancer `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// CreateLoadBalancerPool creates a new load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-create-a-pool -func (api *API) CreateLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("POST", uri, pool) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerPools lists load balancer pools connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-list-pools -func (api *API) ListLoadBalancerPools() ([]LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerPoolDetails returns the details for a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-pool-details -func (api *API) LoadBalancerPoolDetails(poolID string) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerPool disables and deletes a load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-delete-a-pool -func (api *API) DeleteLoadBalancerPool(poolID string) error { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + poolID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancerPool modifies a configured load balancer pool. -// -// API reference: https://api.cloudflare.com/#load-balancer-pools-modify-a-pool -func (api *API) ModifyLoadBalancerPool(pool LoadBalancerPool) (LoadBalancerPool, error) { - uri := api.userBaseURL("/user") + "/load_balancers/pools/" + pool.ID - res, err := api.makeRequest("PUT", uri, pool) - if err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerPoolResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerPool{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancerMonitor creates a new load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-create-a-monitor -func (api *API) CreateLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("POST", uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancerMonitors lists load balancer monitors connected to an account. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-list-monitors -func (api *API) ListLoadBalancerMonitors() ([]LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerMonitorDetails returns the details for a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-monitor-details -func (api *API) LoadBalancerMonitorDetails(monitorID string) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancerMonitor disables and deletes a load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-delete-a-monitor -func (api *API) DeleteLoadBalancerMonitor(monitorID string) error { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitorID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancerMonitor modifies a configured load balancer monitor. -// -// API reference: https://api.cloudflare.com/#load-balancer-monitors-modify-a-monitor -func (api *API) ModifyLoadBalancerMonitor(monitor LoadBalancerMonitor) (LoadBalancerMonitor, error) { - uri := api.userBaseURL("/user") + "/load_balancers/monitors/" + monitor.ID - res, err := api.makeRequest("PUT", uri, monitor) - if err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerMonitorResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancerMonitor{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// CreateLoadBalancer creates a new load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-create-a-load-balancer -func (api *API) CreateLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("POST", uri, lb) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListLoadBalancers lists load balancers configured on a zone. -// -// API reference: https://api.cloudflare.com/#load-balancers-list-load-balancers -func (api *API) ListLoadBalancers(zoneID string) ([]LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerListResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// LoadBalancerDetails returns the details for a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-load-balancer-details -func (api *API) LoadBalancerDetails(zoneID, lbID string) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers/" + lbID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteLoadBalancer disables and deletes a load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-delete-a-load-balancer -func (api *API) DeleteLoadBalancer(zoneID, lbID string) error { - uri := "/zones/" + zoneID + "/load_balancers/" + lbID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ModifyLoadBalancer modifies a configured load balancer. -// -// API reference: https://api.cloudflare.com/#load-balancers-modify-a-load-balancer -func (api *API) ModifyLoadBalancer(zoneID string, lb LoadBalancer) (LoadBalancer, error) { - uri := "/zones/" + zoneID + "/load_balancers/" + lb.ID - res, err := api.makeRequest("PUT", uri, lb) - if err != nil { - return LoadBalancer{}, errors.Wrap(err, errMakeRequestError) - } - var r loadBalancerResponse - if err := json.Unmarshal(res, &r); err != nil { - return LoadBalancer{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/lockdown.go b/vendor/github.com/cloudflare/cloudflare-go/lockdown.go deleted file mode 100644 index 3dba81c21..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/lockdown.go +++ /dev/null @@ -1,150 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// ZoneLockdown represents a Zone Lockdown rule. A rule only permits access to -// the provided URL pattern(s) from the given IP address(es) or subnet(s). -type ZoneLockdown struct { - ID string `json:"id"` - Description string `json:"description"` - URLs []string `json:"urls"` - Configurations []ZoneLockdownConfig `json:"configurations"` - Paused bool `json:"paused"` -} - -// ZoneLockdownConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type ZoneLockdownConfig struct { - Target string `json:"target"` - Value string `json:"value"` -} - -// ZoneLockdownResponse represents a response from the Zone Lockdown endpoint. -type ZoneLockdownResponse struct { - Result ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// ZoneLockdownListResponse represents a response from the List Zone Lockdown -// endpoint. -type ZoneLockdownListResponse struct { - Result []ZoneLockdown `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateZoneLockdown creates a Zone ZoneLockdown rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-create-a-ZoneLockdown-rule -func (api *API) CreateZoneLockdown(zoneID string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns" - res, err := api.makeRequest("POST", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneLockdown updates a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-update-ZoneLockdown-rule -func (api *API) UpdateZoneLockdown(zoneID string, id string, ld ZoneLockdown) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns" - res, err := api.makeRequest("PUT", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteZoneLockdown deletes a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-delete-ZoneLockdown-rule -func (api *API) DeleteZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneLockdown retrieves a Zone ZoneLockdown rule (based on the ID) for the -// given zone ID. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-ZoneLockdown-rule-details -func (api *API) ZoneLockdown(zoneID string, id string) (*ZoneLockdownResponse, error) { - uri := "/zones/" + zoneID + "/firewall/lockdowns/" + id - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListZoneLockdowns retrieves a list of Zone ZoneLockdown rules for a given -// zone ID by page number. -// -// API reference: https://api.cloudflare.com/#zone-ZoneLockdown-list-ZoneLockdown-rules -func (api *API) ListZoneLockdowns(zoneID string, page int) (*ZoneLockdownListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/firewall/lockdowns" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneLockdownListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/options.go b/vendor/github.com/cloudflare/cloudflare-go/options.go deleted file mode 100644 index 1a113ee10..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/options.go +++ /dev/null @@ -1,90 +0,0 @@ -package cloudflare - -import ( - "net/http" - - "time" - - "golang.org/x/time/rate" -) - -// Option is a functional option for configuring the API client. -type Option func(*API) error - -// HTTPClient accepts a custom *http.Client for making API calls. -func HTTPClient(client *http.Client) Option { - return func(api *API) error { - api.httpClient = client - return nil - } -} - -// Headers allows you to set custom HTTP headers when making API calls (e.g. for -// satisfying HTTP proxies, or for debugging). -func Headers(headers http.Header) Option { - return func(api *API) error { - api.headers = headers - return nil - } -} - -// Organization allows you to apply account-level changes (Load Balancing, Railguns) -// to an organization instead. -func UsingOrganization(orgID string) Option { - return func(api *API) error { - api.organizationID = orgID - return nil - } -} - -// UsingRateLimit applies a non-default rate limit to client API requests -// If not specified the default of 4rps will be applied -func UsingRateLimit(rps float64) Option { - return func(api *API) error { - // because ratelimiter doesnt do any windowing - // setting burst makes it difficult to enforce a fixed rate - // so setting it equal to 1 this effectively disables bursting - // this doesn't check for sensible values, ultimately the api will enforce that the value is ok - api.rateLimiter = rate.NewLimiter(rate.Limit(rps), 1) - return nil - } -} - -// UsingRetryPolicy applies a non-default number of retries and min/max retry delays -// This will be used when the client exponentially backs off after errored requests -func UsingRetryPolicy(maxRetries int, minRetryDelaySecs int, maxRetryDelaySecs int) Option { - // seconds is very granular for a minimum delay - but this is only in case of failure - return func(api *API) error { - api.retryPolicy = RetryPolicy{ - MaxRetries: maxRetries, - MinRetryDelay: time.Duration(minRetryDelaySecs) * time.Second, - MaxRetryDelay: time.Duration(maxRetryDelaySecs) * time.Second, - } - return nil - } -} - -// UsingLogger can be set if you want to get log output from this API instance -// By default no log output is emitted -func UsingLogger(logger Logger) Option { - return func(api *API) error { - api.logger = logger - return nil - } -} - -// parseOptions parses the supplied options functions and returns a configured -// *API instance. -func (api *API) parseOptions(opts ...Option) error { - // Range over each options function and apply it to our API type to - // configure it. Options functions are applied in order, with any - // conflicting options overriding earlier calls. - for _, option := range opts { - err := option(api) - if err != nil { - return err - } - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/organizations.go b/vendor/github.com/cloudflare/cloudflare-go/organizations.go deleted file mode 100644 index 97a67e778..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/organizations.go +++ /dev/null @@ -1,185 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// Organization represents a multi-user organization. -type Organization struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Status string `json:"status,omitempty"` - Permissions []string `json:"permissions,omitempty"` - Roles []string `json:"roles,omitempty"` -} - -// organizationResponse represents the response from the Organization endpoint. -type organizationResponse struct { - Response - Result []Organization `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMember has details on a member. -type OrganizationMember struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Email string `json:"email,omitempty"` - Status string `json:"status,omitempty"` - Roles []OrganizationRole `json:"roles,omitempty"` -} - -// OrganizationInvite has details on an invite. -type OrganizationInvite struct { - ID string `json:"id,omitempty"` - InvitedMemberID string `json:"invited_member_id,omitempty"` - InvitedMemberEmail string `json:"invited_member_email,omitempty"` - OrganizationID string `json:"organization_id,omitempty"` - OrganizationName string `json:"organization_name,omitempty"` - Roles []OrganizationRole `json:"roles,omitempty"` - InvitedBy string `json:"invited_by,omitempty"` - InvitedOn *time.Time `json:"invited_on,omitempty"` - ExpiresOn *time.Time `json:"expires_on,omitempty"` - Status string `json:"status,omitempty"` -} - -// OrganizationRole has details on a role. -type OrganizationRole struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - Permissions []string `json:"permissions,omitempty"` -} - -// OrganizationDetails represents details of an organization. -type OrganizationDetails struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Members []OrganizationMember `json:"members"` - Invites []OrganizationInvite `json:"invites"` - Roles []OrganizationRole `json:"roles,omitempty"` -} - -// organizationDetailsResponse represents the response from the OrganizationDetails endpoint. -type organizationDetailsResponse struct { - Response - Result OrganizationDetails `json:"result"` -} - -// ListOrganizations lists organizations of the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-s-organizations-list-organizations -func (api *API) ListOrganizations() ([]Organization, ResultInfo, error) { - var r organizationResponse - res, err := api.makeRequest("GET", "/user/organizations", nil) - if err != nil { - return []Organization{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []Organization{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// OrganizationDetails returns details for the specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organizations-organization-details -func (api *API) OrganizationDetails(organizationID string) (OrganizationDetails, error) { - var r organizationDetailsResponse - uri := "/organizations/" + organizationID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return OrganizationDetails{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return OrganizationDetails{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// organizationMembersResponse represents the response from the Organization members endpoint. -type organizationMembersResponse struct { - Response - Result []OrganizationMember `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMembers returns list of members for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-members-list-members -func (api *API) OrganizationMembers(organizationID string) ([]OrganizationMember, ResultInfo, error) { - var r organizationMembersResponse - uri := "/organizations/" + organizationID + "/members" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationMember{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationMember{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// organizationInvitesResponse represents the response from the Organization invites endpoint. -type organizationInvitesResponse struct { - Response - Result []OrganizationInvite `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationMembers returns list of invites for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-invites -func (api *API) OrganizationInvites(organizationID string) ([]OrganizationInvite, ResultInfo, error) { - var r organizationInvitesResponse - uri := "/organizations/" + organizationID + "/invites" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationInvite{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationInvite{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} - -// organizationRolesResponse represents the response from the Organization roles endpoint. -type organizationRolesResponse struct { - Response - Result []OrganizationRole `json:"result"` - ResultInfo `json:"result_info"` -} - -// OrganizationRoles returns list of roles for specified organization of the logged-in user. -// -// API reference: https://api.cloudflare.com/#organization-roles-list-roles -func (api *API) OrganizationRoles(organizationID string) ([]OrganizationRole, ResultInfo, error) { - var r organizationRolesResponse - uri := "/organizations/" + organizationID + "/roles" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []OrganizationRole{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return []OrganizationRole{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, r.ResultInfo, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go b/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go deleted file mode 100644 index 486033afd..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/origin_ca.go +++ /dev/null @@ -1,168 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// OriginCACertificate represents a Cloudflare-issued certificate. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca -type OriginCACertificate struct { - ID string `json:"id"` - Certificate string `json:"certificate"` - Hostnames []string `json:"hostnames"` - ExpiresOn time.Time `json:"expires_on"` - RequestType string `json:"request_type"` - RequestValidity int `json:"requested_validity"` - CSR string `json:"csr"` -} - -// OriginCACertificateListOptions represents the parameters used to list Cloudflare-issued certificates. -type OriginCACertificateListOptions struct { - ZoneID string -} - -// OriginCACertificateID represents the ID of the revoked certificate from the Revoke Certificate endpoint. -type OriginCACertificateID struct { - ID string `json:"id"` -} - -// originCACertificateResponse represents the response from the Create Certificate and the Certificate Details endpoints. -type originCACertificateResponse struct { - Response - Result OriginCACertificate `json:"result"` -} - -// originCACertificateResponseList represents the response from the List Certificates endpoint. -type originCACertificateResponseList struct { - Response - Result []OriginCACertificate `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// originCACertificateResponseRevoke represents the response from the Revoke Certificate endpoint. -type originCACertificateResponseRevoke struct { - Response - Result OriginCACertificateID `json:"result"` -} - -// CreateOriginCertificate creates a Cloudflare-signed certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-create-certificate -func (api *API) CreateOriginCertificate(certificate OriginCACertificate) (*OriginCACertificate, error) { - uri := "/certificates" - res, err := api.makeRequestWithAuthType("POST", uri, certificate, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// OriginCertificates lists all Cloudflare-issued certificates. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-list-certificates -func (api *API) OriginCertificates(options OriginCACertificateListOptions) ([]OriginCACertificate, error) { - v := url.Values{} - if options.ZoneID != "" { - v.Set("zone_id", options.ZoneID) - } - uri := "/certificates" + "?" + v.Encode() - res, err := api.makeRequestWithAuthType("GET", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponseList - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return originResponse.Result, nil -} - -// OriginCertificate returns the details for a Cloudflare-issued certificate. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-certificate-details -func (api *API) OriginCertificate(certificateID string) (*OriginCACertificate, error) { - uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType("GET", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponse - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil -} - -// RevokeOriginCertificate revokes a created certificate for a zone. -// -// This function requires api.APIUserServiceKey be set to your Certificates API key. -// -// API reference: https://api.cloudflare.com/#cloudflare-ca-revoke-certificate -func (api *API) RevokeOriginCertificate(certificateID string) (*OriginCACertificateID, error) { - uri := "/certificates/" + certificateID - res, err := api.makeRequestWithAuthType("DELETE", uri, nil, AuthUserService) - - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - var originResponse *originCACertificateResponseRevoke - - err = json.Unmarshal(res, &originResponse) - - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - if !originResponse.Success { - return nil, errors.New(errRequestNotSuccessful) - } - - return &originResponse.Result, nil - -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/page_rules.go b/vendor/github.com/cloudflare/cloudflare-go/page_rules.go deleted file mode 100644 index 8749b2c51..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/page_rules.go +++ /dev/null @@ -1,206 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// PageRuleTarget is the target to evaluate on a request. -// -// Currently Target must always be "url" and Operator must be "matches". Value -// is the URL pattern to match against. -type PageRuleTarget struct { - Target string `json:"target"` - Constraint struct { - Operator string `json:"operator"` - Value string `json:"value"` - } `json:"constraint"` -} - -/* -PageRuleAction is the action to take when the target is matched. - -Valid IDs are: - - always_online - always_use_https - browser_cache_ttl - browser_check - cache_level - disable_apps - disable_performance - disable_railgun - disable_security - edge_cache_ttl - email_obfuscation - forwarding_url - ip_geolocation - mirage - rocket_loader - security_level - server_side_exclude - smart_errors - ssl - waf -*/ -type PageRuleAction struct { - ID string `json:"id"` - Value interface{} `json:"value"` -} - -// PageRuleActions maps API action IDs to human-readable strings. -var PageRuleActions = map[string]string{ - "always_online": "Always Online", // Value of type string - "always_use_https": "Always Use HTTPS", // Value of type interface{} - "browser_cache_ttl": "Browser Cache TTL", // Value of type int - "browser_check": "Browser Integrity Check", // Value of type string - "cache_level": "Cache Level", // Value of type string - "disable_apps": "Disable Apps", // Value of type interface{} - "disable_performance": "Disable Performance", // Value of type interface{} - "disable_railgun": "Disable Railgun", // Value of type string - "disable_security": "Disable Security", // Value of type interface{} - "edge_cache_ttl": "Edge Cache TTL", // Value of type int - "email_obfuscation": "Email Obfuscation", // Value of type string - "forwarding_url": "Forwarding URL", // Value of type map[string]interface - "ip_geolocation": "IP Geolocation Header", // Value of type string - "mirage": "Mirage", // Value of type string - "rocket_loader": "Rocker Loader", // Value of type string - "security_level": "Security Level", // Value of type string - "server_side_exclude": "Server Side Excludes", // Value of type string - "smart_errors": "Smart Errors", // Value of type string - "ssl": "SSL", // Value of type string - "waf": "Web Application Firewall", // Value of type string -} - -// PageRule describes a Page Rule. -type PageRule struct { - ID string `json:"id,omitempty"` - Targets []PageRuleTarget `json:"targets"` - Actions []PageRuleAction `json:"actions"` - Priority int `json:"priority"` - Status string `json:"status"` // can be: active, paused - ModifiedOn time.Time `json:"modified_on,omitempty"` - CreatedOn time.Time `json:"created_on,omitempty"` -} - -// PageRuleDetailResponse is the API response, containing a single PageRule. -type PageRuleDetailResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result PageRule `json:"result"` -} - -// PageRulesResponse is the API response, containing an array of PageRules. -type PageRulesResponse struct { - Success bool `json:"success"` - Errors []string `json:"errors"` - Messages []string `json:"messages"` - Result []PageRule `json:"result"` -} - -// CreatePageRule creates a new Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-create-a-page-rule -func (api *API) CreatePageRule(zoneID string, rule PageRule) (*PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("POST", uri, rule) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return &r.Result, nil -} - -// ListPageRules returns all Page Rules for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-list-page-rules -func (api *API) ListPageRules(zoneID string) ([]PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []PageRule{}, errors.Wrap(err, errMakeRequestError) - } - var r PageRulesResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// PageRule fetches detail about one Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-page-rule-details -func (api *API) PageRule(zoneID, ruleID string) (PageRule, error) { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return PageRule{}, errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PageRule{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ChangePageRule lets you change individual settings for a Page Rule. This is -// in contrast to UpdatePageRule which replaces the entire Page Rule. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-change-a-page-rule -func (api *API) ChangePageRule(zoneID, ruleID string, rule PageRule) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PATCH", uri, rule) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// UpdatePageRule lets you replace a Page Rule. This is in contrast to -// ChangePageRule which lets you change individual settings. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-update-a-page-rule -func (api *API) UpdatePageRule(zoneID, ruleID string, rule PageRule) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("PUT", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} - -// DeletePageRule deletes a Page Rule for a zone. -// -// API reference: https://api.cloudflare.com/#page-rules-for-a-zone-delete-a-page-rule -func (api *API) DeletePageRule(zoneID, ruleID string) error { - uri := "/zones/" + zoneID + "/pagerules/" + ruleID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r PageRuleDetailResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/railgun.go b/vendor/github.com/cloudflare/cloudflare-go/railgun.go deleted file mode 100644 index 72d228691..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/railgun.go +++ /dev/null @@ -1,297 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// Railgun represents a Railgun's properties. -type Railgun struct { - ID string `json:"id"` - Name string `json:"name"` - Status string `json:"status"` - Enabled bool `json:"enabled"` - ZonesConnected int `json:"zones_connected"` - Build string `json:"build"` - Version string `json:"version"` - Revision string `json:"revision"` - ActivationKey string `json:"activation_key"` - ActivatedOn time.Time `json:"activated_on"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - UpgradeInfo struct { - LatestVersion string `json:"latest_version"` - DownloadLink string `json:"download_link"` - } `json:"upgrade_info"` -} - -// RailgunListOptions represents the parameters used to list railguns. -type RailgunListOptions struct { - Direction string -} - -// railgunResponse represents the response from the Create Railgun and the Railgun Details endpoints. -type railgunResponse struct { - Response - Result Railgun `json:"result"` -} - -// railgunsResponse represents the response from the List Railguns endpoint. -type railgunsResponse struct { - Response - Result []Railgun `json:"result"` -} - -// CreateRailgun creates a new Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-create-railgun -func (api *API) CreateRailgun(name string) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns" - params := struct { - Name string `json:"name"` - }{ - Name: name, - } - res, err := api.makeRequest("POST", uri, params) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRailguns lists Railguns connected to an account. -// -// API reference: https://api.cloudflare.com/#railgun-list-railguns -func (api *API) ListRailguns(options RailgunListOptions) ([]Railgun, error) { - v := url.Values{} - if options.Direction != "" { - v.Set("direction", options.Direction) - } - uri := api.userBaseURL("") + "/railguns" + "?" + v.Encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r railgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunDetails returns the details for a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-railgun-details -func (api *API) RailgunDetails(railgunID string) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// RailgunZones returns the zones that are currently using a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-get-zones-connected-to-a-railgun -func (api *API) RailgunZones(railgunID string) ([]Zone, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID + "/zones" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r ZonesResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// enableRailgun enables (true) or disables (false) a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) enableRailgun(railgunID string, enable bool) (Railgun, error) { - uri := api.userBaseURL("") + "/railguns/" + railgunID - params := struct { - Enabled bool `json:"enabled"` - }{ - Enabled: enable, - } - res, err := api.makeRequest("PATCH", uri, params) - if err != nil { - return Railgun{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return Railgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// EnableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) EnableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, true) -} - -// DisableRailgun enables a Railgun for all zones connected to it. -// -// API reference: https://api.cloudflare.com/#railgun-enable-or-disable-a-railgun -func (api *API) DisableRailgun(railgunID string) (Railgun, error) { - return api.enableRailgun(railgunID, false) -} - -// DeleteRailgun disables and deletes a Railgun. -// -// API reference: https://api.cloudflare.com/#railgun-delete-railgun -func (api *API) DeleteRailgun(railgunID string) error { - uri := api.userBaseURL("") + "/railguns/" + railgunID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} - -// ZoneRailgun represents the status of a Railgun on a zone. -type ZoneRailgun struct { - ID string `json:"id"` - Name string `json:"name"` - Enabled bool `json:"enabled"` - Connected bool `json:"connected"` -} - -// zoneRailgunResponse represents the response from the Zone Railgun Details endpoint. -type zoneRailgunResponse struct { - Response - Result ZoneRailgun `json:"result"` -} - -// zoneRailgunsResponse represents the response from the Zone Railgun endpoint. -type zoneRailgunsResponse struct { - Response - Result []ZoneRailgun `json:"result"` -} - -// RailgunDiagnosis represents the test results from testing railgun connections -// to a zone. -type RailgunDiagnosis struct { - Method string `json:"method"` - HostName string `json:"host_name"` - HTTPStatus int `json:"http_status"` - Railgun string `json:"railgun"` - URL string `json:"url"` - ResponseStatus string `json:"response_status"` - Protocol string `json:"protocol"` - ElapsedTime string `json:"elapsed_time"` - BodySize string `json:"body_size"` - BodyHash string `json:"body_hash"` - MissingHeaders string `json:"missing_headers"` - ConnectionClose bool `json:"connection_close"` - Cloudflare string `json:"cloudflare"` - CFRay string `json:"cf-ray"` - // NOTE: Cloudflare's online API documentation does not yet have definitions - // for the following fields. See: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection/ - CFWANError string `json:"cf-wan-error"` - CFCacheStatus string `json:"cf-cache-status"` -} - -// railgunDiagnosisResponse represents the response from the Test Railgun Connection enpoint. -type railgunDiagnosisResponse struct { - Response - Result RailgunDiagnosis `json:"result"` -} - -// ZoneRailguns returns the available Railguns for a zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-available-railguns -func (api *API) ZoneRailguns(zoneID string) ([]ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneRailgunDetails returns the configuration for a given Railgun. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-get-railgun-details -func (api *API) ZoneRailgunDetails(zoneID, railgunID string) (ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneRailgun{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// TestRailgunConnection tests a Railgun connection for a given zone. -// -// API reference: https://api.cloudflare.com/#railgun-connections-for-a-zone-test-railgun-connection -func (api *API) TestRailgunConnection(zoneID, railgunID string) (RailgunDiagnosis, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID + "/diagnose" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return RailgunDiagnosis{}, errors.Wrap(err, errMakeRequestError) - } - var r railgunDiagnosisResponse - if err := json.Unmarshal(res, &r); err != nil { - return RailgunDiagnosis{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// connectZoneRailgun connects (true) or disconnects (false) a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) connectZoneRailgun(zoneID, railgunID string, connect bool) (ZoneRailgun, error) { - uri := "/zones/" + zoneID + "/railguns/" + railgunID - params := struct { - Connected bool `json:"connected"` - }{ - Connected: connect, - } - res, err := api.makeRequest("PATCH", uri, params) - if err != nil { - return ZoneRailgun{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneRailgunResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneRailgun{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ConnectZoneRailgun connects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) ConnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, true) -} - -// DisconnectZoneRailgun disconnects a Railgun for a given zone. -// -// API reference: https://api.cloudflare.com/#railguns-for-a-zone-connect-or-disconnect-a-railgun -func (api *API) DisconnectZoneRailgun(zoneID, railgunID string) (ZoneRailgun, error) { - return api.connectZoneRailgun(zoneID, railgunID, false) -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go b/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go deleted file mode 100644 index 96ad70ee9..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/rate_limiting.go +++ /dev/null @@ -1,195 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// RateLimit is a policy than can be applied to limit traffic within a customer domain -type RateLimit struct { - ID string `json:"id,omitempty"` - Disabled bool `json:"disabled,omitempty"` - Description string `json:"description,omitempty"` - Match RateLimitTrafficMatcher `json:"match"` - Bypass []RateLimitKeyValue `json:"bypass,omitempty"` - Threshold int `json:"threshold"` - Period int `json:"period"` - Action RateLimitAction `json:"action"` -} - -// RateLimitTrafficMatcher contains the rules that will be used to apply a rate limit to traffic -type RateLimitTrafficMatcher struct { - Request RateLimitRequestMatcher `json:"request"` - Response RateLimitResponseMatcher `json:"response"` -} - -// RateLimitRequestMatcher contains the matching rules pertaining to requests -type RateLimitRequestMatcher struct { - Methods []string `json:"methods,omitempty"` - Schemes []string `json:"schemes,omitempty"` - URLPattern string `json:"url,omitempty"` -} - -// RateLimitResponseMatcher contains the matching rules pertaining to responses -type RateLimitResponseMatcher struct { - Statuses []int `json:"status,omitempty"` - OriginTraffic *bool `json:"origin_traffic,omitempty"` // api defaults to true so we need an explicit empty value -} - -// RateLimitKeyValue is k-v formatted as expected in the rate limit description -type RateLimitKeyValue struct { - Name string `json:"name"` - Value string `json:"value"` -} - -// RateLimitAction is the action that will be taken when the rate limit threshold is reached -type RateLimitAction struct { - Mode string `json:"mode"` - Timeout int `json:"timeout"` - Response *RateLimitActionResponse `json:"response"` -} - -// RateLimitActionResponse is the response that will be returned when rate limit action is triggered -type RateLimitActionResponse struct { - ContentType string `json:"content_type"` - Body string `json:"body"` -} - -type rateLimitResponse struct { - Response - Result RateLimit `json:"result"` -} - -type rateLimitListResponse struct { - Response - Result []RateLimit `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// CreateRateLimit creates a new rate limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-create-a-ratelimit -func (api *API) CreateRateLimit(zoneID string, limit RateLimit) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits" - res, err := api.makeRequest("POST", uri, limit) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListRateLimits returns Rate Limits for a zone, paginated according to the provided options -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListRateLimits(zoneID string, pageOpts PaginationOptions) ([]RateLimit, ResultInfo, error) { - v := url.Values{} - if pageOpts.PerPage > 0 { - v.Set("per_page", strconv.Itoa(pageOpts.PerPage)) - } - if pageOpts.Page > 0 { - v.Set("page", strconv.Itoa(pageOpts.Page)) - } - - uri := "/zones/" + zoneID + "/rate_limits" - if len(v) > 0 { - uri = uri + "?" + v.Encode() - } - - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errMakeRequestError) - } - - var r rateLimitListResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []RateLimit{}, ResultInfo{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, r.ResultInfo, nil -} - -// ListAllRateLimits returns all Rate Limits for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-list-rate-limits -func (api *API) ListAllRateLimits(zoneID string) ([]RateLimit, error) { - pageOpts := PaginationOptions{ - PerPage: 100, // this is the max page size allowed - Page: 1, - } - - allRateLimits := make([]RateLimit, 0) - for { - rateLimits, resultInfo, err := api.ListRateLimits(zoneID, pageOpts) - if err != nil { - return []RateLimit{}, err - } - allRateLimits = append(allRateLimits, rateLimits...) - // total pages is not returned on this call - // if number of records is less than the max, this must be the last page - // in case TotalCount % PerPage = 0, the last request will return an empty list - if resultInfo.Count < resultInfo.PerPage { - break - } - // continue with the next page - pageOpts.Page = pageOpts.Page + 1 - } - - return allRateLimits, nil -} - -// RateLimit fetches detail about one Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-rate-limit-details -func (api *API) RateLimit(zoneID, limitID string) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateRateLimit lets you replace a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-update-rate-limit -func (api *API) UpdateRateLimit(zoneID, limitID string, limit RateLimit) (RateLimit, error) { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("PUT", uri, limit) - if err != nil { - return RateLimit{}, errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - if err := json.Unmarshal(res, &r); err != nil { - return RateLimit{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteRateLimit deletes a Rate Limit for a zone. -// -// API reference: https://api.cloudflare.com/#rate-limits-for-a-zone-delete-rate-limit -func (api *API) DeleteRateLimit(zoneID, limitID string) error { - uri := "/zones/" + zoneID + "/rate_limits/" + limitID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - var r rateLimitResponse - err = json.Unmarshal(res, &r) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/ssl.go b/vendor/github.com/cloudflare/cloudflare-go/ssl.go deleted file mode 100644 index def81ea01..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/ssl.go +++ /dev/null @@ -1,148 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// ZoneCustomSSL represents custom SSL certificate metadata. -type ZoneCustomSSL struct { - ID string `json:"id"` - Hosts []string `json:"hosts"` - Issuer string `json:"issuer"` - Signature string `json:"signature"` - Status string `json:"status"` - BundleMethod string `json:"bundle_method"` - ZoneID string `json:"zone_id"` - UploadedOn time.Time `json:"uploaded_on"` - ModifiedOn time.Time `json:"modified_on"` - ExpiresOn time.Time `json:"expires_on"` - Priority int `json:"priority"` - KeylessServer KeylessSSL `json:"keyless_server"` -} - -// zoneCustomSSLResponse represents the response from the zone SSL details endpoint. -type zoneCustomSSLResponse struct { - Response - Result ZoneCustomSSL `json:"result"` -} - -// zoneCustomSSLsResponse represents the response from the zone SSL list endpoint. -type zoneCustomSSLsResponse struct { - Response - Result []ZoneCustomSSL `json:"result"` -} - -// ZoneCustomSSLOptions represents the parameters to create or update an existing -// custom SSL configuration. -type ZoneCustomSSLOptions struct { - Certificate string `json:"certificate"` - PrivateKey string `json:"private_key"` - BundleMethod string `json:"bundle_method,omitempty"` -} - -// ZoneCustomSSLPriority represents a certificate's ID and priority. It is a -// subset of ZoneCustomSSL used for patch requests. -type ZoneCustomSSLPriority struct { - ID string `json:"ID"` - Priority int `json:"priority"` -} - -// CreateSSL allows you to add a custom SSL certificate to the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-create-ssl-configuration -func (api *API) CreateSSL(zoneID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("POST", uri, options) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ListSSL lists the custom certificates for the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-list-ssl-configurations -func (api *API) ListSSL(zoneID string) ([]ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// SSLDetails returns the configuration details for a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-ssl-configuration-details -func (api *API) SSLDetails(zoneID, certificateID string) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// UpdateSSL updates (replaces) a custom SSL certificate. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-update-ssl-configuration -func (api *API) UpdateSSL(zoneID, certificateID string, options ZoneCustomSSLOptions) (ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - res, err := api.makeRequest("PATCH", uri, options) - if err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLResponse - if err := json.Unmarshal(res, &r); err != nil { - return ZoneCustomSSL{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ReprioritizeSSL allows you to change the priority (which is served for a given -// request) of custom SSL certificates associated with the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-re-prioritize-ssl-certificates -func (api *API) ReprioritizeSSL(zoneID string, p []ZoneCustomSSLPriority) ([]ZoneCustomSSL, error) { - uri := "/zones/" + zoneID + "/custom_certificates/prioritize" - params := struct { - Certificates []ZoneCustomSSLPriority `json:"certificates"` - }{ - Certificates: p, - } - res, err := api.makeRequest("PUT", uri, params) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneCustomSSLsResponse - if err := json.Unmarshal(res, &r); err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// DeleteSSL deletes a custom SSL certificate from the given zone. -// -// API reference: https://api.cloudflare.com/#custom-ssl-for-a-zone-delete-an-ssl-certificate -func (api *API) DeleteSSL(zoneID, certificateID string) error { - uri := "/zones/" + zoneID + "/custom_certificates/" + certificateID - if _, err := api.makeRequest("DELETE", uri, nil); err != nil { - return errors.Wrap(err, errMakeRequestError) - } - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/user.go b/vendor/github.com/cloudflare/cloudflare-go/user.go deleted file mode 100644 index b42641e92..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/user.go +++ /dev/null @@ -1,113 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "time" - - "github.com/pkg/errors" -) - -// User describes a user account. -type User struct { - ID string `json:"id,omitempty"` - Email string `json:"email,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Username string `json:"username,omitempty"` - Telephone string `json:"telephone,omitempty"` - Country string `json:"country,omitempty"` - Zipcode string `json:"zipcode,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - ModifiedOn *time.Time `json:"modified_on,omitempty"` - APIKey string `json:"api_key,omitempty"` - TwoFA bool `json:"two_factor_authentication_enabled,omitempty"` - Betas []string `json:"betas,omitempty"` - Organizations []Organization `json:"organizations,omitempty"` -} - -// UserResponse wraps a response containing User accounts. -type UserResponse struct { - Response - Result User `json:"result"` -} - -// userBillingProfileResponse wraps a response containing Billing Profile information. -type userBillingProfileResponse struct { - Response - Result UserBillingProfile -} - -// UserBillingProfile contains Billing Profile information. -type UserBillingProfile struct { - ID string `json:"id,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - Address string `json:"address,omitempty"` - Address2 string `json:"address2,omitempty"` - Company string `json:"company,omitempty"` - City string `json:"city,omitempty"` - State string `json:"state,omitempty"` - ZipCode string `json:"zipcode,omitempty"` - Country string `json:"country,omitempty"` - Telephone string `json:"telephone,omitempty"` - CardNumber string `json:"card_number,omitempty"` - CardExpiryYear int `json:"card_expiry_year,omitempty"` - CardExpiryMonth int `json:"card_expiry_month,omitempty"` - VAT string `json:"vat,omitempty"` - CreatedOn *time.Time `json:"created_on,omitempty"` - EditedOn *time.Time `json:"edited_on,omitempty"` -} - -// UserDetails provides information about the logged-in user. -// -// API reference: https://api.cloudflare.com/#user-user-details -func (api *API) UserDetails() (User, error) { - var r UserResponse - res, err := api.makeRequest("GET", "/user", nil) - if err != nil { - return User{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UpdateUser updates the properties of the given user. -// -// API reference: https://api.cloudflare.com/#user-update-user -func (api *API) UpdateUser(user *User) (User, error) { - var r UserResponse - res, err := api.makeRequest("PATCH", "/user", user) - if err != nil { - return User{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return User{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// UserBillingProfile returns the billing profile of the user. -// -// API reference: https://api.cloudflare.com/#user-billing-profile -func (api *API) UserBillingProfile() (UserBillingProfile, error) { - var r userBillingProfileResponse - res, err := api.makeRequest("GET", "/user/billing/profile", nil) - if err != nil { - return UserBillingProfile{}, errors.Wrap(err, errMakeRequestError) - } - - err = json.Unmarshal(res, &r) - if err != nil { - return UserBillingProfile{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/user_agent.go b/vendor/github.com/cloudflare/cloudflare-go/user_agent.go deleted file mode 100644 index 6d75f3a1d..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/user_agent.go +++ /dev/null @@ -1,149 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "net/url" - "strconv" - - "github.com/pkg/errors" -) - -// UserAgentRule represents a User-Agent Block. These rules can be used to -// challenge, block or whitelist specific User-Agents for a given zone. -type UserAgentRule struct { - ID string `json:"id"` - Description string `json:"description"` - Mode string `json:"mode"` - Configuration UserAgentRuleConfig `json:"configuration"` - Paused bool `json:"paused"` -} - -// UserAgentRuleConfig represents a Zone Lockdown config, which comprises -// a Target ("ip" or "ip_range") and a Value (an IP address or IP+mask, -// respectively.) -type UserAgentRuleConfig ZoneLockdownConfig - -// UserAgentRuleResponse represents a response from the Zone Lockdown endpoint. -type UserAgentRuleResponse struct { - Result UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// UserAgentRuleListResponse represents a response from the List Zone Lockdown endpoint. -type UserAgentRuleListResponse struct { - Result []UserAgentRule `json:"result"` - Response - ResultInfo `json:"result_info"` -} - -// CreateUserAgentRule creates a User-Agent Block rule for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-create-a-useragent-rule -func (api *API) CreateUserAgentRule(zoneID string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - switch ld.Mode { - case "block", "challenge", "js_challenge", "whitelist": - break - default: - return nil, errors.New(`the User-Agent Block rule mode must be one of "block", "challenge", "js_challenge", "whitelist"`) - } - - uri := "/zones/" + zoneID + "/firewall/ua_rules" - res, err := api.makeRequest("POST", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateUserAgentRule updates a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-update-useragent-rule -func (api *API) UpdateUserAgentRule(zoneID string, id string, ld UserAgentRule) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("PUT", uri, ld) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// DeleteUserAgentRule deletes a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-delete-useragent-rule -func (api *API) DeleteUserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UserAgentRule retrieves a User-Agent Block rule (based on the ID) for the given zone ID. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-useragent-rule-details -func (api *API) UserAgentRule(zoneID string, id string) (*UserAgentRuleResponse, error) { - uri := "/zones/" + zoneID + "/firewall/ua_rules/" + id - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ListUserAgentRules retrieves a list of User-Agent Block rules for a given zone ID by page number. -// -// API reference: https://api.cloudflare.com/#user-agent-blocking-rules-list-useragent-rules -func (api *API) ListUserAgentRules(zoneID string, page int) (*UserAgentRuleListResponse, error) { - v := url.Values{} - if page <= 0 { - page = 1 - } - - v.Set("page", strconv.Itoa(page)) - v.Set("per_page", strconv.Itoa(100)) - query := "?" + v.Encode() - - uri := "/zones/" + zoneID + "/firewall/ua_rules" + query - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &UserAgentRuleListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go b/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go deleted file mode 100644 index 6eb7629f0..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/virtualdns.go +++ /dev/null @@ -1,125 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - - "github.com/pkg/errors" -) - -// VirtualDNS represents a Virtual DNS configuration. -type VirtualDNS struct { - ID string `json:"id"` - Name string `json:"name"` - OriginIPs []string `json:"origin_ips"` - VirtualDNSIPs []string `json:"virtual_dns_ips"` - MinimumCacheTTL uint `json:"minimum_cache_ttl"` - MaximumCacheTTL uint `json:"maximum_cache_ttl"` - DeprecateAnyRequests bool `json:"deprecate_any_requests"` - ModifiedOn string `json:"modified_on"` -} - -// VirtualDNSResponse represents a Virtual DNS response. -type VirtualDNSResponse struct { - Response - Result *VirtualDNS `json:"result"` -} - -// VirtualDNSListResponse represents an array of Virtual DNS responses. -type VirtualDNSListResponse struct { - Response - Result []*VirtualDNS `json:"result"` -} - -// CreateVirtualDNS creates a new Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--create-a-virtual-dns-cluster -func (api *API) CreateVirtualDNS(v *VirtualDNS) (*VirtualDNS, error) { - res, err := api.makeRequest("POST", "/user/virtual_dns", v) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// VirtualDNS fetches a single virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-a-virtual-dns-cluster -func (api *API) VirtualDNS(virtualDNSID string) (*VirtualDNS, error) { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// ListVirtualDNS lists the virtual DNS clusters associated with an account. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--get-virtual-dns-clusters -func (api *API) ListVirtualDNS() ([]*VirtualDNS, error) { - res, err := api.makeRequest("GET", "/user/virtual_dns", nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSListResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response.Result, nil -} - -// UpdateVirtualDNS updates a Virtual DNS cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--modify-a-virtual-dns-cluster -func (api *API) UpdateVirtualDNS(virtualDNSID string, vv VirtualDNS) error { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("PUT", uri, vv) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} - -// DeleteVirtualDNS deletes a Virtual DNS cluster. Note that this cannot be -// undone, and will stop all traffic to that cluster. -// -// API reference: https://api.cloudflare.com/#virtual-dns-users--delete-a-virtual-dns-cluster -func (api *API) DeleteVirtualDNS(virtualDNSID string) error { - uri := "/user/virtual_dns/" + virtualDNSID - res, err := api.makeRequest("DELETE", uri, nil) - if err != nil { - return errors.Wrap(err, errMakeRequestError) - } - - response := &VirtualDNSResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return errors.Wrap(err, errUnmarshalError) - } - - return nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/waf.go b/vendor/github.com/cloudflare/cloudflare-go/waf.go deleted file mode 100644 index 4ed156236..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/waf.go +++ /dev/null @@ -1,97 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - - "github.com/pkg/errors" -) - -// WAFPackage represents a WAF package configuration. -type WAFPackage struct { - ID string `json:"id"` - Name string `json:"name"` - Description string `json:"description"` - ZoneID string `json:"zone_id"` - DetectionMode string `json:"detection_mode"` - Sensitivity string `json:"sensitivity"` - ActionMode string `json:"action_mode"` -} - -// WAFPackagesResponse represents the response from the WAF packages endpoint. -type WAFPackagesResponse struct { - Response - Result []WAFPackage `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// WAFRule represents a WAF rule. -type WAFRule struct { - ID string `json:"id"` - Description string `json:"description"` - Priority string `json:"priority"` - PackageID string `json:"package_id"` - Group struct { - ID string `json:"id"` - Name string `json:"name"` - } `json:"group"` - Mode string `json:"mode"` - DefaultMode string `json:"default_mode"` - AllowedModes []string `json:"allowed_modes"` -} - -// WAFRulesResponse represents the response from the WAF rule endpoint. -type WAFRulesResponse struct { - Response - Result []WAFRule `json:"result"` - ResultInfo ResultInfo `json:"result_info"` -} - -// ListWAFPackages returns a slice of the WAF packages for the given zone. -func (api *API) ListWAFPackages(zoneID string) ([]WAFPackage, error) { - var p WAFPackagesResponse - var packages []WAFPackage - var res []byte - var err error - uri := "/zones/" + zoneID + "/firewall/waf/packages" - res, err = api.makeRequest("GET", uri, nil) - if err != nil { - return []WAFPackage{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &p) - if err != nil { - return []WAFPackage{}, errors.Wrap(err, errUnmarshalError) - } - if !p.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFPackage{}, err - } - for pi := range p.Result { - packages = append(packages, p.Result[pi]) - } - return packages, nil -} - -// ListWAFRules returns a slice of the WAF rules for the given WAF package. -func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) { - var r WAFRulesResponse - var rules []WAFRule - var res []byte - var err error - uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules" - res, err = api.makeRequest("GET", uri, nil) - if err != nil { - return []WAFRule{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []WAFRule{}, errors.Wrap(err, errUnmarshalError) - } - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []WAFRule{}, err - } - for ri := range r.Result { - rules = append(rules, r.Result[ri]) - } - return rules, nil -} diff --git a/vendor/github.com/cloudflare/cloudflare-go/zone.go b/vendor/github.com/cloudflare/cloudflare-go/zone.go deleted file mode 100644 index fe222d33e..000000000 --- a/vendor/github.com/cloudflare/cloudflare-go/zone.go +++ /dev/null @@ -1,587 +0,0 @@ -package cloudflare - -import ( - "encoding/json" - "fmt" - "net/url" - "time" - - "github.com/pkg/errors" -) - -// Owner describes the resource owner. -type Owner struct { - ID string `json:"id"` - Email string `json:"email"` - OwnerType string `json:"owner_type"` -} - -// Zone describes a Cloudflare zone. -type Zone struct { - ID string `json:"id"` - Name string `json:"name"` - // DevMode contains the time in seconds until development expires (if - // positive) or since it expired (if negative). It will be 0 if never used. - DevMode int `json:"development_mode"` - OriginalNS []string `json:"original_name_servers"` - OriginalRegistrar string `json:"original_registrar"` - OriginalDNSHost string `json:"original_dnshost"` - CreatedOn time.Time `json:"created_on"` - ModifiedOn time.Time `json:"modified_on"` - NameServers []string `json:"name_servers"` - Owner Owner `json:"owner"` - Permissions []string `json:"permissions"` - Plan ZoneRatePlan `json:"plan"` - PlanPending ZoneRatePlan `json:"plan_pending,omitempty"` - Status string `json:"status"` - Paused bool `json:"paused"` - Type string `json:"type"` - Host struct { - Name string - Website string - } `json:"host"` - VanityNS []string `json:"vanity_name_servers"` - Betas []string `json:"betas"` - DeactReason string `json:"deactivation_reason"` - Meta ZoneMeta `json:"meta"` -} - -// ZoneMeta describes metadata about a zone. -type ZoneMeta struct { - // custom_certificate_quota is broken - sometimes it's a string, sometimes a number! - // CustCertQuota int `json:"custom_certificate_quota"` - PageRuleQuota int `json:"page_rule_quota"` - WildcardProxiable bool `json:"wildcard_proxiable"` - PhishingDetected bool `json:"phishing_detected"` -} - -// ZoneRatePlan contains the plan information for a zone. -type ZoneRatePlan struct { - ID string `json:"id"` - Name string `json:"name,omitempty"` - Price int `json:"price,omitempty"` - Currency string `json:"currency,omitempty"` - Duration int `json:"duration,omitempty"` - Frequency string `json:"frequency,omitempty"` - Components []zoneRatePlanComponents `json:"components,omitempty"` -} - -type zoneRatePlanComponents struct { - Name string `json:"name"` - Default int `json:"Default"` - UnitPrice int `json:"unit_price"` -} - -// ZoneID contains only the zone ID. -type ZoneID struct { - ID string `json:"id"` -} - -// ZoneResponse represents the response from the Zone endpoint containing a single zone. -type ZoneResponse struct { - Response - Result Zone `json:"result"` -} - -// ZonesResponse represents the response from the Zone endpoint containing an array of zones. -type ZonesResponse struct { - Response - Result []Zone `json:"result"` -} - -// ZoneIDResponse represents the response from the Zone endpoint, containing only a zone ID. -type ZoneIDResponse struct { - Response - Result ZoneID `json:"result"` -} - -// AvailableZoneRatePlansResponse represents the response from the Available Rate Plans endpoint. -type AvailableZoneRatePlansResponse struct { - Response - Result []ZoneRatePlan `json:"result"` - ResultInfo -} - -// ZoneRatePlanResponse represents the response from the Plan Details endpoint. -type ZoneRatePlanResponse struct { - Response - Result ZoneRatePlan `json:"result"` -} - -// ZoneSetting contains settings for a zone. -type ZoneSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on"` - Value interface{} `json:"value"` - TimeRemaining int `json:"time_remaining"` -} - -// ZoneSettingResponse represents the response from the Zone Setting endpoint. -type ZoneSettingResponse struct { - Response - Result []ZoneSetting `json:"result"` -} - -// ZoneSSLSetting contains ssl setting for a zone. -type ZoneSSLSetting struct { - ID string `json:"id"` - Editable bool `json:"editable"` - ModifiedOn string `json:"modified_on"` - Value string `json:"value"` - CertificateStatus string `json:"certificate_status"` -} - -// ZoneSettingResponse represents the response from the Zone SSL Setting endpoint. -type ZoneSSLSettingResponse struct { - Response - Result ZoneSSLSetting `json:"result"` -} - -// ZoneAnalyticsData contains totals and timeseries analytics data for a zone. -type ZoneAnalyticsData struct { - Totals ZoneAnalytics `json:"totals"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsDataResponse represents the response from the Zone Analytics Dashboard endpoint. -type zoneAnalyticsDataResponse struct { - Response - Result ZoneAnalyticsData `json:"result"` -} - -// ZoneAnalyticsColocation contains analytics data by datacenter. -type ZoneAnalyticsColocation struct { - ColocationID string `json:"colo_id"` - Timeseries []ZoneAnalytics `json:"timeseries"` -} - -// zoneAnalyticsColocationResponse represents the response from the Zone Analytics By Co-location endpoint. -type zoneAnalyticsColocationResponse struct { - Response - Result []ZoneAnalyticsColocation `json:"result"` -} - -// ZoneAnalytics contains analytics data for a zone. -type ZoneAnalytics struct { - Since time.Time `json:"since"` - Until time.Time `json:"until"` - Requests struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - HTTPStatus map[string]int `json:"http_status"` - } `json:"requests"` - Bandwidth struct { - All int `json:"all"` - Cached int `json:"cached"` - Uncached int `json:"uncached"` - ContentType map[string]int `json:"content_type"` - Country map[string]int `json:"country"` - SSL struct { - Encrypted int `json:"encrypted"` - Unencrypted int `json:"unencrypted"` - } `json:"ssl"` - } `json:"bandwidth"` - Threats struct { - All int `json:"all"` - Country map[string]int `json:"country"` - Type map[string]int `json:"type"` - } `json:"threats"` - Pageviews struct { - All int `json:"all"` - SearchEngines map[string]int `json:"search_engines"` - } `json:"pageviews"` - Uniques struct { - All int `json:"all"` - } -} - -// ZoneAnalyticsOptions represents the optional parameters in Zone Analytics -// endpoint requests. -type ZoneAnalyticsOptions struct { - Since *time.Time - Until *time.Time - Continuous *bool -} - -// PurgeCacheRequest represents the request format made to the purge endpoint. -type PurgeCacheRequest struct { - Everything bool `json:"purge_everything,omitempty"` - // Purge by filepath (exact match). Limit of 30 - Files []string `json:"files,omitempty"` - // Purge by Tag (Enterprise only): - // https://support.cloudflare.com/hc/en-us/articles/206596608-How-to-Purge-Cache-Using-Cache-Tags-Enterprise-only- - Tags []string `json:"tags,omitempty"` - // Purge by hostname - e.g. "assets.example.com" - Hosts []string `json:"hosts,omitempty"` -} - -// PurgeCacheResponse represents the response from the purge endpoint. -type PurgeCacheResponse struct { - Response - Result struct { - ID string `json:"id"` - } `json:"result"` -} - -// newZone describes a new zone. -type newZone struct { - Name string `json:"name"` - JumpStart bool `json:"jump_start"` - // We use a pointer to get a nil type when the field is empty. - // This allows us to completely omit this with json.Marshal(). - Organization *Organization `json:"organization,omitempty"` -} - -// CreateZone creates a zone on an account. -// -// Setting jumpstart to true will attempt to automatically scan for existing -// DNS records. Setting this to false will create the zone with no DNS records. -// -// If Organization is non-empty, it must have at least the ID field populated. -// This will add the new zone to the specified multi-user organization. -// -// API reference: https://api.cloudflare.com/#zone-create-a-zone -func (api *API) CreateZone(name string, jumpstart bool, org Organization) (Zone, error) { - var newzone newZone - newzone.Name = name - newzone.JumpStart = jumpstart - if org.ID != "" { - newzone.Organization = &org - } - - res, err := api.makeRequest("POST", "/zones", newzone) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneActivationCheck initiates another zone activation check for newly-created zones. -// -// API reference: https://api.cloudflare.com/#zone-initiate-another-zone-activation-check -func (api *API) ZoneActivationCheck(zoneID string) (Response, error) { - res, err := api.makeRequest("PUT", "/zones/"+zoneID+"/activation_check", nil) - if err != nil { - return Response{}, errors.Wrap(err, errMakeRequestError) - } - var r Response - err = json.Unmarshal(res, &r) - if err != nil { - return Response{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// ListZones lists zones on an account. Optionally takes a list of zone names -// to filter against. -// -// API reference: https://api.cloudflare.com/#zone-list-zones -func (api *API) ListZones(z ...string) ([]Zone, error) { - v := url.Values{} - var res []byte - var r ZonesResponse - var zones []Zone - var err error - if len(z) > 0 { - for _, zone := range z { - v.Set("name", zone) - res, err = api.makeRequest("GET", "/zones?"+v.Encode(), nil) - if err != nil { - return []Zone{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []Zone{}, errors.Wrap(err, errUnmarshalError) - } - if !r.Success { - // TODO: Provide an actual error message instead of always returning nil - return []Zone{}, err - } - for zi := range r.Result { - zones = append(zones, r.Result[zi]) - } - } - } else { - // TODO: Paginate here. We only grab the first page of results. - // Could do this concurrently after the first request by creating a - // sync.WaitGroup or just a channel + workers. - res, err = api.makeRequest("GET", "/zones", nil) - if err != nil { - return []Zone{}, errors.Wrap(err, errMakeRequestError) - } - err = json.Unmarshal(res, &r) - if err != nil { - return []Zone{}, errors.Wrap(err, errUnmarshalError) - } - zones = r.Result - } - - return zones, nil -} - -// ZoneDetails fetches information about a zone. -// -// API reference: https://api.cloudflare.com/#zone-zone-details -func (api *API) ZoneDetails(zoneID string) (Zone, error) { - res, err := api.makeRequest("GET", "/zones/"+zoneID, nil) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneOptions is a subset of Zone, for editable options. -type ZoneOptions struct { - Paused *bool `json:"paused,omitempty"` - VanityNS []string `json:"vanity_name_servers,omitempty"` - Plan *ZoneRatePlan `json:"plan,omitempty"` -} - -// ZoneSetPaused pauses Cloudflare service for the entire zone, sending all -// traffic direct to the origin. -func (api *API) ZoneSetPaused(zoneID string, paused bool) (Zone, error) { - zoneopts := ZoneOptions{Paused: &paused} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetVanityNS sets custom nameservers for the zone. -// These names must be within the same zone. -func (api *API) ZoneSetVanityNS(zoneID string, ns []string) (Zone, error) { - zoneopts := ZoneOptions{VanityNS: ns} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// ZoneSetRatePlan changes the zone plan. -func (api *API) ZoneSetRatePlan(zoneID string, plan ZoneRatePlan) (Zone, error) { - zoneopts := ZoneOptions{Plan: &plan} - zone, err := api.EditZone(zoneID, zoneopts) - if err != nil { - return Zone{}, err - } - - return zone, nil -} - -// EditZone edits the given zone. -// -// This is usually called by ZoneSetPaused, ZoneSetVanityNS or ZoneSetPlan. -// -// API reference: https://api.cloudflare.com/#zone-edit-zone-properties -func (api *API) EditZone(zoneID string, zoneOpts ZoneOptions) (Zone, error) { - res, err := api.makeRequest("PATCH", "/zones/"+zoneID, zoneOpts) - if err != nil { - return Zone{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneResponse - err = json.Unmarshal(res, &r) - if err != nil { - return Zone{}, errors.Wrap(err, errUnmarshalError) - } - - return r.Result, nil -} - -// PurgeEverything purges the cache for the given zone. -// -// Note: this will substantially increase load on the origin server for that -// zone if there is a high cached vs. uncached request ratio. -// -// API reference: https://api.cloudflare.com/#zone-purge-all-files -func (api *API) PurgeEverything(zoneID string) (PurgeCacheResponse, error) { - uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequest("DELETE", uri, PurgeCacheRequest{true, nil, nil, nil}) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errMakeRequestError) - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// PurgeCache purges the cache using the given PurgeCacheRequest (zone/url/tag). -// -// API reference: https://api.cloudflare.com/#zone-purge-individual-files-by-url-and-cache-tags -func (api *API) PurgeCache(zoneID string, pcr PurgeCacheRequest) (PurgeCacheResponse, error) { - uri := "/zones/" + zoneID + "/purge_cache" - res, err := api.makeRequest("DELETE", uri, pcr) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errMakeRequestError) - } - var r PurgeCacheResponse - err = json.Unmarshal(res, &r) - if err != nil { - return PurgeCacheResponse{}, errors.Wrap(err, errUnmarshalError) - } - return r, nil -} - -// DeleteZone deletes the given zone. -// -// API reference: https://api.cloudflare.com/#zone-delete-a-zone -func (api *API) DeleteZone(zoneID string) (ZoneID, error) { - res, err := api.makeRequest("DELETE", "/zones/"+zoneID, nil) - if err != nil { - return ZoneID{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneIDResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneID{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// AvailableZoneRatePlans returns information about all plans available to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-plan-available-plans -func (api *API) AvailableZoneRatePlans(zoneID string) ([]ZoneRatePlan, error) { - uri := "/zones/" + zoneID + "/available_rate_plans" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return []ZoneRatePlan{}, errors.Wrap(err, errMakeRequestError) - } - var r AvailableZoneRatePlansResponse - err = json.Unmarshal(res, &r) - if err != nil { - return []ZoneRatePlan{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// encode encodes non-nil fields into URL encoded form. -func (o ZoneAnalyticsOptions) encode() string { - v := url.Values{} - if o.Since != nil { - v.Set("since", (*o.Since).Format(time.RFC3339)) - } - if o.Until != nil { - v.Set("until", (*o.Until).Format(time.RFC3339)) - } - if o.Continuous != nil { - v.Set("continuous", fmt.Sprintf("%t", *o.Continuous)) - } - return v.Encode() -} - -// ZoneAnalyticsDashboard returns zone analytics information. -// -// API reference: https://api.cloudflare.com/#zone-analytics-dashboard -func (api *API) ZoneAnalyticsDashboard(zoneID string, options ZoneAnalyticsOptions) (ZoneAnalyticsData, error) { - uri := "/zones/" + zoneID + "/analytics/dashboard" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneAnalyticsData{}, errors.Wrap(err, errMakeRequestError) - } - var r zoneAnalyticsDataResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneAnalyticsData{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneAnalyticsByColocation returns zone analytics information by datacenter. -// -// API reference: https://api.cloudflare.com/#zone-analytics-analytics-by-co-locations -func (api *API) ZoneAnalyticsByColocation(zoneID string, options ZoneAnalyticsOptions) ([]ZoneAnalyticsColocation, error) { - uri := "/zones/" + zoneID + "/analytics/colos" + "?" + options.encode() - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - var r zoneAnalyticsColocationResponse - err = json.Unmarshal(res, &r) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} - -// ZoneSettings returns all of the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-all-zone-settings -func (api *API) ZoneSettings(zoneID string) (*ZoneSettingResponse, error) { - uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// UpdateZoneSettings updates the settings for a given zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-edit-zone-settings-info -func (api *API) UpdateZoneSettings(zoneID string, settings []ZoneSetting) (*ZoneSettingResponse, error) { - uri := "/zones/" + zoneID + "/settings" - res, err := api.makeRequest("PATCH", uri, struct { - Items []ZoneSetting `json:"items"` - }{settings}) - if err != nil { - return nil, errors.Wrap(err, errMakeRequestError) - } - - response := &ZoneSettingResponse{} - err = json.Unmarshal(res, &response) - if err != nil { - return nil, errors.Wrap(err, errUnmarshalError) - } - - return response, nil -} - -// ZoneSSLSettings returns information about SSL setting to the specified zone. -// -// API reference: https://api.cloudflare.com/#zone-settings-get-ssl-setting -func (api *API) ZoneSSLSettings(zoneID string) (ZoneSSLSetting, error) { - uri := "/zones/" + zoneID + "/settings/ssl" - res, err := api.makeRequest("GET", uri, nil) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errMakeRequestError) - } - var r ZoneSSLSettingResponse - err = json.Unmarshal(res, &r) - if err != nil { - return ZoneSSLSetting{}, errors.Wrap(err, errUnmarshalError) - } - return r.Result, nil -} diff --git a/vendor/github.com/codahale/hdrhistogram/LICENSE b/vendor/github.com/codahale/hdrhistogram/LICENSE deleted file mode 100644 index f9835c241..000000000 --- a/vendor/github.com/codahale/hdrhistogram/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Coda Hale - -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/codahale/hdrhistogram/hdr.go b/vendor/github.com/codahale/hdrhistogram/hdr.go deleted file mode 100644 index c97842926..000000000 --- a/vendor/github.com/codahale/hdrhistogram/hdr.go +++ /dev/null @@ -1,564 +0,0 @@ -// Package hdrhistogram provides an implementation of Gil Tene's HDR Histogram -// data structure. The HDR Histogram allows for fast and accurate analysis of -// the extreme ranges of data with non-normal distributions, like latency. -package hdrhistogram - -import ( - "fmt" - "math" -) - -// A Bracket is a part of a cumulative distribution. -type Bracket struct { - Quantile float64 - Count, ValueAt int64 -} - -// A Snapshot is an exported view of a Histogram, useful for serializing them. -// A Histogram can be constructed from it by passing it to Import. -type Snapshot struct { - LowestTrackableValue int64 - HighestTrackableValue int64 - SignificantFigures int64 - Counts []int64 -} - -// A Histogram is a lossy data structure used to record the distribution of -// non-normally distributed data (like latency) with a high degree of accuracy -// and a bounded degree of precision. -type Histogram struct { - lowestTrackableValue int64 - highestTrackableValue int64 - unitMagnitude int64 - significantFigures int64 - subBucketHalfCountMagnitude int32 - subBucketHalfCount int32 - subBucketMask int64 - subBucketCount int32 - bucketCount int32 - countsLen int32 - totalCount int64 - counts []int64 -} - -// New returns a new Histogram instance capable of tracking values in the given -// range and with the given amount of precision. -func New(minValue, maxValue int64, sigfigs int) *Histogram { - if sigfigs < 1 || 5 < sigfigs { - panic(fmt.Errorf("sigfigs must be [1,5] (was %d)", sigfigs)) - } - - largestValueWithSingleUnitResolution := 2 * math.Pow10(sigfigs) - subBucketCountMagnitude := int32(math.Ceil(math.Log2(float64(largestValueWithSingleUnitResolution)))) - - subBucketHalfCountMagnitude := subBucketCountMagnitude - if subBucketHalfCountMagnitude < 1 { - subBucketHalfCountMagnitude = 1 - } - subBucketHalfCountMagnitude-- - - unitMagnitude := int32(math.Floor(math.Log2(float64(minValue)))) - if unitMagnitude < 0 { - unitMagnitude = 0 - } - - subBucketCount := int32(math.Pow(2, float64(subBucketHalfCountMagnitude)+1)) - - subBucketHalfCount := subBucketCount / 2 - subBucketMask := int64(subBucketCount-1) << uint(unitMagnitude) - - // determine exponent range needed to support the trackable value with no - // overflow: - smallestUntrackableValue := int64(subBucketCount) << uint(unitMagnitude) - bucketsNeeded := int32(1) - for smallestUntrackableValue < maxValue { - smallestUntrackableValue <<= 1 - bucketsNeeded++ - } - - bucketCount := bucketsNeeded - countsLen := (bucketCount + 1) * (subBucketCount / 2) - - return &Histogram{ - lowestTrackableValue: minValue, - highestTrackableValue: maxValue, - unitMagnitude: int64(unitMagnitude), - significantFigures: int64(sigfigs), - subBucketHalfCountMagnitude: subBucketHalfCountMagnitude, - subBucketHalfCount: subBucketHalfCount, - subBucketMask: subBucketMask, - subBucketCount: subBucketCount, - bucketCount: bucketCount, - countsLen: countsLen, - totalCount: 0, - counts: make([]int64, countsLen), - } -} - -// ByteSize returns an estimate of the amount of memory allocated to the -// histogram in bytes. -// -// N.B.: This does not take into account the overhead for slices, which are -// small, constant, and specific to the compiler version. -func (h *Histogram) ByteSize() int { - return 6*8 + 5*4 + len(h.counts)*8 -} - -// Merge merges the data stored in the given histogram with the receiver, -// returning the number of recorded values which had to be dropped. -func (h *Histogram) Merge(from *Histogram) (dropped int64) { - i := from.rIterator() - for i.next() { - v := i.valueFromIdx - c := i.countAtIdx - - if h.RecordValues(v, c) != nil { - dropped += c - } - } - - return -} - -// TotalCount returns total number of values recorded. -func (h *Histogram) TotalCount() int64 { - return h.totalCount -} - -// Max returns the approximate maximum recorded value. -func (h *Histogram) Max() int64 { - var max int64 - i := h.iterator() - for i.next() { - if i.countAtIdx != 0 { - max = i.highestEquivalentValue - } - } - return h.highestEquivalentValue(max) -} - -// Min returns the approximate minimum recorded value. -func (h *Histogram) Min() int64 { - var min int64 - i := h.iterator() - for i.next() { - if i.countAtIdx != 0 && min == 0 { - min = i.highestEquivalentValue - break - } - } - return h.lowestEquivalentValue(min) -} - -// Mean returns the approximate arithmetic mean of the recorded values. -func (h *Histogram) Mean() float64 { - if h.totalCount == 0 { - return 0 - } - var total int64 - i := h.iterator() - for i.next() { - if i.countAtIdx != 0 { - total += i.countAtIdx * h.medianEquivalentValue(i.valueFromIdx) - } - } - return float64(total) / float64(h.totalCount) -} - -// StdDev returns the approximate standard deviation of the recorded values. -func (h *Histogram) StdDev() float64 { - if h.totalCount == 0 { - return 0 - } - - mean := h.Mean() - geometricDevTotal := 0.0 - - i := h.iterator() - for i.next() { - if i.countAtIdx != 0 { - dev := float64(h.medianEquivalentValue(i.valueFromIdx)) - mean - geometricDevTotal += (dev * dev) * float64(i.countAtIdx) - } - } - - return math.Sqrt(geometricDevTotal / float64(h.totalCount)) -} - -// Reset deletes all recorded values and restores the histogram to its original -// state. -func (h *Histogram) Reset() { - h.totalCount = 0 - for i := range h.counts { - h.counts[i] = 0 - } -} - -// RecordValue records the given value, returning an error if the value is out -// of range. -func (h *Histogram) RecordValue(v int64) error { - return h.RecordValues(v, 1) -} - -// RecordCorrectedValue records the given value, correcting for stalls in the -// recording process. This only works for processes which are recording values -// at an expected interval (e.g., doing jitter analysis). Processes which are -// recording ad-hoc values (e.g., latency for incoming requests) can't take -// advantage of this. -func (h *Histogram) RecordCorrectedValue(v, expectedInterval int64) error { - if err := h.RecordValue(v); err != nil { - return err - } - - if expectedInterval <= 0 || v <= expectedInterval { - return nil - } - - missingValue := v - expectedInterval - for missingValue >= expectedInterval { - if err := h.RecordValue(missingValue); err != nil { - return err - } - missingValue -= expectedInterval - } - - return nil -} - -// RecordValues records n occurrences of the given value, returning an error if -// the value is out of range. -func (h *Histogram) RecordValues(v, n int64) error { - idx := h.countsIndexFor(v) - if idx < 0 || int(h.countsLen) <= idx { - return fmt.Errorf("value %d is too large to be recorded", v) - } - h.counts[idx] += n - h.totalCount += n - - return nil -} - -// ValueAtQuantile returns the recorded value at the given quantile (0..100). -func (h *Histogram) ValueAtQuantile(q float64) int64 { - if q > 100 { - q = 100 - } - - total := int64(0) - countAtPercentile := int64(((q / 100) * float64(h.totalCount)) + 0.5) - - i := h.iterator() - for i.next() { - total += i.countAtIdx - if total >= countAtPercentile { - return h.highestEquivalentValue(i.valueFromIdx) - } - } - - return 0 -} - -// CumulativeDistribution returns an ordered list of brackets of the -// distribution of recorded values. -func (h *Histogram) CumulativeDistribution() []Bracket { - var result []Bracket - - i := h.pIterator(1) - for i.next() { - result = append(result, Bracket{ - Quantile: i.percentile, - Count: i.countToIdx, - ValueAt: i.highestEquivalentValue, - }) - } - - return result -} - -// SignificantFigures returns the significant figures used to create the -// histogram -func (h *Histogram) SignificantFigures() int64 { - return h.significantFigures -} - -// LowestTrackableValue returns the lower bound on values that will be added -// to the histogram -func (h *Histogram) LowestTrackableValue() int64 { - return h.lowestTrackableValue -} - -// HighestTrackableValue returns the upper bound on values that will be added -// to the histogram -func (h *Histogram) HighestTrackableValue() int64 { - return h.highestTrackableValue -} - -// Histogram bar for plotting -type Bar struct { - From, To, Count int64 -} - -// Pretty print as csv for easy plotting -func (b Bar) String() string { - return fmt.Sprintf("%v, %v, %v\n", b.From, b.To, b.Count) -} - -// Distribution returns an ordered list of bars of the -// distribution of recorded values, counts can be normalized to a probability -func (h *Histogram) Distribution() (result []Bar) { - i := h.iterator() - for i.next() { - result = append(result, Bar{ - Count: i.countAtIdx, - From: h.lowestEquivalentValue(i.valueFromIdx), - To: i.highestEquivalentValue, - }) - } - - return result -} - -// Equals returns true if the two Histograms are equivalent, false if not. -func (h *Histogram) Equals(other *Histogram) bool { - switch { - case - h.lowestTrackableValue != other.lowestTrackableValue, - h.highestTrackableValue != other.highestTrackableValue, - h.unitMagnitude != other.unitMagnitude, - h.significantFigures != other.significantFigures, - h.subBucketHalfCountMagnitude != other.subBucketHalfCountMagnitude, - h.subBucketHalfCount != other.subBucketHalfCount, - h.subBucketMask != other.subBucketMask, - h.subBucketCount != other.subBucketCount, - h.bucketCount != other.bucketCount, - h.countsLen != other.countsLen, - h.totalCount != other.totalCount: - return false - default: - for i, c := range h.counts { - if c != other.counts[i] { - return false - } - } - } - return true -} - -// Export returns a snapshot view of the Histogram. This can be later passed to -// Import to construct a new Histogram with the same state. -func (h *Histogram) Export() *Snapshot { - return &Snapshot{ - LowestTrackableValue: h.lowestTrackableValue, - HighestTrackableValue: h.highestTrackableValue, - SignificantFigures: h.significantFigures, - Counts: append([]int64(nil), h.counts...), // copy - } -} - -// Import returns a new Histogram populated from the Snapshot data (which the -// caller must stop accessing). -func Import(s *Snapshot) *Histogram { - h := New(s.LowestTrackableValue, s.HighestTrackableValue, int(s.SignificantFigures)) - h.counts = s.Counts - totalCount := int64(0) - for i := int32(0); i < h.countsLen; i++ { - countAtIndex := h.counts[i] - if countAtIndex > 0 { - totalCount += countAtIndex - } - } - h.totalCount = totalCount - return h -} - -func (h *Histogram) iterator() *iterator { - return &iterator{ - h: h, - subBucketIdx: -1, - } -} - -func (h *Histogram) rIterator() *rIterator { - return &rIterator{ - iterator: iterator{ - h: h, - subBucketIdx: -1, - }, - } -} - -func (h *Histogram) pIterator(ticksPerHalfDistance int32) *pIterator { - return &pIterator{ - iterator: iterator{ - h: h, - subBucketIdx: -1, - }, - ticksPerHalfDistance: ticksPerHalfDistance, - } -} - -func (h *Histogram) sizeOfEquivalentValueRange(v int64) int64 { - bucketIdx := h.getBucketIndex(v) - subBucketIdx := h.getSubBucketIdx(v, bucketIdx) - adjustedBucket := bucketIdx - if subBucketIdx >= h.subBucketCount { - adjustedBucket++ - } - return int64(1) << uint(h.unitMagnitude+int64(adjustedBucket)) -} - -func (h *Histogram) valueFromIndex(bucketIdx, subBucketIdx int32) int64 { - return int64(subBucketIdx) << uint(int64(bucketIdx)+h.unitMagnitude) -} - -func (h *Histogram) lowestEquivalentValue(v int64) int64 { - bucketIdx := h.getBucketIndex(v) - subBucketIdx := h.getSubBucketIdx(v, bucketIdx) - return h.valueFromIndex(bucketIdx, subBucketIdx) -} - -func (h *Histogram) nextNonEquivalentValue(v int64) int64 { - return h.lowestEquivalentValue(v) + h.sizeOfEquivalentValueRange(v) -} - -func (h *Histogram) highestEquivalentValue(v int64) int64 { - return h.nextNonEquivalentValue(v) - 1 -} - -func (h *Histogram) medianEquivalentValue(v int64) int64 { - return h.lowestEquivalentValue(v) + (h.sizeOfEquivalentValueRange(v) >> 1) -} - -func (h *Histogram) getCountAtIndex(bucketIdx, subBucketIdx int32) int64 { - return h.counts[h.countsIndex(bucketIdx, subBucketIdx)] -} - -func (h *Histogram) countsIndex(bucketIdx, subBucketIdx int32) int32 { - bucketBaseIdx := (bucketIdx + 1) << uint(h.subBucketHalfCountMagnitude) - offsetInBucket := subBucketIdx - h.subBucketHalfCount - return bucketBaseIdx + offsetInBucket -} - -func (h *Histogram) getBucketIndex(v int64) int32 { - pow2Ceiling := bitLen(v | h.subBucketMask) - return int32(pow2Ceiling - int64(h.unitMagnitude) - - int64(h.subBucketHalfCountMagnitude+1)) -} - -func (h *Histogram) getSubBucketIdx(v int64, idx int32) int32 { - return int32(v >> uint(int64(idx)+int64(h.unitMagnitude))) -} - -func (h *Histogram) countsIndexFor(v int64) int { - bucketIdx := h.getBucketIndex(v) - subBucketIdx := h.getSubBucketIdx(v, bucketIdx) - return int(h.countsIndex(bucketIdx, subBucketIdx)) -} - -type iterator struct { - h *Histogram - bucketIdx, subBucketIdx int32 - countAtIdx, countToIdx, valueFromIdx int64 - highestEquivalentValue int64 -} - -func (i *iterator) next() bool { - if i.countToIdx >= i.h.totalCount { - return false - } - - // increment bucket - i.subBucketIdx++ - if i.subBucketIdx >= i.h.subBucketCount { - i.subBucketIdx = i.h.subBucketHalfCount - i.bucketIdx++ - } - - if i.bucketIdx >= i.h.bucketCount { - return false - } - - i.countAtIdx = i.h.getCountAtIndex(i.bucketIdx, i.subBucketIdx) - i.countToIdx += i.countAtIdx - i.valueFromIdx = i.h.valueFromIndex(i.bucketIdx, i.subBucketIdx) - i.highestEquivalentValue = i.h.highestEquivalentValue(i.valueFromIdx) - - return true -} - -type rIterator struct { - iterator - countAddedThisStep int64 -} - -func (r *rIterator) next() bool { - for r.iterator.next() { - if r.countAtIdx != 0 { - r.countAddedThisStep = r.countAtIdx - return true - } - } - return false -} - -type pIterator struct { - iterator - seenLastValue bool - ticksPerHalfDistance int32 - percentileToIteratorTo float64 - percentile float64 -} - -func (p *pIterator) next() bool { - if !(p.countToIdx < p.h.totalCount) { - if p.seenLastValue { - return false - } - - p.seenLastValue = true - p.percentile = 100 - - return true - } - - if p.subBucketIdx == -1 && !p.iterator.next() { - return false - } - - var done = false - for !done { - currentPercentile := (100.0 * float64(p.countToIdx)) / float64(p.h.totalCount) - if p.countAtIdx != 0 && p.percentileToIteratorTo <= currentPercentile { - p.percentile = p.percentileToIteratorTo - halfDistance := math.Trunc(math.Pow(2, math.Trunc(math.Log2(100.0/(100.0-p.percentileToIteratorTo)))+1)) - percentileReportingTicks := float64(p.ticksPerHalfDistance) * halfDistance - p.percentileToIteratorTo += 100.0 / percentileReportingTicks - return true - } - done = !p.iterator.next() - } - - return true -} - -func bitLen(x int64) (n int64) { - for ; x >= 0x8000; x >>= 16 { - n += 16 - } - if x >= 0x80 { - x >>= 8 - n += 8 - } - if x >= 0x8 { - x >>= 4 - n += 4 - } - if x >= 0x2 { - x >>= 2 - n += 2 - } - if x >= 0x1 { - n++ - } - return -} diff --git a/vendor/github.com/codahale/hdrhistogram/window.go b/vendor/github.com/codahale/hdrhistogram/window.go deleted file mode 100644 index dc43612a4..000000000 --- a/vendor/github.com/codahale/hdrhistogram/window.go +++ /dev/null @@ -1,45 +0,0 @@ -package hdrhistogram - -// A WindowedHistogram combines histograms to provide windowed statistics. -type WindowedHistogram struct { - idx int - h []Histogram - m *Histogram - - Current *Histogram -} - -// NewWindowed creates a new WindowedHistogram with N underlying histograms with -// the given parameters. -func NewWindowed(n int, minValue, maxValue int64, sigfigs int) *WindowedHistogram { - w := WindowedHistogram{ - idx: -1, - h: make([]Histogram, n), - m: New(minValue, maxValue, sigfigs), - } - - for i := range w.h { - w.h[i] = *New(minValue, maxValue, sigfigs) - } - w.Rotate() - - return &w -} - -// Merge returns a histogram which includes the recorded values from all the -// sections of the window. -func (w *WindowedHistogram) Merge() *Histogram { - w.m.Reset() - for _, h := range w.h { - w.m.Merge(&h) - } - return w.m -} - -// Rotate resets the oldest histogram and rotates it to be used as the current -// histogram. -func (w *WindowedHistogram) Rotate() { - w.idx++ - w.Current = &w.h[w.idx%len(w.h)] - w.Current.Reset() -} 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 ad61022ad..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy.go +++ /dev/null @@ -1,172 +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/ioutil" - "os" - "path/filepath" - "sync" - - "github.com/pkg/errors" -) - -var bufferPool = &sync.Pool{ - New: func() interface{} { - buffer := make([]byte, 32*1024) - return &buffer - }, -} - -// XAttrErrorHandlers 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 -} - -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) -} - -// 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 errors.Wrapf(err, "failed to stat %s", src) - } - if !stat.IsDir() { - return errors.Errorf("source is not directory") - } - - if st, err := os.Stat(dst); err != nil { - if err := os.Mkdir(dst, stat.Mode()); err != nil { - return errors.Wrapf(err, "failed to mkdir %s", dst) - } - } else if !st.IsDir() { - return errors.Errorf("cannot copy to non-directory: %s", dst) - } else { - if err := os.Chmod(dst, stat.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod on %s", dst) - } - } - - fis, err := ioutil.ReadDir(src) - if err != nil { - return errors.Wrapf(err, "failed to read %s", src) - } - - if err := copyFileInfo(stat, dst); err != nil { - return errors.Wrapf(err, "failed to copy file info for %s", dst) - } - - for _, fi := range fis { - source := filepath.Join(src, fi.Name()) - target := filepath.Join(dst, fi.Name()) - - switch { - case fi.IsDir(): - if err := copyDirectory(target, source, inodes, o); err != nil { - return err - } - continue - case (fi.Mode() & os.ModeType) == 0: - link, err := getLinkSource(target, fi, inodes) - if err != nil { - return errors.Wrap(err, "failed to get hardlink") - } - if link != "" { - if err := os.Link(link, target); err != nil { - return errors.Wrap(err, "failed to create hard link") - } - } else if err := CopyFile(target, source); err != nil { - return errors.Wrap(err, "failed to copy files") - } - case (fi.Mode() & os.ModeSymlink) == os.ModeSymlink: - link, err := os.Readlink(source) - if err != nil { - return errors.Wrapf(err, "failed to read link: %s", source) - } - if err := os.Symlink(link, target); err != nil { - return errors.Wrapf(err, "failed to create symlink: %s", target) - } - case (fi.Mode() & os.ModeDevice) == os.ModeDevice: - if err := copyDevice(target, fi); err != nil { - return errors.Wrapf(err, "failed to create device") - } - default: - // TODO: Support pipes and sockets - return errors.Wrapf(err, "unsupported mode %s", fi.Mode()) - } - if err := copyFileInfo(fi, target); err != nil { - return errors.Wrap(err, "failed to copy file info") - } - - if err := copyXAttrs(target, source, o.xeh); err != nil { - return errors.Wrap(err, "failed to copy xattrs") - } - } - - return nil -} - -// 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 { - src, err := os.Open(source) - if err != nil { - return errors.Wrapf(err, "failed to open source %s", source) - } - defer src.Close() - tgt, err := os.Create(target) - if err != nil { - return errors.Wrapf(err, "failed to open target %s", target) - } - defer tgt.Close() - - return copyFileContent(tgt, src) -} 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 81c71522a..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_linux.go +++ /dev/null @@ -1,144 +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" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func copyFileInfo(fi os.FileInfo, 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 errors.Wrapf(err, "failed to chown %s", name) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - } - - timespec := []unix.Timespec{unix.Timespec(StatAtime(st)), unix.Timespec(StatMtime(st))} - if err := unix.UtimesNanoAt(unix.AT_FDCWD, name, timespec, unix.AT_SYMLINK_NOFOLLOW); err != nil { - return errors.Wrapf(err, "failed to utime %s", name) - } - - return nil -} - -const maxSSizeT = int64(^uint(0) >> 1) - -func copyFileContent(dst, src *os.File) error { - st, err := src.Stat() - if err != nil { - return errors.Wrap(err, "unable to stat source") - } - - size := st.Size() - first := true - srcFd := int(src.Fd()) - dstFd := int(dst.Fd()) - - for size > 0 { - // Ensure that we are never trying to copy more than SSIZE_MAX at a - // time and at the same time avoids overflows when the file is larger - // than 4GB on 32-bit systems. - var copySize int - if size > maxSSizeT { - copySize = int(maxSSizeT) - } else { - copySize = int(size) - } - n, err := unix.CopyFileRange(srcFd, nil, dstFd, nil, copySize, 0) - if err != nil { - if (err != unix.ENOSYS && err != unix.EXDEV) || !first { - return errors.Wrap(err, "copy file range failed") - } - - buf := bufferPool.Get().(*[]byte) - _, err = io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - return errors.Wrap(err, "userspace copy failed") - } - - first = false - size -= int64(n) - } - - return nil -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - e := errors.Wrapf(err, "failed to list xattrs on %s", src) - if xeh != nil { - e = xeh(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} - -func copyDevice(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("unsupported stat type") - } - return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev)) -} 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 73c01a46d..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_unix.go +++ /dev/null @@ -1,112 +0,0 @@ -// +build solaris 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 fs - -import ( - "io" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func copyFileInfo(fi os.FileInfo, 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 errors.Wrapf(err, "failed to chown %s", name) - } - } - - if (fi.Mode() & os.ModeSymlink) != os.ModeSymlink { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - } - - timespec := []syscall.Timespec{StatAtime(st), StatMtime(st)} - if err := syscall.UtimesNano(name, timespec); err != nil { - return errors.Wrapf(err, "failed to utime %s", name) - } - - return nil -} - -func copyFileContent(dst, src *os.File) error { - buf := bufferPool.Get().(*[]byte) - _, err := io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - - return err -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - xattrKeys, err := sysx.LListxattr(src) - if err != nil { - e := errors.Wrapf(err, "failed to list xattrs on %s", src) - if xeh != nil { - e = xeh(dst, src, "", e) - } - return e - } - for _, xattr := range xattrKeys { - data, err := sysx.LGetxattr(src, xattr) - if err != nil { - e := errors.Wrapf(err, "failed to get xattr %q on %s", xattr, src) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - if err := sysx.LSetxattr(dst, xattr, data, 0); err != nil { - e := errors.Wrapf(err, "failed to set xattr %q on %s", xattr, dst) - if xeh != nil { - if e = xeh(dst, src, xattr, e); e == nil { - continue - } - } - return e - } - } - - return nil -} - -func copyDevice(dst string, fi os.FileInfo) error { - st, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return errors.New("unsupported stat type") - } - return unix.Mknod(dst, uint32(fi.Mode()), int(st.Rdev)) -} 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 27c7d7dbb..000000000 --- a/vendor/github.com/containerd/continuity/fs/copy_windows.go +++ /dev/null @@ -1,49 +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" - - "github.com/pkg/errors" -) - -func copyFileInfo(fi os.FileInfo, name string) error { - if err := os.Chmod(name, fi.Mode()); err != nil { - return errors.Wrapf(err, "failed to chmod %s", name) - } - - // TODO: copy windows specific metadata - - return nil -} - -func copyFileContent(dst, src *os.File) error { - buf := bufferPool.Get().(*[]byte) - _, err := io.CopyBuffer(dst, src, *buf) - bufferPool.Put(buf) - return err -} - -func copyXAttrs(dst, src string, xeh XAttrErrorHandler) error { - return nil -} - -func copyDevice(dst string, fi os.FileInfo) error { - return errors.New("device 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 e64f9e73d..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" - - "golang.org/x/sync/errgroup" - - "github.com/sirupsen/logrus" -) - -// 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 7913af27d..000000000 --- a/vendor/github.com/containerd/continuity/fs/diff_unix.go +++ /dev/null @@ -1,74 +0,0 @@ -// +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" - "os" - "syscall" - - "github.com/containerd/continuity/sysx" - "github.com/pkg/errors" -) - -// 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, errors.Wrapf(err, "failed to get xattr for %s", p1) - } - c2, err := sysx.LGetxattr(p2, "security.capability") - if err != nil && err != sysx.ENODATA { - return false, errors.Wrapf(err, "failed to get xattr for %s", p2) - } - 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/dtype_linux.go b/vendor/github.com/containerd/continuity/fs/dtype_linux.go deleted file mode 100644 index 10510d8de..000000000 --- a/vendor/github.com/containerd/continuity/fs/dtype_linux.go +++ /dev/null @@ -1,103 +0,0 @@ -// +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" - "io/ioutil" - "os" - "syscall" - "unsafe" -) - -func locateDummyIfEmpty(path string) (string, error) { - children, err := ioutil.ReadDir(path) - if err != nil { - return "", err - } - if len(children) != 0 { - return "", nil - } - dummyFile, err := ioutil.TempFile(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 e22ffbea3..000000000 --- a/vendor/github.com/containerd/continuity/fs/du_unix.go +++ /dev/null @@ -1,110 +0,0 @@ -// +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" -) - -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 is uint32 on darwin/bsd, uint64 on linux/solaris - dev: uint64(stat.Dev), // nolint: unconvert - // Ino is uint32 on bsd, uint64 on darwin/linux/solaris - ino: uint64(stat.Ino), // nolint: unconvert - } -} - -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: - } - - inoKey := newInode(fi.Sys().(*syscall.Stat_t)) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += fi.Size() - } - - 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 { - inoKey := newInode(fi.Sys().(*syscall.Stat_t)) - if _, ok := inodes[inoKey]; !ok { - inodes[inoKey] = struct{}{} - size += fi.Size() - } - - 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 8f25ec59c..000000000 --- a/vendor/github.com/containerd/continuity/fs/du_windows.go +++ /dev/null @@ -1,82 +0,0 @@ -// +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 f95f0904c..000000000 --- a/vendor/github.com/containerd/continuity/fs/hardlink_unix.go +++ /dev/null @@ -1,34 +0,0 @@ -// +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 - } - - // Ino is uint32 on bsd, uint64 on darwin/linux/solaris - return uint64(s.Ino), !fi.IsDir() && s.Nlink > 1 // nolint: unconvert -} 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 8863caa9d..000000000 --- a/vendor/github.com/containerd/continuity/fs/path.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 fs - -import ( - "bytes" - "context" - "io" - "os" - "path/filepath" - - "github.com/pkg/errors" -) - -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 { - var eq bool - if (f1.f.Mode() & os.ModeSymlink) == os.ModeSymlink { - eq, err = compareSymlinkTarget(f1.fullPath, f2.fullPath) - } else if f1.f.Size() > 0 { - eq, err = compareFileContent(f1.fullPath, f2.fullPath) - } - if err != nil || !eq { - return eq, err - } - } 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_bsd.go b/vendor/github.com/containerd/continuity/fs/stat_bsd.go deleted file mode 100644 index cb7400a33..000000000 --- a/vendor/github.com/containerd/continuity/fs/stat_bsd.go +++ /dev/null @@ -1,44 +0,0 @@ -// +build 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 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(int64(st.Atimespec.Sec), int64(st.Atimespec.Nsec)) // nolint: unconvert -} diff --git a/vendor/github.com/containerd/continuity/fs/stat_linux.go b/vendor/github.com/containerd/continuity/fs/stat_linux.go deleted file mode 100644 index 4a678dd1f..000000000 --- a/vendor/github.com/containerd/continuity/fs/stat_linux.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 ( - "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 { - // The int64 conversions ensure the line compiles for 32-bit systems as well. - return time.Unix(int64(st.Atim.Sec), int64(st.Atim.Nsec)) // nolint: unconvert -} 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/pathdriver/path_driver.go b/vendor/github.com/containerd/continuity/pathdriver/path_driver.go deleted file mode 100644 index b0d5a6b56..000000000 --- a/vendor/github.com/containerd/continuity/pathdriver/path_driver.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 pathdriver - -import ( - "path/filepath" -) - -// PathDriver provides all of the path manipulation functions in a common -// interface. The context should call these and never use the `filepath` -// package or any other package to manipulate paths. -type PathDriver interface { - Join(paths ...string) string - IsAbs(path string) bool - Rel(base, target string) (string, error) - Base(path string) string - Dir(path string) string - Clean(path string) string - Split(path string) (dir, file string) - Separator() byte - Abs(path string) (string, error) - Walk(string, filepath.WalkFunc) error - FromSlash(path string) string - ToSlash(path string) string - Match(pattern, name string) (matched bool, err error) -} - -// pathDriver is a simple default implementation calls the filepath package. -type pathDriver struct{} - -// LocalPathDriver is the exported pathDriver struct for convenience. -var LocalPathDriver PathDriver = &pathDriver{} - -func (*pathDriver) Join(paths ...string) string { - return filepath.Join(paths...) -} - -func (*pathDriver) IsAbs(path string) bool { - return filepath.IsAbs(path) -} - -func (*pathDriver) Rel(base, target string) (string, error) { - return filepath.Rel(base, target) -} - -func (*pathDriver) Base(path string) string { - return filepath.Base(path) -} - -func (*pathDriver) Dir(path string) string { - return filepath.Dir(path) -} - -func (*pathDriver) Clean(path string) string { - return filepath.Clean(path) -} - -func (*pathDriver) Split(path string) (dir, file string) { - return filepath.Split(path) -} - -func (*pathDriver) Separator() byte { - return filepath.Separator -} - -func (*pathDriver) Abs(path string) (string, error) { - return filepath.Abs(path) -} - -// Note that filepath.Walk calls os.Stat, so if the context wants to -// to call Driver.Stat() for Walk, they need to create a new struct that -// overrides this method. -func (*pathDriver) Walk(root string, walkFn filepath.WalkFunc) error { - return filepath.Walk(root, walkFn) -} - -func (*pathDriver) FromSlash(path string) string { - return filepath.FromSlash(path) -} - -func (*pathDriver) ToSlash(path string) string { - return filepath.ToSlash(path) -} - -func (*pathDriver) Match(pattern, name string) (bool, error) { - return filepath.Match(pattern, name) -} diff --git a/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go b/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go deleted file mode 100644 index 0bfa6a040..000000000 --- a/vendor/github.com/containerd/continuity/syscallx/syscall_unix.go +++ /dev/null @@ -1,26 +0,0 @@ -// +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 syscallx - -import "syscall" - -// Readlink returns the destination of the named symbolic link. -func Readlink(path string, buf []byte) (n int, err error) { - return syscall.Readlink(path, buf) -} diff --git a/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go b/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go deleted file mode 100644 index 2ba814990..000000000 --- a/vendor/github.com/containerd/continuity/syscallx/syscall_windows.go +++ /dev/null @@ -1,112 +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 syscallx - -import ( - "syscall" - "unsafe" -) - -type reparseDataBuffer struct { - ReparseTag uint32 - ReparseDataLength uint16 - Reserved uint16 - - // GenericReparseBuffer - reparseBuffer byte -} - -type mountPointReparseBuffer struct { - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - PathBuffer [1]uint16 -} - -type symbolicLinkReparseBuffer struct { - SubstituteNameOffset uint16 - SubstituteNameLength uint16 - PrintNameOffset uint16 - PrintNameLength uint16 - Flags uint32 - PathBuffer [1]uint16 -} - -const ( - _IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003 - _SYMLINK_FLAG_RELATIVE = 1 -) - -// Readlink returns the destination of the named symbolic link. -func Readlink(path string, buf []byte) (n int, err error) { - fd, err := syscall.CreateFile(syscall.StringToUTF16Ptr(path), syscall.GENERIC_READ, 0, nil, syscall.OPEN_EXISTING, - syscall.FILE_FLAG_OPEN_REPARSE_POINT|syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) - if err != nil { - return -1, err - } - defer syscall.CloseHandle(fd) - - rdbbuf := make([]byte, syscall.MAXIMUM_REPARSE_DATA_BUFFER_SIZE) - var bytesReturned uint32 - err = syscall.DeviceIoControl(fd, syscall.FSCTL_GET_REPARSE_POINT, nil, 0, &rdbbuf[0], uint32(len(rdbbuf)), &bytesReturned, nil) - if err != nil { - return -1, err - } - - rdb := (*reparseDataBuffer)(unsafe.Pointer(&rdbbuf[0])) - var s string - switch rdb.ReparseTag { - case syscall.IO_REPARSE_TAG_SYMLINK: - data := (*symbolicLinkReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) - p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) - s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2]) - if data.Flags&_SYMLINK_FLAG_RELATIVE == 0 { - if len(s) >= 4 && s[:4] == `\??\` { - s = s[4:] - switch { - case len(s) >= 2 && s[1] == ':': // \??\C:\foo\bar - // do nothing - case len(s) >= 4 && s[:4] == `UNC\`: // \??\UNC\foo\bar - s = `\\` + s[4:] - default: - // unexpected; do nothing - } - } else { - // unexpected; do nothing - } - } - case _IO_REPARSE_TAG_MOUNT_POINT: - data := (*mountPointReparseBuffer)(unsafe.Pointer(&rdb.reparseBuffer)) - p := (*[0xffff]uint16)(unsafe.Pointer(&data.PathBuffer[0])) - s = syscall.UTF16ToString(p[data.SubstituteNameOffset/2 : (data.SubstituteNameOffset+data.SubstituteNameLength)/2]) - if len(s) >= 4 && s[:4] == `\??\` { // \??\C:\foo\bar - if len(s) < 48 || s[:11] != `\??\Volume{` { - s = s[4:] - } - } else { - // unexpected; do nothing - } - default: - // the path is not a symlink or junction but another type of reparse - // point - return -1, syscall.ENOENT - } - n = copy(buf, []byte(s)) - - return n, nil -} diff --git a/vendor/github.com/containerd/continuity/sysx/file_posix.go b/vendor/github.com/containerd/continuity/sysx/file_posix.go deleted file mode 100644 index e28f3a1b5..000000000 --- a/vendor/github.com/containerd/continuity/sysx/file_posix.go +++ /dev/null @@ -1,128 +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 ( - "os" - "path/filepath" - - "github.com/containerd/continuity/syscallx" -) - -// Readlink returns the destination of the named symbolic link. -// If there is an error, it will be of type *PathError. -func Readlink(name string) (string, error) { - for len := 128; ; len *= 2 { - b := make([]byte, len) - n, e := fixCount(syscallx.Readlink(fixLongPath(name), b)) - if e != nil { - return "", &os.PathError{Op: "readlink", Path: name, Err: e} - } - if n < len { - return string(b[0:n]), nil - } - } -} - -// Many functions in package syscall return a count of -1 instead of 0. -// Using fixCount(call()) instead of call() corrects the count. -func fixCount(n int, err error) (int, error) { - if n < 0 { - n = 0 - } - return n, err -} - -// fixLongPath returns the extended-length (\\?\-prefixed) form of -// path when needed, in order to avoid the default 260 character file -// path limit imposed by Windows. If path is not easily converted to -// the extended-length form (for example, if path is a relative path -// or contains .. elements), or is short enough, fixLongPath returns -// path unmodified. -// -// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath -func fixLongPath(path string) string { - // Do nothing (and don't allocate) if the path is "short". - // Empirically (at least on the Windows Server 2013 builder), - // the kernel is arbitrarily okay with < 248 bytes. That - // matches what the docs above say: - // "When using an API to create a directory, the specified - // path cannot be so long that you cannot append an 8.3 file - // name (that is, the directory name cannot exceed MAX_PATH - // minus 12)." Since MAX_PATH is 260, 260 - 12 = 248. - // - // The MSDN docs appear to say that a normal path that is 248 bytes long - // will work; empirically the path must be less then 248 bytes long. - if len(path) < 248 { - // Don't fix. (This is how Go 1.7 and earlier worked, - // not automatically generating the \\?\ form) - return path - } - - // The extended form begins with \\?\, as in - // \\?\c:\windows\foo.txt or \\?\UNC\server\share\foo.txt. - // The extended form disables evaluation of . and .. path - // elements and disables the interpretation of / as equivalent - // to \. The conversion here rewrites / to \ and elides - // . elements as well as trailing or duplicate separators. For - // simplicity it avoids the conversion entirely for relative - // paths or paths containing .. elements. For now, - // \\server\share paths are not converted to - // \\?\UNC\server\share paths because the rules for doing so - // are less well-specified. - if len(path) >= 2 && path[:2] == `\\` { - // Don't canonicalize UNC paths. - return path - } - if !filepath.IsAbs(path) { - // Relative path - return path - } - - const prefix = `\\?` - - pathbuf := make([]byte, len(prefix)+len(path)+len(`\`)) - copy(pathbuf, prefix) - n := len(path) - r, w := 0, len(prefix) - for r < n { - switch { - case os.IsPathSeparator(path[r]): - // empty block - r++ - case path[r] == '.' && (r+1 == n || os.IsPathSeparator(path[r+1])): - // /./ - r++ - case r+1 < n && path[r] == '.' && path[r+1] == '.' && (r+2 == n || os.IsPathSeparator(path[r+2])): - // /../ is currently unhandled - return path - default: - pathbuf[w] = '\\' - w++ - for ; r < n && !os.IsPathSeparator(path[r]); r++ { - pathbuf[w] = path[r] - w++ - } - } - } - // A drive's root directory needs a trailing \ - if w == len(`\\?\c:`) { - pathbuf[w] = '\\' - w++ - } - return string(pathbuf[:w]) -} 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 b26f5b3d0..000000000 --- a/vendor/github.com/containerd/continuity/sysx/nodata_unix.go +++ /dev/null @@ -1,25 +0,0 @@ -// +build 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 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 9e4326dcf..000000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr.go +++ /dev/null @@ -1,125 +0,0 @@ -// +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" - "syscall" - - "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 = 5 - -type listxattrFunc func(path string, dest []byte) (int, error) - -func listxattrAll(path string, listFunc listxattrFunc) ([]string, error) { - var p []byte // nil on first execution - - for { - n, err := listFunc(path, p) // first call gets buffer size. - if err != nil { - return nil, err - } - - if n > len(p) { - p = make([]byte, n) - continue - } - - p = p[:n] - - ps := bytes.Split(bytes.TrimSuffix(p, []byte{0}), []byte{0}) - var entries []string - for _, p := range ps { - s := string(p) - if s != "" { - entries = append(entries, s) - } - } - - return entries, nil - } -} - -type getxattrFunc func(string, string, []byte) (int, error) - -func getxattrAll(path, attr string, getFunc getxattrFunc) ([]byte, error) { - p := make([]byte, defaultXattrBufferSize) - for { - n, err := getFunc(path, attr, p) - if err != nil { - if errno, ok := err.(syscall.Errno); ok && errno == syscall.ERANGE { - p = make([]byte, len(p)*2) // this can't be ideal. - continue // try again! - } - - return nil, err - } - - // realloc to correct size and repeat - if n > len(p) { - p = make([]byte, n) - continue - } - - return p[: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 c9ef3a1d2..000000000 --- a/vendor/github.com/containerd/continuity/sysx/xattr_unsupported.go +++ /dev/null @@ -1,67 +0,0 @@ -// +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 unsupported = 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 unsupported -} - -// Setxattr calls syscall setxattr -func Setxattr(path string, attr string, data []byte, flags int) (err error) { - return unsupported -} - -// Getxattr calls syscall getxattr -func Getxattr(path, attr string) ([]byte, error) { - return []byte{}, unsupported -} - -// 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 unsupported -} - -// LSetxattr sets an xattr, not following symlinks -func LSetxattr(path string, attr string, data []byte, flags int) (err error) { - return unsupported -} - -// LGetxattr gets an xattr, not following symlinks -func LGetxattr(path, attr string) ([]byte, error) { - return []byte{}, nil -} diff --git a/vendor/github.com/containous/alice/LICENSE b/vendor/github.com/containous/alice/LICENSE deleted file mode 100644 index 0d0d352ec..000000000 --- a/vendor/github.com/containous/alice/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Justinas Stankevicius - -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/containous/alice/chain.go b/vendor/github.com/containous/alice/chain.go deleted file mode 100644 index 3bd132120..000000000 --- a/vendor/github.com/containous/alice/chain.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package alice provides a convenient way to chain http handlers. -package alice - -import "net/http" - -// Constructor A constructor for a piece of middleware. -// Some middleware use this constructor out of the box, -// so in most cases you can just pass somepackage.New -type Constructor func(http.Handler) (http.Handler, error) - -// Chain acts as a list of http.Handler constructors. -// Chain is effectively immutable: -// once created, it will always hold -// the same set of constructors in the same order. -type Chain struct { - constructors []Constructor -} - -// New creates a new chain, -// memorizing the given list of middleware constructors. -// New serves no other function, -// constructors are only called upon a call to Then(). -func New(constructors ...Constructor) Chain { - return Chain{constructors: constructors} -} - -// Then chains the middleware and returns the final http.Handler. -// New(m1, m2, m3).Then(h) -// is equivalent to: -// m1(m2(m3(h))) -// When the request comes in, it will be passed to m1, then m2, then m3 -// and finally, the given handler -// (assuming every middleware calls the following one). -// -// A chain can be safely reused by calling Then() several times. -// stdStack := alice.New(ratelimitHandler, csrfHandler) -// indexPipe = stdStack.Then(indexHandler) -// authPipe = stdStack.Then(authHandler) -// Note that constructors are called on every call to Then() -// and thus several instances of the same middleware will be created -// when a chain is reused in this way. -// For proper middleware, this should cause no problems. -// -// Then() treats nil as http.DefaultServeMux. -func (c Chain) Then(h http.Handler) (http.Handler, error) { - if h == nil { - h = http.DefaultServeMux - } - - for i := range c.constructors { - handler, err := c.constructors[len(c.constructors)-1-i](h) - if err != nil { - return nil, err - } - h = handler - } - - return h, nil -} - -// ThenFunc works identically to Then, but takes -// a HandlerFunc instead of a Handler. -// -// The following two statements are equivalent: -// c.Then(http.HandlerFunc(fn)) -// c.ThenFunc(fn) -// -// ThenFunc provides all the guarantees of Then. -func (c Chain) ThenFunc(fn http.HandlerFunc) (http.Handler, error) { - if fn == nil { - return c.Then(nil) - } - return c.Then(fn) -} - -// Append extends a chain, adding the specified constructors -// as the last ones in the request flow. -// -// Append returns a new chain, leaving the original one untouched. -// -// stdChain := alice.New(m1, m2) -// extChain := stdChain.Append(m3, m4) -// // requests in stdChain go m1 -> m2 -// // requests in extChain go m1 -> m2 -> m3 -> m4 -func (c Chain) Append(constructors ...Constructor) Chain { - newCons := make([]Constructor, 0, len(c.constructors)+len(constructors)) - newCons = append(newCons, c.constructors...) - newCons = append(newCons, constructors...) - - return Chain{newCons} -} - -// Extend extends a chain by adding the specified chain -// as the last one in the request flow. -// -// Extend returns a new chain, leaving the original one untouched. -// -// stdChain := alice.New(m1, m2) -// ext1Chain := alice.New(m3, m4) -// ext2Chain := stdChain.Extend(ext1Chain) -// // requests in stdChain go m1 -> m2 -// // requests in ext1Chain go m3 -> m4 -// // requests in ext2Chain go m1 -> m2 -> m3 -> m4 -// -// Another example: -// aHtmlAfterNosurf := alice.New(m2) -// aHtml := alice.New(m1, func(h http.Handler) http.Handler { -// csrf := nosurf.New(h) -// csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail)) -// return csrf -// }).Extend(aHtmlAfterNosurf) -// // requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler -// // requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail -func (c Chain) Extend(chain Chain) Chain { - return c.Append(chain.constructors...) -} diff --git a/vendor/github.com/containous/mux/LICENSE b/vendor/github.com/containous/mux/LICENSE deleted file mode 100644 index 0e5fb8728..000000000 --- a/vendor/github.com/containous/mux/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2012 Rodrigo Moraes. 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/containous/mux/context_gorilla.go b/vendor/github.com/containous/mux/context_gorilla.go deleted file mode 100644 index d7adaa8fa..000000000 --- a/vendor/github.com/containous/mux/context_gorilla.go +++ /dev/null @@ -1,26 +0,0 @@ -// +build !go1.7 - -package mux - -import ( - "net/http" - - "github.com/gorilla/context" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return context.Get(r, key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - context.Set(r, key, val) - return r -} - -func contextClear(r *http.Request) { - context.Clear(r) -} diff --git a/vendor/github.com/containous/mux/context_native.go b/vendor/github.com/containous/mux/context_native.go deleted file mode 100644 index 209cbea7d..000000000 --- a/vendor/github.com/containous/mux/context_native.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build go1.7 - -package mux - -import ( - "context" - "net/http" -) - -func contextGet(r *http.Request, key interface{}) interface{} { - return r.Context().Value(key) -} - -func contextSet(r *http.Request, key, val interface{}) *http.Request { - if val == nil { - return r - } - - return r.WithContext(context.WithValue(r.Context(), key, val)) -} - -func contextClear(r *http.Request) { - return -} diff --git a/vendor/github.com/containous/mux/doc.go b/vendor/github.com/containous/mux/doc.go deleted file mode 100644 index 3fab182ea..000000000 --- a/vendor/github.com/containous/mux/doc.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux implements a request router and dispatcher. - -The name mux stands for "HTTP request multiplexer". Like the standard -http.ServeMux, mux.Router matches incoming requests against a list of -registered routes and calls a handler for the route that matches the URL -or other conditions. The main features are: - - * Requests can be matched based on URL host, path, path prefix, schemes, - header and query values, HTTP methods or using custom matchers. - * URL hosts, paths and query values can have variables with an optional - regular expression. - * Registered URLs can be built, or "reversed", which helps maintaining - references to resources. - * Routes can be used as subrouters: nested routes are only tested if the - parent route matches. This is useful to define groups of routes that - share common conditions like a host, a path prefix or other repeated - attributes. As a bonus, this optimizes request matching. - * It implements the http.Handler interface so it is compatible with the - standard http.ServeMux. - -Let's start registering a couple of URL paths and handlers: - - func main() { - r := mux.NewRouter() - r.HandleFunc("/", HomeHandler) - r.HandleFunc("/products", ProductsHandler) - r.HandleFunc("/articles", ArticlesHandler) - http.Handle("/", r) - } - -Here we register three routes mapping URL paths to handlers. This is -equivalent to how http.HandleFunc() works: if an incoming request URL matches -one of the paths, the corresponding handler is called passing -(http.ResponseWriter, *http.Request) as parameters. - -Paths can have variables. They are defined using the format {name} or -{name:pattern}. If a regular expression pattern is not defined, the matched -variable will be anything until the next slash. For example: - - r := mux.NewRouter() - r.HandleFunc("/products/{key}", ProductHandler) - r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) - -Groups can be used inside patterns, as long as they are non-capturing (?:re). For example: - - r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler) - -The names are used to create a map of route variables which can be retrieved -calling mux.Vars(): - - vars := mux.Vars(request) - category := vars["category"] - -And this is all you need to know about the basic usage. More advanced options -are explained below. - -Routes can also be restricted to a domain or subdomain. Just define a host -pattern to be matched. They can also have variables: - - r := mux.NewRouter() - // Only matches if domain is "www.example.com". - r.Host("www.example.com") - // Matches a dynamic subdomain. - r.Host("{subdomain:[a-z]+}.domain.com") - -There are several other matchers that can be added. To match path prefixes: - - r.PathPrefix("/products/") - -...or HTTP methods: - - r.Methods("GET", "POST") - -...or URL schemes: - - r.Schemes("https") - -...or header values: - - r.Headers("X-Requested-With", "XMLHttpRequest") - -...or query values: - - r.Queries("key", "value") - -...or to use a custom matcher function: - - r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { - return r.ProtoMajor == 0 - }) - -...and finally, it is possible to combine several matchers in a single route: - - r.HandleFunc("/products", ProductsHandler). - Host("www.example.com"). - Methods("GET"). - Schemes("http") - -Setting the same matching conditions again and again can be boring, so we have -a way to group several routes that share the same requirements. -We call it "subrouting". - -For example, let's say we have several URLs that should only match when the -host is "www.example.com". Create a route for that host and get a "subrouter" -from it: - - r := mux.NewRouter() - s := r.Host("www.example.com").Subrouter() - -Then register routes in the subrouter: - - s.HandleFunc("/products/", ProductsHandler) - s.HandleFunc("/products/{key}", ProductHandler) - s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) - -The three URL paths we registered above will only be tested if the domain is -"www.example.com", because the subrouter is tested first. This is not -only convenient, but also optimizes request matching. You can create -subrouters combining any attribute matchers accepted by a route. - -Subrouters can be used to create domain or path "namespaces": you define -subrouters in a central place and then parts of the app can register its -paths relatively to a given subrouter. - -There's one more thing about subroutes. When a subrouter has a path prefix, -the inner routes use it as base for their paths: - - r := mux.NewRouter() - s := r.PathPrefix("/products").Subrouter() - // "/products/" - s.HandleFunc("/", ProductsHandler) - // "/products/{key}/" - s.HandleFunc("/{key}/", ProductHandler) - // "/products/{key}/details" - s.HandleFunc("/{key}/details", ProductDetailsHandler) - -Note that the path provided to PathPrefix() represents a "wildcard": calling -PathPrefix("/static/").Handler(...) means that the handler will be passed any -request that matches "/static/*". This makes it easy to serve static files with mux: - - func main() { - var dir string - - flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") - flag.Parse() - r := mux.NewRouter() - - // This will serve files under http://localhost:8000/static/ - r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) - - srv := &http.Server{ - Handler: r, - Addr: "127.0.0.1:8000", - // Good practice: enforce timeouts for servers you create! - WriteTimeout: 15 * time.Second, - ReadTimeout: 15 * time.Second, - } - - log.Fatal(srv.ListenAndServe()) - } - -Now let's see how to build registered URLs. - -Routes can be named. All routes that define a name can have their URLs built, -or "reversed". We define a name calling Name() on a route. For example: - - r := mux.NewRouter() - r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). - Name("article") - -To build a URL, get the route and call the URL() method, passing a sequence of -key/value pairs for the route variables. For the previous route, we would do: - - url, err := r.Get("article").URL("category", "technology", "id", "42") - -...and the result will be a url.URL with the following path: - - "/articles/technology/42" - -This also works for host and query value variables: - - r := mux.NewRouter() - r.Host("{subdomain}.domain.com"). - Path("/articles/{category}/{id:[0-9]+}"). - Queries("filter", "{filter}"). - HandlerFunc(ArticleHandler). - Name("article") - - // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42", - "filter", "gorilla") - -All variables defined in the route are required, and their values must -conform to the corresponding patterns. These requirements guarantee that a -generated URL will always match a registered route -- the only exception is -for explicitly defined "build-only" routes which never match. - -Regex support also exists for matching Headers within a route. For example, we could do: - - r.HeadersRegexp("Content-Type", "application/(text|json)") - -...and the route will match both requests with a Content-Type of `application/json` as well as -`application/text` - -There's also a way to build only the URL host or path for a route: -use the methods URLHost() or URLPath() instead. For the previous route, -we would do: - - // "http://news.domain.com/" - host, err := r.Get("article").URLHost("subdomain", "news") - - // "/articles/technology/42" - path, err := r.Get("article").URLPath("category", "technology", "id", "42") - -And if you use subrouters, host and path defined separately can be built -as well: - - r := mux.NewRouter() - s := r.Host("{subdomain}.domain.com").Subrouter() - s.Path("/articles/{category}/{id:[0-9]+}"). - HandlerFunc(ArticleHandler). - Name("article") - - // "http://news.domain.com/articles/technology/42" - url, err := r.Get("article").URL("subdomain", "news", - "category", "technology", - "id", "42") -*/ -package mux diff --git a/vendor/github.com/containous/mux/mux.go b/vendor/github.com/containous/mux/mux.go deleted file mode 100644 index 91faff120..000000000 --- a/vendor/github.com/containous/mux/mux.go +++ /dev/null @@ -1,569 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "path" - "regexp" - "sort" -) - -var ( - ErrMethodMismatch = errors.New("method is not allowed") -) - -// NewRouter returns a new router instance. -func NewRouter() *Router { - return &Router{namedRoutes: make(map[string]*Route), KeepContext: false} -} - -// Router registers routes to be matched and dispatches a handler. -// -// It implements the http.Handler interface, so it can be registered to serve -// requests: -// -// var router = mux.NewRouter() -// -// func main() { -// http.Handle("/", router) -// } -// -// Or, for Google App Engine, register it in a init() function: -// -// func init() { -// http.Handle("/", router) -// } -// -// This will send all incoming requests to the router. -type Router struct { - // Configurable Handler to be used when no route matches. - NotFoundHandler http.Handler - - // Configurable Handler to be used when the request method does not match the route. - MethodNotAllowedHandler http.Handler - - // Parent route, if this is a subrouter. - parent parentRoute - // Routes to be matched, in order. - routes []*Route - // Routes by name for URL building. - namedRoutes map[string]*Route - // See Router.StrictSlash(). This defines the flag for new routes. - strictSlash bool - // See Router.SkipClean(). This defines the flag for new routes. - skipClean bool - // If true, do not clear the request context after handling the request. - // This has no effect when go1.7+ is used, since the context is stored - // on the request itself. - KeepContext bool - // see Router.UseEncodedPath(). This defines a flag for all routes. - useEncodedPath bool -} - -// Match matches registered routes against the request. -func (r *Router) Match(req *http.Request, match *RouteMatch) bool { - for _, route := range r.routes { - if route.Match(req, match) { - return true - } - } - - if match.MatchErr == ErrMethodMismatch && r.MethodNotAllowedHandler != nil { - match.Handler = r.MethodNotAllowedHandler - return true - } - - // Closest match for a router (includes sub-routers) - if r.NotFoundHandler != nil { - match.Handler = r.NotFoundHandler - return true - } - return false -} - -// ServeHTTP dispatches the handler registered in the matched route. -// -// When there is a match, the route variables can be retrieved calling -// mux.Vars(request). -func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if !r.skipClean { - path := req.URL.Path - if r.useEncodedPath { - path = req.URL.EscapedPath() - } - // Clean path to canonical form and redirect. - if p := cleanPath(path); p != path { - - // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. - // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: - // http://code.google.com/p/go/issues/detail?id=5252 - url := *req.URL - url.Path = p - p = url.String() - - w.Header().Set("Location", p) - w.WriteHeader(http.StatusMovedPermanently) - return - } - } - var match RouteMatch - var handler http.Handler - if r.Match(req, &match) { - handler = match.Handler - req = setVars(req, match.Vars) - req = setCurrentRoute(req, match.Route) - } - - if handler == nil && match.MatchErr == ErrMethodMismatch { - handler = methodNotAllowedHandler() - } - - if handler == nil { - handler = http.NotFoundHandler() - } - - if !r.KeepContext { - defer contextClear(req) - } - handler.ServeHTTP(w, req) -} - -// Get returns a route registered with the given name. -func (r *Router) Get(name string) *Route { - return r.getNamedRoutes()[name] -} - -// GetRoute returns a route registered with the given name. This method -// was renamed to Get() and remains here for backwards compatibility. -func (r *Router) GetRoute(name string) *Route { - return r.getNamedRoutes()[name] -} - -// StrictSlash defines the trailing slash behavior for new routes. The initial -// value is false. -// -// When true, if the route path is "/path/", accessing "/path" will redirect -// to the former and vice versa. In other words, your application will always -// see the path as specified in the route. -// -// When false, if the route path is "/path", accessing "/path/" will not match -// this route and vice versa. -// -// Special case: when a route sets a path prefix using the PathPrefix() method, -// strict slash is ignored for that route because the redirect behavior can't -// be determined from a prefix alone. However, any subrouters created from that -// route inherit the original StrictSlash setting. -func (r *Router) StrictSlash(value bool) *Router { - r.strictSlash = value - return r -} - -// SkipClean defines the path cleaning behaviour for new routes. The initial -// value is false. Users should be careful about which routes are not cleaned -// -// When true, if the route path is "/path//to", it will remain with the double -// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ -// -// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will -// become /fetch/http/xkcd.com/534 -func (r *Router) SkipClean(value bool) *Router { - r.skipClean = value - return r -} - -// UseEncodedPath tells the router to match the encoded original path -// to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". -// This behavior has the drawback of needing to match routes against -// r.RequestURI instead of r.URL.Path. Any modifications (such as http.StripPrefix) -// to r.URL.Path will not affect routing when this flag is on and thus may -// induce unintended behavior. -// -// If not called, the router will match the unencoded path to the routes. -// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to" -func (r *Router) UseEncodedPath() *Router { - r.useEncodedPath = true - return r -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -func (r *Router) getBuildScheme() string { - if r.parent != nil { - return r.parent.getBuildScheme() - } - return "" -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Router) getNamedRoutes() map[string]*Route { - if r.namedRoutes == nil { - if r.parent != nil { - r.namedRoutes = r.parent.getNamedRoutes() - } else { - r.namedRoutes = make(map[string]*Route) - } - } - return r.namedRoutes -} - -// getRegexpGroup returns regexp definitions from the parent route, if any. -func (r *Router) getRegexpGroup() *routeRegexpGroup { - if r.parent != nil { - return r.parent.getRegexpGroup() - } - return nil -} - -func (r *Router) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// Route factories -// ---------------------------------------------------------------------------- - -// NewRoute registers an empty route. -func (r *Router) NewRoute() *Route { - route := &Route{parent: r, strictSlash: r.strictSlash, skipClean: r.skipClean, useEncodedPath: r.useEncodedPath} - r.routes = append(r.routes, route) - return route -} - -// Handle registers a new route with a matcher for the URL path. -// See Route.Path() and Route.Handler(). -func (r *Router) Handle(path string, handler http.Handler) *Route { - return r.NewRoute().Path(path).Handler(handler) -} - -// HandleFunc registers a new route with a matcher for the URL path. -// See Route.Path() and Route.HandlerFunc(). -func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, - *http.Request)) *Route { - return r.NewRoute().Path(path).HandlerFunc(f) -} - -// Headers registers a new route with a matcher for request header values. -// See Route.Headers(). -func (r *Router) Headers(pairs ...string) *Route { - return r.NewRoute().Headers(pairs...) -} - -// Host registers a new route with a matcher for the URL host. -// See Route.Host(). -func (r *Router) Host(tpl string) *Route { - return r.NewRoute().Host(tpl) -} - -// MatcherFunc registers a new route with a custom matcher function. -// See Route.MatcherFunc(). -func (r *Router) MatcherFunc(f MatcherFunc) *Route { - return r.NewRoute().MatcherFunc(f) -} - -// Methods registers a new route with a matcher for HTTP methods. -// See Route.Methods(). -func (r *Router) Methods(methods ...string) *Route { - return r.NewRoute().Methods(methods...) -} - -// Path registers a new route with a matcher for the URL path. -// See Route.Path(). -func (r *Router) Path(tpl string) *Route { - return r.NewRoute().Path(tpl) -} - -// PathPrefix registers a new route with a matcher for the URL path prefix. -// See Route.PathPrefix(). -func (r *Router) PathPrefix(tpl string) *Route { - return r.NewRoute().PathPrefix(tpl) -} - -// Queries registers a new route with a matcher for URL query values. -// See Route.Queries(). -func (r *Router) Queries(pairs ...string) *Route { - return r.NewRoute().Queries(pairs...) -} - -// Schemes registers a new route with a matcher for URL schemes. -// See Route.Schemes(). -func (r *Router) Schemes(schemes ...string) *Route { - return r.NewRoute().Schemes(schemes...) -} - -// BuildVarsFunc registers a new route with a custom function for modifying -// route variables before building a URL. -func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { - return r.NewRoute().BuildVarsFunc(f) -} - -// Walk walks the router and all its sub-routers, calling walkFn for each route -// in the tree. The routes are walked in the order they were added. Sub-routers -// are explored depth-first. -func (r *Router) Walk(walkFn WalkFunc) error { - return r.walk(walkFn, []*Route{}) -} - -// SkipRouter is used as a return value from WalkFuncs to indicate that the -// router that walk is about to descend down to should be skipped. -var SkipRouter = errors.New("skip this router") - -// WalkFunc is the type of the function called for each route visited by Walk. -// At every invocation, it is given the current route, and the current router, -// and a list of ancestor routes that lead to the current route. -type WalkFunc func(route *Route, router *Router, ancestors []*Route) error - -func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { - for _, t := range r.routes { - err := walkFn(t, r, ancestors) - if err == SkipRouter { - continue - } - if err != nil { - return err - } - for _, sr := range t.matchers { - if h, ok := sr.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - if h, ok := t.handler.(*Router); ok { - ancestors = append(ancestors, t) - err := h.walk(walkFn, ancestors) - if err != nil { - return err - } - ancestors = ancestors[:len(ancestors)-1] - } - } - return nil -} - -type routes []*Route - -func (r routes) Len() int { return len(r) } -func (r routes) Swap(i, j int) { r[i], r[j] = r[j], r[i] } -func (r routes) Less(i, j int) bool { return r[i].GetPriority() > r[j].GetPriority() } - -// SortRoutes sort routes by route priority -func (r *Router) SortRoutes() { - sort.Sort(routes(r.routes)) -} - -// ---------------------------------------------------------------------------- -// Context -// ---------------------------------------------------------------------------- - -// RouteMatch stores information about a matched route. -type RouteMatch struct { - Route *Route - Handler http.Handler - Vars map[string]string - - // MatchErr is set to appropriate matching error - // It is set to ErrMethodMismatch if there is a mismatch in - // the request method and route method - MatchErr error -} - -type contextKey int - -const ( - varsKey contextKey = iota - routeKey -) - -// Vars returns the route variables for the current request, if any. -func Vars(r *http.Request) map[string]string { - if rv := contextGet(r, varsKey); rv != nil { - return rv.(map[string]string) - } - return nil -} - -// CurrentRoute returns the matched route for the current request, if any. -// This only works when called inside the handler of the matched route -// because the matched route is stored in the request context which is cleared -// after the handler returns, unless the KeepContext option is set on the -// Router. -func CurrentRoute(r *http.Request) *Route { - if rv := contextGet(r, routeKey); rv != nil { - return rv.(*Route) - } - return nil -} - -func setVars(r *http.Request, val interface{}) *http.Request { - return contextSet(r, varsKey, val) -} - -func setCurrentRoute(r *http.Request, val interface{}) *http.Request { - return contextSet(r, routeKey, val) -} - -// ---------------------------------------------------------------------------- -// Helpers -// ---------------------------------------------------------------------------- - -// cleanPath returns the canonical path for p, eliminating . and .. elements. -// Borrowed from the net/http package. -func cleanPath(p string) string { - if p == "" { - return "/" - } - if p[0] != '/' { - p = "/" + p - } - np := path.Clean(p) - // path.Clean removes trailing slash except for root; - // put the trailing slash back if necessary. - if p[len(p)-1] == '/' && np != "/" { - np += "/" - } - - return np -} - -// uniqueVars returns an error if two slices contain duplicated strings. -func uniqueVars(s1, s2 []string) error { - for _, v1 := range s1 { - for _, v2 := range s2 { - if v1 == v2 { - return fmt.Errorf("mux: duplicated route variable %q", v2) - } - } - } - return nil -} - -// checkPairs returns the count of strings passed in, and an error if -// the count is not an even number. -func checkPairs(pairs ...string) (int, error) { - length := len(pairs) - if length%2 != 0 { - return length, fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - } - return length, nil -} - -// mapFromPairsToString converts variadic string parameters to a -// string to string map. -func mapFromPairsToString(pairs ...string) (map[string]string, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]string, length/2) - for i := 0; i < length; i += 2 { - m[pairs[i]] = pairs[i+1] - } - return m, nil -} - -// mapFromPairsToRegex converts variadic string parameters to a -// string to regex map. -func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { - length, err := checkPairs(pairs...) - if err != nil { - return nil, err - } - m := make(map[string]*regexp.Regexp, length/2) - for i := 0; i < length; i += 2 { - regex, err := regexp.Compile(pairs[i+1]) - if err != nil { - return nil, err - } - m[pairs[i]] = regex - } - return m, nil -} - -// matchInArray returns true if the given string value is in the array. -func matchInArray(arr []string, value string) bool { - for _, v := range arr { - if v == value { - return true - } - } - return false -} - -// matchMapWithString returns true if the given key/value pairs exist in a given map. -func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != "" { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v == value { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against -// the given regex -func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { - for k, v := range toCheck { - // Check if key exists. - if canonicalKey { - k = http.CanonicalHeaderKey(k) - } - if values := toMatch[k]; values == nil { - return false - } else if v != nil { - // If value was defined as an empty string we only check that the - // key exists. Otherwise we also check for equality. - valueExists := false - for _, value := range values { - if v.MatchString(value) { - valueExists = true - break - } - } - if !valueExists { - return false - } - } - } - return true -} - -// methodNotAllowed replies to the request with an HTTP status code 405. -func methodNotAllowed(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusMethodNotAllowed) -} - -// methodNotAllowedHandler returns a simple request handler -// that replies to each request with a status code 405. -func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) } diff --git a/vendor/github.com/containous/mux/regexp.go b/vendor/github.com/containous/mux/regexp.go deleted file mode 100644 index d3049b7df..000000000 --- a/vendor/github.com/containous/mux/regexp.go +++ /dev/null @@ -1,332 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "bytes" - "fmt" - "net/http" - "net/url" - "regexp" - "strconv" - "strings" -) - -// newRouteRegexp parses a route template and returns a routeRegexp, -// used to match a host, a path or a query string. -// -// It will extract named variables, assemble a regexp to be matched, create -// a "reverse" template to build URLs and compile regexps to validate variable -// values used in URL building. -// -// Previously we accepted only Python-like identifiers for variable -// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that -// name and pattern can't be empty, and names can't contain a colon. -func newRouteRegexp(tpl string, matchHost, matchPrefix, matchQuery, strictSlash, useEncodedPath bool) (*routeRegexp, error) { - // Check if it is well-formed. - idxs, errBraces := braceIndices(tpl) - if errBraces != nil { - return nil, errBraces - } - // Backup the original. - template := tpl - // Now let's parse it. - defaultPattern := "[^/]+" - if matchQuery { - defaultPattern = ".*" - } else if matchHost { - defaultPattern = "[^.]+" - matchPrefix = false - } - // Only match strict slash if not matching - if matchPrefix || matchHost || matchQuery { - strictSlash = false - } - // Set a flag for strictSlash. - endSlash := false - if strictSlash && strings.HasSuffix(tpl, "/") { - tpl = tpl[:len(tpl)-1] - endSlash = true - } - varsN := make([]string, len(idxs)/2) - varsR := make([]*regexp.Regexp, len(idxs)/2) - pattern := bytes.NewBufferString("") - - // Host matching is case insensitive - if matchHost { - fmt.Fprint(pattern, "(?i)") - } - - pattern.WriteByte('^') - reverse := bytes.NewBufferString("") - var end int - var err error - for i := 0; i < len(idxs); i += 2 { - // Set all values we are interested in. - raw := tpl[end:idxs[i]] - end = idxs[i+1] - parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) - name := parts[0] - patt := defaultPattern - if len(parts) == 2 { - patt = parts[1] - } - // Name or pattern can't be empty. - if name == "" || patt == "" { - return nil, fmt.Errorf("mux: missing name or pattern in %q", - tpl[idxs[i]:end]) - } - // Build the regexp pattern. - fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) - - // Build the reverse template. - fmt.Fprintf(reverse, "%s%%s", raw) - - // Append variable name and compiled pattern. - varsN[i/2] = name - varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) - if err != nil { - return nil, err - } - } - // Add the remaining. - raw := tpl[end:] - pattern.WriteString(regexp.QuoteMeta(raw)) - if strictSlash { - pattern.WriteString("[/]?") - } - if matchQuery { - // Add the default pattern if the query value is empty - if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { - pattern.WriteString(defaultPattern) - } - } - if !matchPrefix { - pattern.WriteByte('$') - } - reverse.WriteString(raw) - if endSlash { - reverse.WriteByte('/') - } - // Compile full regexp. - reg, errCompile := regexp.Compile(pattern.String()) - if errCompile != nil { - return nil, errCompile - } - // Done! - return &routeRegexp{ - template: template, - matchHost: matchHost, - matchQuery: matchQuery, - strictSlash: strictSlash, - useEncodedPath: useEncodedPath, - regexp: reg, - reverse: reverse.String(), - varsN: varsN, - varsR: varsR, - }, nil -} - -// routeRegexp stores a regexp to match a host or path and information to -// collect and validate route variables. -type routeRegexp struct { - // The unmodified template. - template string - // True for host match, false for path or query string match. - matchHost bool - // True for query string match, false for path and host match. - matchQuery bool - // The strictSlash value defined on the route, but disabled if PathPrefix was used. - strictSlash bool - // Determines whether to use encoded req.URL.EnscapedPath() or unencoded - // req.URL.Path for path matching - useEncodedPath bool - // Expanded regexp. - regexp *regexp.Regexp - // Reverse template. - reverse string - // Variable names. - varsN []string - // Variable regexps (validators). - varsR []*regexp.Regexp -} - -// Match matches the regexp against the URL host or path. -func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { - if !r.matchHost { - if r.matchQuery { - return r.matchQueryString(req) - } - path := req.URL.Path - if r.useEncodedPath { - path = req.URL.EscapedPath() - } - return r.regexp.MatchString(path) - } - - return r.regexp.MatchString(getHost(req)) -} - -// url builds a URL part using the given values. -func (r *routeRegexp) url(values map[string]string) (string, error) { - urlValues := make([]interface{}, len(r.varsN)) - for k, v := range r.varsN { - value, ok := values[v] - if !ok { - return "", fmt.Errorf("mux: missing route variable %q", v) - } - if r.matchQuery { - value = url.QueryEscape(value) - } - urlValues[k] = value - } - rv := fmt.Sprintf(r.reverse, urlValues...) - if !r.regexp.MatchString(rv) { - // The URL is checked against the full regexp, instead of checking - // individual variables. This is faster but to provide a good error - // message, we check individual regexps if the URL doesn't match. - for k, v := range r.varsN { - if !r.varsR[k].MatchString(values[v]) { - return "", fmt.Errorf( - "mux: variable %q doesn't match, expected %q", values[v], - r.varsR[k].String()) - } - } - } - return rv, nil -} - -// getURLQuery returns a single query parameter from a request URL. -// For a URL with foo=bar&baz=ding, we return only the relevant key -// value pair for the routeRegexp. -func (r *routeRegexp) getURLQuery(req *http.Request) string { - if !r.matchQuery { - return "" - } - templateKey := strings.SplitN(r.template, "=", 2)[0] - for key, vals := range req.URL.Query() { - if key == templateKey && len(vals) > 0 { - return key + "=" + vals[0] - } - } - return "" -} - -func (r *routeRegexp) matchQueryString(req *http.Request) bool { - return r.regexp.MatchString(r.getURLQuery(req)) -} - -// braceIndices returns the first level curly brace indices from a string. -// It returns an error in case of unbalanced braces. -func braceIndices(s string) ([]int, error) { - var level, idx int - var idxs []int - for i := 0; i < len(s); i++ { - switch s[i] { - case '{': - if level++; level == 1 { - idx = i - } - case '}': - if level--; level == 0 { - idxs = append(idxs, idx, i+1) - } else if level < 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - } - } - if level != 0 { - return nil, fmt.Errorf("mux: unbalanced braces in %q", s) - } - return idxs, nil -} - -// varGroupName builds a capturing group name for the indexed variable. -func varGroupName(idx int) string { - return "v" + strconv.Itoa(idx) -} - -// ---------------------------------------------------------------------------- -// routeRegexpGroup -// ---------------------------------------------------------------------------- - -// routeRegexpGroup groups the route matchers that carry variables. -type routeRegexpGroup struct { - host *routeRegexp - path *routeRegexp - queries []*routeRegexp -} - -// setMatch extracts the variables from the URL once a route matches. -func (v *routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { - // Store host variables. - if v.host != nil { - host := getHost(req) - matches := v.host.regexp.FindStringSubmatchIndex(host) - if len(matches) > 0 { - extractVars(host, matches, v.host.varsN, m.Vars) - } - } - path := req.URL.Path - if r.useEncodedPath { - path = req.URL.EscapedPath() - } - // Store path variables. - if v.path != nil { - matches := v.path.regexp.FindStringSubmatchIndex(path) - if len(matches) > 0 { - extractVars(path, matches, v.path.varsN, m.Vars) - // Check if we should redirect. - if v.path.strictSlash { - p1 := strings.HasSuffix(path, "/") - p2 := strings.HasSuffix(v.path.template, "/") - if p1 != p2 { - u, _ := url.Parse(req.URL.String()) - if p1 { - u.Path = u.Path[:len(u.Path)-1] - } else { - u.Path += "/" - } - m.Handler = http.RedirectHandler(u.String(), 301) - } - } - } - } - // Store query string variables. - for _, q := range v.queries { - queryURL := q.getURLQuery(req) - matches := q.regexp.FindStringSubmatchIndex(queryURL) - if len(matches) > 0 { - extractVars(queryURL, matches, q.varsN, m.Vars) - } - } -} - -// getHost tries its best to return the request host. -func getHost(r *http.Request) string { - if r.URL.IsAbs() { - return r.URL.Host - } - host := r.Host - // Slice off any port information. - if i := strings.Index(host, ":"); i != -1 { - host = host[:i] - } - return host - -} - -func extractVars(input string, matches []int, names []string, output map[string]string) { - matchesCount := 0 - prevEnd := -1 - for i := 2; i < len(matches) && matchesCount < len(names); i += 2 { - if prevEnd < matches[i+1] { - value := input[matches[i]:matches[i+1]] - output[names[matchesCount]] = value - prevEnd = matches[i+1] - matchesCount++ - } - } -} diff --git a/vendor/github.com/containous/mux/route.go b/vendor/github.com/containous/mux/route.go deleted file mode 100644 index 69c3893ff..000000000 --- a/vendor/github.com/containous/mux/route.go +++ /dev/null @@ -1,766 +0,0 @@ -// Copyright 2012 The Gorilla 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 mux - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "regexp" - "strings" -) - -// Route stores information to match a request and build URLs. -type Route struct { - // Parent where the route was registered (a Router). - parent parentRoute - // Request handler for the route. - handler http.Handler - // List of matchers. - matchers []matcher - // Manager for the variables from host and path. - regexp *routeRegexpGroup - // If true, when the path pattern is "/path/", accessing "/path" will - // redirect to the former and vice versa. - strictSlash bool - // If true, when the path pattern is "/path//to", accessing "/path//to" - // will not redirect - skipClean bool - // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" - useEncodedPath bool - // The scheme used when building URLs. - buildScheme string - // If true, this route never matches: it is only used to build URLs. - buildOnly bool - // The name used to build URLs. - name string - // Error resulted from building a route. - err error - // Priority of this route - priority int - - buildVarsFunc BuildVarsFunc -} - -func (r *Route) SkipClean() bool { - return r.skipClean -} - -// Match matches the route against the request. -func (r *Route) Match(req *http.Request, match *RouteMatch) bool { - if r.buildOnly || r.err != nil { - return false - } - - var matchErr error - - // Match everything. - for _, m := range r.matchers { - if matched := m.Match(req, match); !matched { - if _, ok := m.(methodMatcher); ok { - matchErr = ErrMethodMismatch - continue - } - matchErr = nil - return false - } - } - - if matchErr != nil { - match.MatchErr = matchErr - return false - } - - match.MatchErr = nil - // Yay, we have a match. Let's collect some info about it. - if match.Route == nil { - match.Route = r - } - if match.Handler == nil { - match.Handler = r.handler - } - if match.Vars == nil { - match.Vars = make(map[string]string) - } - - // Set variables. - if r.regexp != nil { - r.regexp.setMatch(req, match, r) - } - return true -} - -// ---------------------------------------------------------------------------- -// Route attributes -// ---------------------------------------------------------------------------- - -// GetError returns an error resulted from building the route, if any. -func (r *Route) GetError() error { - return r.err -} - -// BuildOnly sets the route to never match: it is only used to build URLs. -func (r *Route) BuildOnly() *Route { - r.buildOnly = true - return r -} - -// Handler -------------------------------------------------------------------- - -// Handler sets a handler for the route. -func (r *Route) Handler(handler http.Handler) *Route { - if r.err == nil { - r.handler = handler - } - return r -} - -// HandlerFunc sets a handler function for the route. -func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { - return r.Handler(http.HandlerFunc(f)) -} - -// GetHandler returns the handler for the route, if any. -func (r *Route) GetHandler() http.Handler { - return r.handler -} - -// Name ----------------------------------------------------------------------- - -// Name sets the name for the route, used to build URLs. -// If the name was registered already it will be overwritten. -func (r *Route) Name(name string) *Route { - if r.name != "" { - r.err = fmt.Errorf("mux: route already has name %q, can't set %q", - r.name, name) - } - if r.err == nil { - r.name = name - r.getNamedRoutes()[name] = r - } - return r -} - -// GetName returns the name for the route, if any. -func (r *Route) GetName() string { - return r.name -} - -// Priority ----------------------------------------------------------------------- - -// Priority sets the priority for the route -func (r *Route) Priority(priority int) *Route { - r.priority = priority - return r -} - -// GetPriority returns the priority for the route. -func (r *Route) GetPriority() int { - return r.priority -} - -// ---------------------------------------------------------------------------- -// Matchers -// ---------------------------------------------------------------------------- - -// matcher types try to match a request. -type matcher interface { - Match(*http.Request, *RouteMatch) bool -} - -// addMatcher adds a matcher to the route. -func (r *Route) addMatcher(m matcher) *Route { - if r.err == nil { - r.matchers = append(r.matchers, m) - } - return r -} - -// addRegexpMatcher adds a host or path matcher and builder to a route. -func (r *Route) addRegexpMatcher(tpl string, matchHost, matchPrefix, matchQuery bool) error { - if r.err != nil { - return r.err - } - r.regexp = r.getRegexpGroup() - if !matchHost && !matchQuery { - if len(tpl) > 0 && tpl[0] != '/' { - return fmt.Errorf("mux: path must start with a slash, got %q", tpl) - } - if r.regexp.path != nil { - tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl - } - } - rr, err := newRouteRegexp(tpl, matchHost, matchPrefix, matchQuery, r.strictSlash, r.useEncodedPath) - if err != nil { - return err - } - for _, q := range r.regexp.queries { - if err = uniqueVars(rr.varsN, q.varsN); err != nil { - return err - } - } - if matchHost { - if r.regexp.path != nil { - if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { - return err - } - } - r.regexp.host = rr - } else { - if r.regexp.host != nil { - if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { - return err - } - } - if matchQuery { - r.regexp.queries = append(r.regexp.queries, rr) - } else { - r.regexp.path = rr - } - } - r.addMatcher(rr) - return nil -} - -// Headers -------------------------------------------------------------------- - -// headerMatcher matches the request against header values. -type headerMatcher map[string]string - -func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithString(m, r.Header, true) -} - -// Headers adds a matcher for request header values. -// It accepts a sequence of key/value pairs to be matched. For example: -// -// r := mux.NewRouter() -// r.Headers("Content-Type", "application/json", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both request header values match. -// If the value is an empty string, it will match any value if the key is set. -func (r *Route) Headers(pairs ...string) *Route { - if r.err == nil { - var headers map[string]string - headers, r.err = mapFromPairsToString(pairs...) - return r.addMatcher(headerMatcher(headers)) - } - return r -} - -// headerRegexMatcher matches the request against the route given a regex for the header -type headerRegexMatcher map[string]*regexp.Regexp - -func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchMapWithRegex(m, r.Header, true) -} - -// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex -// support. For example: -// -// r := mux.NewRouter() -// r.HeadersRegexp("Content-Type", "application/(text|json)", -// "X-Requested-With", "XMLHttpRequest") -// -// The above route will only match if both the request header matches both regular expressions. -// It the value is an empty string, it will match any value if the key is set. -func (r *Route) HeadersRegexp(pairs ...string) *Route { - if r.err == nil { - var headers map[string]*regexp.Regexp - headers, r.err = mapFromPairsToRegex(pairs...) - return r.addMatcher(headerRegexMatcher(headers)) - } - return r -} - -// Host ----------------------------------------------------------------------- - -// Host adds a matcher for the URL host. -// It accepts a template with zero or more URL variables enclosed by {}. -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next dot. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Host("www.example.com") -// r.Host("{subdomain}.domain.com") -// r.Host("{subdomain:[a-z]+}.domain.com") -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Host(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, true, false, false) - return r -} - -// MatcherFunc ---------------------------------------------------------------- - -// MatcherFunc is the function signature used by custom matchers. -type MatcherFunc func(*http.Request, *RouteMatch) bool - -// Match returns the match for a given request. -func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { - return m(r, match) -} - -// MatcherFunc adds a custom function to be used as request matcher. -func (r *Route) MatcherFunc(f MatcherFunc) *Route { - return r.addMatcher(f) -} - -// Methods -------------------------------------------------------------------- - -// methodMatcher matches the request against HTTP methods. -type methodMatcher []string - -func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.Method) -} - -// Methods adds a matcher for HTTP methods. -// It accepts a sequence of one or more methods to be matched, e.g.: -// "GET", "POST", "PUT". -func (r *Route) Methods(methods ...string) *Route { - for k, v := range methods { - methods[k] = strings.ToUpper(v) - } - return r.addMatcher(methodMatcher(methods)) -} - -// Path ----------------------------------------------------------------------- - -// Path adds a matcher for the URL path. -// It accepts a template with zero or more URL variables enclosed by {}. The -// template must start with a "/". -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -// -// For example: -// -// r := mux.NewRouter() -// r.Path("/products/").Handler(ProductsHandler) -// r.Path("/products/{key}").Handler(ProductsHandler) -// r.Path("/articles/{category}/{id:[0-9]+}"). -// Handler(ArticleHandler) -// -// Variable names must be unique in a given route. They can be retrieved -// calling mux.Vars(request). -func (r *Route) Path(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, false, false) - return r -} - -// PathPrefix ----------------------------------------------------------------- - -// PathPrefix adds a matcher for the URL path prefix. This matches if the given -// template is a prefix of the full URL path. See Route.Path() for details on -// the tpl argument. -// -// Note that it does not treat slashes specially ("/foobar/" will be matched by -// the prefix "/foo") so you may want to use a trailing slash here. -// -// Also note that the setting of Router.StrictSlash() has no effect on routes -// with a PathPrefix matcher. -func (r *Route) PathPrefix(tpl string) *Route { - r.err = r.addRegexpMatcher(tpl, false, true, false) - return r -} - -// Query ---------------------------------------------------------------------- - -// Queries adds a matcher for URL query values. -// It accepts a sequence of key/value pairs. Values may define variables. -// For example: -// -// r := mux.NewRouter() -// r.Queries("foo", "bar", "id", "{id:[0-9]+}") -// -// The above route will only match if the URL contains the defined queries -// values, e.g.: ?foo=bar&id=42. -// -// It the value is an empty string, it will match any value if the key is set. -// -// Variables can define an optional regexp pattern to be matched: -// -// - {name} matches anything until the next slash. -// -// - {name:pattern} matches the given regexp pattern. -func (r *Route) Queries(pairs ...string) *Route { - length := len(pairs) - if length%2 != 0 { - r.err = fmt.Errorf( - "mux: number of parameters must be multiple of 2, got %v", pairs) - return nil - } - for i := 0; i < length; i += 2 { - if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], false, false, true); r.err != nil { - return r - } - } - - return r -} - -// Schemes -------------------------------------------------------------------- - -// schemeMatcher matches the request against URL schemes. -type schemeMatcher []string - -func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { - return matchInArray(m, r.URL.Scheme) -} - -// Schemes adds a matcher for URL schemes. -// It accepts a sequence of schemes to be matched, e.g.: "http", "https". -func (r *Route) Schemes(schemes ...string) *Route { - for k, v := range schemes { - schemes[k] = strings.ToLower(v) - } - if r.buildScheme == "" && len(schemes) > 0 { - r.buildScheme = schemes[0] - } - return r.addMatcher(schemeMatcher(schemes)) -} - -// BuildVarsFunc -------------------------------------------------------------- - -// BuildVarsFunc is the function signature used by custom build variable -// functions (which can modify route variables before a route's URL is built). -type BuildVarsFunc func(map[string]string) map[string]string - -// BuildVarsFunc adds a custom function to be used to modify build variables -// before a route's URL is built. -func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { - r.buildVarsFunc = f - return r -} - -// Subrouter ------------------------------------------------------------------ - -// Subrouter creates a subrouter for the route. -// -// It will test the inner routes only if the parent route matched. For example: -// -// r := mux.NewRouter() -// s := r.Host("www.example.com").Subrouter() -// s.HandleFunc("/products/", ProductsHandler) -// s.HandleFunc("/products/{key}", ProductHandler) -// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) -// -// Here, the routes registered in the subrouter won't be tested if the host -// doesn't match. -func (r *Route) Subrouter() *Router { - router := &Router{parent: r, strictSlash: r.strictSlash} - r.addMatcher(router) - return router -} - -// ---------------------------------------------------------------------------- -// URL building -// ---------------------------------------------------------------------------- - -// URL builds a URL for the route. -// -// It accepts a sequence of key/value pairs for the route variables. For -// example, given this route: -// -// r := mux.NewRouter() -// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// ...a URL for it can be built using: -// -// url, err := r.Get("article").URL("category", "technology", "id", "42") -// -// ...which will return an url.URL with the following path: -// -// "/articles/technology/42" -// -// This also works for host variables: -// -// r := mux.NewRouter() -// r.Host("{subdomain}.domain.com"). -// HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). -// Name("article") -// -// // url.String() will be "http://news.domain.com/articles/technology/42" -// url, err := r.Get("article").URL("subdomain", "news", -// "category", "technology", -// "id", "42") -// -// All variables defined in the route are required, and their values must -// conform to the corresponding patterns. -func (r *Route) URL(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil { - return nil, errors.New("mux: route doesn't have a host or path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - var scheme, host, path string - queries := make([]string, 0, len(r.regexp.queries)) - if r.regexp.host != nil { - if host, err = r.regexp.host.url(values); err != nil { - return nil, err - } - scheme = "http" - if s := r.getBuildScheme(); s != "" { - scheme = s - } - } - if r.regexp.path != nil { - if path, err = r.regexp.path.url(values); err != nil { - return nil, err - } - } - for _, q := range r.regexp.queries { - var query string - if query, err = q.url(values); err != nil { - return nil, err - } - queries = append(queries, query) - } - return &url.URL{ - Scheme: scheme, - Host: host, - Path: path, - RawQuery: strings.Join(queries, "&"), - }, nil -} - -// URLHost builds the host part of the URL for a route. See Route.URL(). -// -// The route must have a host defined. -func (r *Route) URLHost(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.host == nil { - return nil, errors.New("mux: route doesn't have a host") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - host, err := r.regexp.host.url(values) - if err != nil { - return nil, err - } - u := &url.URL{ - Scheme: "http", - Host: host, - } - if s := r.getBuildScheme(); s != "" { - u.Scheme = s - } - return u, nil -} - -// URLPath builds the path part of the URL for a route. See Route.URL(). -// -// The route must have a path defined. -func (r *Route) URLPath(pairs ...string) (*url.URL, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.path == nil { - return nil, errors.New("mux: route doesn't have a path") - } - values, err := r.prepareVars(pairs...) - if err != nil { - return nil, err - } - path, err := r.regexp.path.url(values) - if err != nil { - return nil, err - } - return &url.URL{ - Path: path, - }, nil -} - -// GetPathTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a path. -func (r *Route) GetPathTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.path == nil { - return "", errors.New("mux: route doesn't have a path") - } - return r.regexp.path.template, nil -} - -// GetPathRegexp returns the expanded regular expression used to match route path. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a path. -func (r *Route) GetPathRegexp() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.path == nil { - return "", errors.New("mux: route does not have a path") - } - return r.regexp.path.regexp.String(), nil -} - -// GetQueriesRegexp returns the expanded regular expressions used to match the -// route queries. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An empty list will be returned if the route does not have queries. -func (r *Route) GetQueriesRegexp() ([]string, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.queries == nil { - return nil, errors.New("mux: route doesn't have queries") - } - var queries []string - for _, query := range r.regexp.queries { - queries = append(queries, query.regexp.String()) - } - return queries, nil -} - -// GetQueriesTemplates returns the templates used to build the -// query matching. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An empty list will be returned if the route does not define queries. -func (r *Route) GetQueriesTemplates() ([]string, error) { - if r.err != nil { - return nil, r.err - } - if r.regexp == nil || r.regexp.queries == nil { - return nil, errors.New("mux: route doesn't have queries") - } - var queries []string - for _, query := range r.regexp.queries { - queries = append(queries, query.template) - } - return queries, nil -} - -// GetMethods returns the methods the route matches against -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An empty list will be returned if route does not have methods. -func (r *Route) GetMethods() ([]string, error) { - if r.err != nil { - return nil, r.err - } - for _, m := range r.matchers { - if methods, ok := m.(methodMatcher); ok { - return []string(methods), nil - } - } - return nil, nil -} - -// GetHostTemplate returns the template used to build the -// route match. -// This is useful for building simple REST API documentation and for instrumentation -// against third-party services. -// An error will be returned if the route does not define a host. -func (r *Route) GetHostTemplate() (string, error) { - if r.err != nil { - return "", r.err - } - if r.regexp == nil || r.regexp.host == nil { - return "", errors.New("mux: route doesn't have a host") - } - return r.regexp.host.template, nil -} - -// prepareVars converts the route variable pairs into a map. If the route has a -// BuildVarsFunc, it is invoked. -func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { - m, err := mapFromPairsToString(pairs...) - if err != nil { - return nil, err - } - return r.buildVars(m), nil -} - -func (r *Route) buildVars(m map[string]string) map[string]string { - if r.parent != nil { - m = r.parent.buildVars(m) - } - if r.buildVarsFunc != nil { - m = r.buildVarsFunc(m) - } - return m -} - -// ---------------------------------------------------------------------------- -// parentRoute -// ---------------------------------------------------------------------------- - -// parentRoute allows routes to know about parent host and path definitions. -type parentRoute interface { - getBuildScheme() string - getNamedRoutes() map[string]*Route - getRegexpGroup() *routeRegexpGroup - buildVars(map[string]string) map[string]string -} - -func (r *Route) getBuildScheme() string { - if r.buildScheme != "" { - return r.buildScheme - } - if r.parent != nil { - return r.parent.getBuildScheme() - } - return "" -} - -// getNamedRoutes returns the map where named routes are registered. -func (r *Route) getNamedRoutes() map[string]*Route { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - return r.parent.getNamedRoutes() -} - -// getRegexpGroup returns regexp definitions from this route. -func (r *Route) getRegexpGroup() *routeRegexpGroup { - if r.regexp == nil { - if r.parent == nil { - // During tests router is not always set. - r.parent = NewRouter() - } - regexp := r.parent.getRegexpGroup() - if regexp == nil { - r.regexp = new(routeRegexpGroup) - } else { - // Copy. - r.regexp = &routeRegexpGroup{ - host: regexp.host, - path: regexp.path, - queries: regexp.queries, - } - } - } - return r.regexp -} diff --git a/vendor/github.com/coreos/go-systemd/LICENSE b/vendor/github.com/coreos/go-systemd/LICENSE deleted file mode 100644 index 37ec93a14..000000000 --- a/vendor/github.com/coreos/go-systemd/LICENSE +++ /dev/null @@ -1,191 +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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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/coreos/go-systemd/daemon/sdnotify.go b/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go deleted file mode 100644 index ba6d41d85..000000000 --- a/vendor/github.com/coreos/go-systemd/daemon/sdnotify.go +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright 2014 Docker, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -// - -// Code forked from Docker project -package daemon - -import ( - "net" - "os" -) - -// SdNotify sends a message to the init daemon. It is common to ignore the error. -// If `unsetEnvironment` is true, the environment variable `NOTIFY_SOCKET` -// will be unconditionally unset. -// -// It returns one of the following: -// (false, nil) - notification not supported (i.e. NOTIFY_SOCKET is unset) -// (false, err) - notification supported, but failure happened (e.g. error connecting to NOTIFY_SOCKET or while sending data) -// (true, nil) - notification supported, data has been sent -func SdNotify(unsetEnvironment bool, state string) (sent bool, err error) { - socketAddr := &net.UnixAddr{ - Name: os.Getenv("NOTIFY_SOCKET"), - Net: "unixgram", - } - - // NOTIFY_SOCKET not set - if socketAddr.Name == "" { - return false, nil - } - - if unsetEnvironment { - err = os.Unsetenv("NOTIFY_SOCKET") - } - if err != nil { - return false, err - } - - conn, err := net.DialUnix(socketAddr.Net, nil, socketAddr) - // Error connecting to NOTIFY_SOCKET - if err != nil { - return false, err - } - defer conn.Close() - - _, err = conn.Write([]byte(state)) - // Error sending the message - if err != nil { - return false, err - } - return true, nil -} diff --git a/vendor/github.com/coreos/go-systemd/daemon/watchdog.go b/vendor/github.com/coreos/go-systemd/daemon/watchdog.go deleted file mode 100644 index 35a92e6e6..000000000 --- a/vendor/github.com/coreos/go-systemd/daemon/watchdog.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2016 CoreOS, Inc. -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -package daemon - -import ( - "fmt" - "os" - "strconv" - "time" -) - -// SdWatchdogEnabled return watchdog information for a service. -// Process should send daemon.SdNotify("WATCHDOG=1") every time / 2. -// If `unsetEnvironment` is true, the environment variables `WATCHDOG_USEC` -// and `WATCHDOG_PID` will be unconditionally unset. -// -// It returns one of the following: -// (0, nil) - watchdog isn't enabled or we aren't the watched PID. -// (0, err) - an error happened (e.g. error converting time). -// (time, nil) - watchdog is enabled and we can send ping. -// time is delay before inactive service will be killed. -func SdWatchdogEnabled(unsetEnvironment bool) (time.Duration, error) { - wusec := os.Getenv("WATCHDOG_USEC") - wpid := os.Getenv("WATCHDOG_PID") - if unsetEnvironment { - wusecErr := os.Unsetenv("WATCHDOG_USEC") - wpidErr := os.Unsetenv("WATCHDOG_PID") - if wusecErr != nil { - return 0, wusecErr - } - if wpidErr != nil { - return 0, wpidErr - } - } - - if wusec == "" { - return 0, nil - } - s, err := strconv.Atoi(wusec) - if err != nil { - return 0, fmt.Errorf("error converting WATCHDOG_USEC: %s", err) - } - if s <= 0 { - return 0, fmt.Errorf("error WATCHDOG_USEC must be a positive number") - } - interval := time.Duration(s) * time.Microsecond - - if wpid == "" { - return interval, nil - } - p, err := strconv.Atoi(wpid) - if err != nil { - return 0, fmt.Errorf("error converting WATCHDOG_PID: %s", err) - } - if os.Getpid() != p { - return 0, nil - } - - return interval, nil -} diff --git a/vendor/github.com/cpu/goacmedns/LICENSE b/vendor/github.com/cpu/goacmedns/LICENSE deleted file mode 100644 index 3215897de..000000000 --- a/vendor/github.com/cpu/goacmedns/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2018 Daniel McCarney - -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/cpu/goacmedns/account.go b/vendor/github.com/cpu/goacmedns/account.go deleted file mode 100644 index 9a1d9c81a..000000000 --- a/vendor/github.com/cpu/goacmedns/account.go +++ /dev/null @@ -1,11 +0,0 @@ -package goacmedns - -// Account is a struct that holds the registration response from an ACME-DNS -// server. It represents an API username/key that can be used to update TXT -// records for the account's subdomain. -type Account struct { - FullDomain string - SubDomain string - Username string - Password string -} diff --git a/vendor/github.com/cpu/goacmedns/client.go b/vendor/github.com/cpu/goacmedns/client.go deleted file mode 100644 index 8be70306e..000000000 --- a/vendor/github.com/cpu/goacmedns/client.go +++ /dev/null @@ -1,191 +0,0 @@ -package goacmedns - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "runtime" - "time" -) - -const ( - // ua is a custom user-agent identifier - ua = "goacmedns" -) - -// userAgent returns a string that can be used as a HTTP request `User-Agent` -// header. It includes the `ua` string alongside the OS and architecture of the -// system. -func userAgent() string { - return fmt.Sprintf("%s (%s; %s)", ua, runtime.GOOS, runtime.GOARCH) -} - -var ( - // defaultTimeout is used for the httpClient Timeout settings - defaultTimeout = 30 * time.Second - // httpClient is a `http.Client` that is customized with the `defaultTimeout` - httpClient = http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: defaultTimeout, - KeepAlive: defaultTimeout, - }).Dial, - TLSHandshakeTimeout: defaultTimeout, - ResponseHeaderTimeout: defaultTimeout, - ExpectContinueTimeout: 1 * time.Second, - }, - } -) - -// postAPI makes an HTTP POST request to the given URL, sending the given body -// and attaching the requested custom headers to the request. If there is no -// error the HTTP response body and HTTP response object are returned, otherwise -// an error is returned.. All POST requests include a `User-Agent` header -// populated with the `userAgent` function and a `Content-Type` header of -// `application/json`. -func postAPI(url string, body []byte, headers map[string]string) ([]byte, *http.Response, error) { - req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(body)) - if err != nil { - fmt.Printf("Failed to make req: %s\n", err.Error()) - return nil, nil, err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("User-Agent", userAgent()) - for h, v := range headers { - req.Header.Set(h, v) - } - - resp, err := httpClient.Do(req) - if err != nil { - fmt.Printf("Failed to do req: %s\n", err.Error()) - return nil, resp, err - } - defer func() { _ = resp.Body.Close() }() - - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - fmt.Printf("Failed to read body: %s\n", err.Error()) - return nil, resp, err - } - return respBody, resp, nil -} - -// ClientError represents an error from the ACME-DNS server. It holds -// a `Message` describing the operation the client was doing, a `HTTPStatus` -// code returned by the server, and the `Body` of the HTTP Response from the -// server. -type ClientError struct { - // Message is a string describing the client operation that failed - Message string - // HTTPStatus is the HTTP status code the ACME DNS server returned - HTTPStatus int - // Body is the response body the ACME DNS server returned - Body []byte -} - -// Error collects all of the ClientError fields into a single string -func (e ClientError) Error() string { - return fmt.Sprintf("%s : status code %d response: %s", - e.Message, e.HTTPStatus, string(e.Body)) -} - -// newClientError creates a ClientError instance populated with the given -// arguments -func newClientError(msg string, respCode int, respBody []byte) ClientError { - return ClientError{ - Message: msg, - HTTPStatus: respCode, - Body: respBody, - } -} - -// Client is a struct that can be used to interact with an ACME DNS server to -// register accounts and update TXT records. -type Client struct { - // baseURL is the address of the ACME DNS server - baseURL string -} - -// NewClient returns a Client configured to interact with the ACME DNS server at -// the given URL. -func NewClient(url string) Client { - return Client{ - baseURL: url, - } -} - -// RegisterAccount creates an Account with the ACME DNS server. The optional -// `allowFrom` argument is used to constrain which CIDR ranges can use the -// created Account. -func (c Client) RegisterAccount(allowFrom []string) (Account, error) { - var body []byte - if len(allowFrom) > 0 { - req := struct { - AllowFrom []string - }{ - AllowFrom: allowFrom, - } - reqBody, err := json.Marshal(req) - if err != nil { - return Account{}, err - } - body = reqBody - } - - url := fmt.Sprintf("%s/register", c.baseURL) - respBody, resp, err := postAPI(url, body, nil) - if err != nil { - return Account{}, err - } - - if resp.StatusCode != http.StatusCreated { - return Account{}, newClientError( - "failed to register account", resp.StatusCode, respBody) - } - - var acct Account - err = json.Unmarshal(respBody, &acct) - if err != nil { - return Account{}, err - } - - return acct, nil -} - -// UpdateTXTRecord updates a TXT record with the ACME DNS server to the `value` -// provided using the `account` specified. -func (c Client) UpdateTXTRecord(account Account, value string) error { - update := struct { - SubDomain string - Txt string - }{ - SubDomain: account.SubDomain, - Txt: value, - } - updateBody, err := json.Marshal(update) - if err != nil { - fmt.Printf("Failed to marshal update: %s\n", update) - return err - } - - headers := map[string]string{ - "X-Api-User": account.Username, - "X-Api-Key": account.Password, - } - - url := fmt.Sprintf("%s/update", c.baseURL) - respBody, resp, err := postAPI(url, updateBody, headers) - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - return newClientError( - "failed to update txt record", resp.StatusCode, respBody) - } - - return nil -} diff --git a/vendor/github.com/cpu/goacmedns/storage.go b/vendor/github.com/cpu/goacmedns/storage.go deleted file mode 100644 index 6e0186b0c..000000000 --- a/vendor/github.com/cpu/goacmedns/storage.go +++ /dev/null @@ -1,89 +0,0 @@ -package goacmedns - -import ( - "encoding/json" - "errors" - "io/ioutil" - "os" -) - -// Storage is an interface describing the required functions for an ACME DNS -// Account storage mechanism. -type Storage interface { - // Save will persist the `Account` data that has been `Put` so far - Save() error - // Put will add an `Account` for the given domain to the storage. It may not - // be persisted until `Save` is called. - Put(string, Account) error - // Fetch will retrieve an `Account` for the given domain from the storage. If - // the provided domain does not have an `Account` saved in the storage - // `ErrDomainNotFound` will be returned - Fetch(string) (Account, error) -} - -var ( - // ErrDomainNotFound is returned from `Fetch` when the provided domain is not - // present in the storage. - ErrDomainNotFound = errors.New("requested domain is not present in storage") -) - -// fileStorage implements the `Storage` interface and persists `Accounts` to -// a JSON file on disk. -type fileStorage struct { - // path is the filepath that the `accounts` are persisted to when the `Save` - // function is called. - path string - // mode is the file mode used when the `path` JSON file must be created - mode os.FileMode - // accounts holds the `Account` data that has been `Put` into the storage - accounts map[string]Account -} - -// NewFileStorage returns a `Storage` implementation backed by JSON content -// saved into the provided `path` on disk. The file at `path` will be created if -// required. When creating a new file the provided `mode` is used to set the -// permissions. -func NewFileStorage(path string, mode os.FileMode) Storage { - fs := fileStorage{ - path: path, - mode: mode, - accounts: make(map[string]Account), - } - // Opportunistically try to load the account data. Return an empty account if - // any errors occur. - if jsonData, err := ioutil.ReadFile(path); err == nil { - if err := json.Unmarshal(jsonData, &fs.accounts); err != nil { - return fs - } - } - return fs -} - -// Save persists the `Account` data to the fileStorage's configured path. The -// file at that path will be created with the fileStorage's mode if required. -func (f fileStorage) Save() error { - if serialized, err := json.Marshal(f.accounts); err != nil { - return err - } else if err = ioutil.WriteFile(f.path, serialized, f.mode); err != nil { - return err - } - return nil -} - -// Put saves an `Account` for the given `Domain` into the in-memory accounts of -// the fileStorage instance. The `Account` data will not be written to disk -// until the `Save` function is called -func (f fileStorage) Put(domain string, acct Account) error { - f.accounts[domain] = acct - return nil -} - -// Fetch retrieves the `Account` object for the given `domain` from the -// fileStorage in-memory accounts. If the `domain` provided does not have an -// `Account` in the storage an `ErrDomainNotFound` error is returned. -func (f fileStorage) Fetch(domain string) (Account, error) { - if acct, exists := f.accounts[domain]; exists { - return acct, nil - } - return Account{}, ErrDomainNotFound -} diff --git a/vendor/github.com/davecgh/go-spew/LICENSE b/vendor/github.com/davecgh/go-spew/LICENSE deleted file mode 100644 index c83641619..000000000 --- a/vendor/github.com/davecgh/go-spew/LICENSE +++ /dev/null @@ -1,15 +0,0 @@ -ISC License - -Copyright (c) 2012-2016 Dave Collins - -Permission to use, copy, modify, and distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go deleted file mode 100644 index 8a4a6589a..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is not running on Google App Engine, compiled by GopherJS, and -// "-tags safe" is not added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build !js,!appengine,!safe,!disableunsafe - -package spew - -import ( - "reflect" - "unsafe" -) - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = false - - // ptrSize is the size of a pointer on the current arch. - ptrSize = unsafe.Sizeof((*byte)(nil)) -) - -var ( - // offsetPtr, offsetScalar, and offsetFlag are the offsets for the - // internal reflect.Value fields. These values are valid before golang - // commit ecccf07e7f9d which changed the format. The are also valid - // after commit 82f48826c6c7 which changed the format again to mirror - // the original format. Code in the init function updates these offsets - // as necessary. - offsetPtr = uintptr(ptrSize) - offsetScalar = uintptr(0) - offsetFlag = uintptr(ptrSize * 2) - - // flagKindWidth and flagKindShift indicate various bits that the - // reflect package uses internally to track kind information. - // - // flagRO indicates whether or not the value field of a reflect.Value is - // read-only. - // - // flagIndir indicates whether the value field of a reflect.Value is - // the actual data or a pointer to the data. - // - // These values are valid before golang commit 90a7c3c86944 which - // changed their positions. Code in the init function updates these - // flags as necessary. - flagKindWidth = uintptr(5) - flagKindShift = uintptr(flagKindWidth - 1) - flagRO = uintptr(1 << 0) - flagIndir = uintptr(1 << 1) -) - -func init() { - // Older versions of reflect.Value stored small integers directly in the - // ptr field (which is named val in the older versions). Versions - // between commits ecccf07e7f9d and 82f48826c6c7 added a new field named - // scalar for this purpose which unfortunately came before the flag - // field, so the offset of the flag field is different for those - // versions. - // - // This code constructs a new reflect.Value from a known small integer - // and checks if the size of the reflect.Value struct indicates it has - // the scalar field. When it does, the offsets are updated accordingly. - vv := reflect.ValueOf(0xf00) - if unsafe.Sizeof(vv) == (ptrSize * 4) { - offsetScalar = ptrSize * 2 - offsetFlag = ptrSize * 3 - } - - // Commit 90a7c3c86944 changed the flag positions such that the low - // order bits are the kind. This code extracts the kind from the flags - // field and ensures it's the correct type. When it's not, the flag - // order has been changed to the newer format, so the flags are updated - // accordingly. - upf := unsafe.Pointer(uintptr(unsafe.Pointer(&vv)) + offsetFlag) - upfv := *(*uintptr)(upf) - flagKindMask := uintptr((1<>flagKindShift != uintptr(reflect.Int) { - flagKindShift = 0 - flagRO = 1 << 5 - flagIndir = 1 << 6 - - // Commit adf9b30e5594 modified the flags to separate the - // flagRO flag into two bits which specifies whether or not the - // field is embedded. This causes flagIndir to move over a bit - // and means that flagRO is the combination of either of the - // original flagRO bit and the new bit. - // - // This code detects the change by extracting what used to be - // the indirect bit to ensure it's set. When it's not, the flag - // order has been changed to the newer format, so the flags are - // updated accordingly. - if upfv&flagIndir == 0 { - flagRO = 3 << 5 - flagIndir = 1 << 7 - } - } -} - -// unsafeReflectValue converts the passed reflect.Value into a one that bypasses -// the typical safety restrictions preventing access to unaddressable and -// unexported data. It works by digging the raw pointer to the underlying -// value out of the protected value and generating a new unprotected (unsafe) -// reflect.Value to it. -// -// This allows us to check for implementations of the Stringer and error -// interfaces to be used for pretty printing ordinarily unaddressable and -// inaccessible values such as unexported struct fields. -func unsafeReflectValue(v reflect.Value) (rv reflect.Value) { - indirects := 1 - vt := v.Type() - upv := unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetPtr) - rvf := *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + offsetFlag)) - if rvf&flagIndir != 0 { - vt = reflect.PtrTo(v.Type()) - indirects++ - } else if offsetScalar != 0 { - // The value is in the scalar field when it's not one of the - // reference types. - switch vt.Kind() { - case reflect.Uintptr: - case reflect.Chan: - case reflect.Func: - case reflect.Map: - case reflect.Ptr: - case reflect.UnsafePointer: - default: - upv = unsafe.Pointer(uintptr(unsafe.Pointer(&v)) + - offsetScalar) - } - } - - pv := reflect.NewAt(vt, upv) - rv = pv - for i := 0; i < indirects; i++ { - rv = rv.Elem() - } - return rv -} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go deleted file mode 100644 index 1fe3cf3d5..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) 2015-2016 Dave Collins -// -// Permission to use, copy, modify, and distribute this software for any -// purpose with or without fee is hereby granted, provided that the above -// copyright notice and this permission notice appear in all copies. -// -// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -// NOTE: Due to the following build constraints, this file will only be compiled -// when the code is running on Google App Engine, compiled by GopherJS, or -// "-tags safe" is added to the go build command line. The "disableunsafe" -// tag is deprecated and thus should not be used. -// +build js appengine safe disableunsafe - -package spew - -import "reflect" - -const ( - // UnsafeDisabled is a build-time constant which specifies whether or - // not access to the unsafe package is available. - UnsafeDisabled = true -) - -// unsafeReflectValue typically converts the passed reflect.Value into a one -// that bypasses the typical safety restrictions preventing access to -// unaddressable and unexported data. However, doing this relies on access to -// the unsafe package. This is a stub version which simply returns the passed -// reflect.Value when the unsafe package is not available. -func unsafeReflectValue(v reflect.Value) reflect.Value { - return v -} diff --git a/vendor/github.com/davecgh/go-spew/spew/common.go b/vendor/github.com/davecgh/go-spew/spew/common.go deleted file mode 100644 index 7c519ff47..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/common.go +++ /dev/null @@ -1,341 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "reflect" - "sort" - "strconv" -) - -// Some constants in the form of bytes to avoid string overhead. This mirrors -// the technique used in the fmt package. -var ( - panicBytes = []byte("(PANIC=") - plusBytes = []byte("+") - iBytes = []byte("i") - trueBytes = []byte("true") - falseBytes = []byte("false") - interfaceBytes = []byte("(interface {})") - commaNewlineBytes = []byte(",\n") - newlineBytes = []byte("\n") - openBraceBytes = []byte("{") - openBraceNewlineBytes = []byte("{\n") - closeBraceBytes = []byte("}") - asteriskBytes = []byte("*") - colonBytes = []byte(":") - colonSpaceBytes = []byte(": ") - openParenBytes = []byte("(") - closeParenBytes = []byte(")") - spaceBytes = []byte(" ") - pointerChainBytes = []byte("->") - nilAngleBytes = []byte("") - maxNewlineBytes = []byte("\n") - maxShortBytes = []byte("") - circularBytes = []byte("") - circularShortBytes = []byte("") - invalidAngleBytes = []byte("") - openBracketBytes = []byte("[") - closeBracketBytes = []byte("]") - percentBytes = []byte("%") - precisionBytes = []byte(".") - openAngleBytes = []byte("<") - closeAngleBytes = []byte(">") - openMapBytes = []byte("map[") - closeMapBytes = []byte("]") - lenEqualsBytes = []byte("len=") - capEqualsBytes = []byte("cap=") -) - -// hexDigits is used to map a decimal value to a hex digit. -var hexDigits = "0123456789abcdef" - -// catchPanic handles any panics that might occur during the handleMethods -// calls. -func catchPanic(w io.Writer, v reflect.Value) { - if err := recover(); err != nil { - w.Write(panicBytes) - fmt.Fprintf(w, "%v", err) - w.Write(closeParenBytes) - } -} - -// handleMethods attempts to call the Error and String methods on the underlying -// type the passed reflect.Value represents and outputes the result to Writer w. -// -// It handles panics in any called methods by catching and displaying the error -// as the formatted value. -func handleMethods(cs *ConfigState, w io.Writer, v reflect.Value) (handled bool) { - // We need an interface to check if the type implements the error or - // Stringer interface. However, the reflect package won't give us an - // interface on certain things like unexported struct fields in order - // to enforce visibility rules. We use unsafe, when it's available, - // to bypass these restrictions since this package does not mutate the - // values. - if !v.CanInterface() { - if UnsafeDisabled { - return false - } - - v = unsafeReflectValue(v) - } - - // Choose whether or not to do error and Stringer interface lookups against - // the base type or a pointer to the base type depending on settings. - // Technically calling one of these methods with a pointer receiver can - // mutate the value, however, types which choose to satisify an error or - // Stringer interface with a pointer receiver should not be mutating their - // state inside these interface methods. - if !cs.DisablePointerMethods && !UnsafeDisabled && !v.CanAddr() { - v = unsafeReflectValue(v) - } - if v.CanAddr() { - v = v.Addr() - } - - // Is it an error or Stringer? - switch iface := v.Interface().(type) { - case error: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.Error())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - - w.Write([]byte(iface.Error())) - return true - - case fmt.Stringer: - defer catchPanic(w, v) - if cs.ContinueOnMethod { - w.Write(openParenBytes) - w.Write([]byte(iface.String())) - w.Write(closeParenBytes) - w.Write(spaceBytes) - return false - } - w.Write([]byte(iface.String())) - return true - } - return false -} - -// printBool outputs a boolean value as true or false to Writer w. -func printBool(w io.Writer, val bool) { - if val { - w.Write(trueBytes) - } else { - w.Write(falseBytes) - } -} - -// printInt outputs a signed integer value to Writer w. -func printInt(w io.Writer, val int64, base int) { - w.Write([]byte(strconv.FormatInt(val, base))) -} - -// printUint outputs an unsigned integer value to Writer w. -func printUint(w io.Writer, val uint64, base int) { - w.Write([]byte(strconv.FormatUint(val, base))) -} - -// printFloat outputs a floating point value using the specified precision, -// which is expected to be 32 or 64bit, to Writer w. -func printFloat(w io.Writer, val float64, precision int) { - w.Write([]byte(strconv.FormatFloat(val, 'g', -1, precision))) -} - -// printComplex outputs a complex value using the specified float precision -// for the real and imaginary parts to Writer w. -func printComplex(w io.Writer, c complex128, floatPrecision int) { - r := real(c) - w.Write(openParenBytes) - w.Write([]byte(strconv.FormatFloat(r, 'g', -1, floatPrecision))) - i := imag(c) - if i >= 0 { - w.Write(plusBytes) - } - w.Write([]byte(strconv.FormatFloat(i, 'g', -1, floatPrecision))) - w.Write(iBytes) - w.Write(closeParenBytes) -} - -// printHexPtr outputs a uintptr formatted as hexidecimal with a leading '0x' -// prefix to Writer w. -func printHexPtr(w io.Writer, p uintptr) { - // Null pointer. - num := uint64(p) - if num == 0 { - w.Write(nilAngleBytes) - return - } - - // Max uint64 is 16 bytes in hex + 2 bytes for '0x' prefix - buf := make([]byte, 18) - - // It's simpler to construct the hex string right to left. - base := uint64(16) - i := len(buf) - 1 - for num >= base { - buf[i] = hexDigits[num%base] - num /= base - i-- - } - buf[i] = hexDigits[num] - - // Add '0x' prefix. - i-- - buf[i] = 'x' - i-- - buf[i] = '0' - - // Strip unused leading bytes. - buf = buf[i:] - w.Write(buf) -} - -// valuesSorter implements sort.Interface to allow a slice of reflect.Value -// elements to be sorted. -type valuesSorter struct { - values []reflect.Value - strings []string // either nil or same len and values - cs *ConfigState -} - -// newValuesSorter initializes a valuesSorter instance, which holds a set of -// surrogate keys on which the data should be sorted. It uses flags in -// ConfigState to decide if and how to populate those surrogate keys. -func newValuesSorter(values []reflect.Value, cs *ConfigState) sort.Interface { - vs := &valuesSorter{values: values, cs: cs} - if canSortSimply(vs.values[0].Kind()) { - return vs - } - if !cs.DisableMethods { - vs.strings = make([]string, len(values)) - for i := range vs.values { - b := bytes.Buffer{} - if !handleMethods(cs, &b, vs.values[i]) { - vs.strings = nil - break - } - vs.strings[i] = b.String() - } - } - if vs.strings == nil && cs.SpewKeys { - vs.strings = make([]string, len(values)) - for i := range vs.values { - vs.strings[i] = Sprintf("%#v", vs.values[i].Interface()) - } - } - return vs -} - -// canSortSimply tests whether a reflect.Kind is a primitive that can be sorted -// directly, or whether it should be considered for sorting by surrogate keys -// (if the ConfigState allows it). -func canSortSimply(kind reflect.Kind) bool { - // This switch parallels valueSortLess, except for the default case. - switch kind { - case reflect.Bool: - return true - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return true - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return true - case reflect.Float32, reflect.Float64: - return true - case reflect.String: - return true - case reflect.Uintptr: - return true - case reflect.Array: - return true - } - return false -} - -// Len returns the number of values in the slice. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Len() int { - return len(s.values) -} - -// Swap swaps the values at the passed indices. It is part of the -// sort.Interface implementation. -func (s *valuesSorter) Swap(i, j int) { - s.values[i], s.values[j] = s.values[j], s.values[i] - if s.strings != nil { - s.strings[i], s.strings[j] = s.strings[j], s.strings[i] - } -} - -// valueSortLess returns whether the first value should sort before the second -// value. It is used by valueSorter.Less as part of the sort.Interface -// implementation. -func valueSortLess(a, b reflect.Value) bool { - switch a.Kind() { - case reflect.Bool: - return !a.Bool() && b.Bool() - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - return a.Int() < b.Int() - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - return a.Uint() < b.Uint() - case reflect.Float32, reflect.Float64: - return a.Float() < b.Float() - case reflect.String: - return a.String() < b.String() - case reflect.Uintptr: - return a.Uint() < b.Uint() - case reflect.Array: - // Compare the contents of both arrays. - l := a.Len() - for i := 0; i < l; i++ { - av := a.Index(i) - bv := b.Index(i) - if av.Interface() == bv.Interface() { - continue - } - return valueSortLess(av, bv) - } - } - return a.String() < b.String() -} - -// Less returns whether the value at index i should sort before the -// value at index j. It is part of the sort.Interface implementation. -func (s *valuesSorter) Less(i, j int) bool { - if s.strings == nil { - return valueSortLess(s.values[i], s.values[j]) - } - return s.strings[i] < s.strings[j] -} - -// sortValues is a sort function that handles both native types and any type that -// can be converted to error or Stringer. Other inputs are sorted according to -// their Value.String() value to ensure display stability. -func sortValues(values []reflect.Value, cs *ConfigState) { - if len(values) == 0 { - return - } - sort.Sort(newValuesSorter(values, cs)) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/config.go b/vendor/github.com/davecgh/go-spew/spew/config.go deleted file mode 100644 index 2e3d22f31..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/config.go +++ /dev/null @@ -1,306 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "io" - "os" -) - -// ConfigState houses the configuration options used by spew to format and -// display values. There is a global instance, Config, that is used to control -// all top-level Formatter and Dump functionality. Each ConfigState instance -// provides methods equivalent to the top-level functions. -// -// The zero value for ConfigState provides no indentation. You would typically -// want to set it to a space or a tab. -// -// Alternatively, you can use NewDefaultConfig to get a ConfigState instance -// with default settings. See the documentation of NewDefaultConfig for default -// values. -type ConfigState struct { - // Indent specifies the string to use for each indentation level. The - // global config instance that all top-level functions use set this to a - // single space by default. If you would like more indentation, you might - // set this to a tab with "\t" or perhaps two spaces with " ". - Indent string - - // MaxDepth controls the maximum number of levels to descend into nested - // data structures. The default, 0, means there is no limit. - // - // NOTE: Circular data structures are properly detected, so it is not - // necessary to set this value unless you specifically want to limit deeply - // nested data structures. - MaxDepth int - - // DisableMethods specifies whether or not error and Stringer interfaces are - // invoked for types that implement them. - DisableMethods bool - - // DisablePointerMethods specifies whether or not to check for and invoke - // error and Stringer interfaces on types which only accept a pointer - // receiver when the current type is not a pointer. - // - // NOTE: This might be an unsafe action since calling one of these methods - // with a pointer receiver could technically mutate the value, however, - // in practice, types which choose to satisify an error or Stringer - // interface with a pointer receiver should not be mutating their state - // inside these interface methods. As a result, this option relies on - // access to the unsafe package, so it will not have any effect when - // running in environments without access to the unsafe package such as - // Google App Engine or with the "safe" build tag specified. - DisablePointerMethods bool - - // DisablePointerAddresses specifies whether to disable the printing of - // pointer addresses. This is useful when diffing data structures in tests. - DisablePointerAddresses bool - - // DisableCapacities specifies whether to disable the printing of capacities - // for arrays, slices, maps and channels. This is useful when diffing - // data structures in tests. - DisableCapacities bool - - // ContinueOnMethod specifies whether or not recursion should continue once - // a custom error or Stringer interface is invoked. The default, false, - // means it will print the results of invoking the custom error or Stringer - // interface and return immediately instead of continuing to recurse into - // the internals of the data type. - // - // NOTE: This flag does not have any effect if method invocation is disabled - // via the DisableMethods or DisablePointerMethods options. - ContinueOnMethod bool - - // SortKeys specifies map keys should be sorted before being printed. Use - // this to have a more deterministic, diffable output. Note that only - // native types (bool, int, uint, floats, uintptr and string) and types - // that support the error or Stringer interfaces (if methods are - // enabled) are supported, with other types sorted according to the - // reflect.Value.String() output which guarantees display stability. - SortKeys bool - - // SpewKeys specifies that, as a last resort attempt, map keys should - // be spewed to strings and sorted by those strings. This is only - // considered if SortKeys is true. - SpewKeys bool -} - -// Config is the active configuration of the top-level functions. -// The configuration can be changed by modifying the contents of spew.Config. -var Config = ConfigState{Indent: " "} - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the formatted string as a value that satisfies error. See NewFormatter -// for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, c.convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, c.convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, c.convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a Formatter interface returned by c.NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, c.convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Print(a ...interface{}) (n int, err error) { - return fmt.Print(c.convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, c.convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Println(a ...interface{}) (n int, err error) { - return fmt.Println(c.convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprint(a ...interface{}) string { - return fmt.Sprint(c.convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a Formatter interface returned by c.NewFormatter. It returns -// the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, c.convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a Formatter interface returned by c.NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(c.NewFormatter(a), c.NewFormatter(b)) -func (c *ConfigState) Sprintln(a ...interface{}) string { - return fmt.Sprintln(c.convertArgs(a)...) -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), and %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -c.Printf, c.Println, or c.Printf. -*/ -func (c *ConfigState) NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(c, v) -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func (c *ConfigState) Fdump(w io.Writer, a ...interface{}) { - fdump(c, w, a...) -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by modifying the public members -of c. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func (c *ConfigState) Dump(a ...interface{}) { - fdump(c, os.Stdout, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func (c *ConfigState) Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(c, &buf, a...) - return buf.String() -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a spew Formatter interface using -// the ConfigState associated with s. -func (c *ConfigState) convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = newFormatter(c, arg) - } - return formatters -} - -// NewDefaultConfig returns a ConfigState with the following default settings. -// -// Indent: " " -// MaxDepth: 0 -// DisableMethods: false -// DisablePointerMethods: false -// ContinueOnMethod: false -// SortKeys: false -func NewDefaultConfig() *ConfigState { - return &ConfigState{Indent: " "} -} diff --git a/vendor/github.com/davecgh/go-spew/spew/doc.go b/vendor/github.com/davecgh/go-spew/spew/doc.go deleted file mode 100644 index aacaac6f1..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/doc.go +++ /dev/null @@ -1,211 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -/* -Package spew implements a deep pretty printer for Go data structures to aid in -debugging. - -A quick overview of the additional features spew provides over the built-in -printing facilities for Go data types are as follows: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output (only when using - Dump style) - -There are two different approaches spew allows for dumping Go data structures: - - * Dump style which prints with newlines, customizable indentation, - and additional debug information such as types and all pointer addresses - used to indirect to the final value - * A custom Formatter interface that integrates cleanly with the standard fmt - package and replaces %v, %+v, %#v, and %#+v to provide inline printing - similar to the default %v while providing the additional functionality - outlined above and passing unsupported format verbs such as %x and %q - along to fmt - -Quick Start - -This section demonstrates how to quickly get started with spew. See the -sections below for further details on formatting and configuration options. - -To dump a variable with full newlines, indentation, type, and pointer -information use Dump, Fdump, or Sdump: - spew.Dump(myVar1, myVar2, ...) - spew.Fdump(someWriter, myVar1, myVar2, ...) - str := spew.Sdump(myVar1, myVar2, ...) - -Alternatively, if you would prefer to use format strings with a compacted inline -printing style, use the convenience wrappers Printf, Fprintf, etc with -%v (most compact), %+v (adds pointer addresses), %#v (adds types), or -%#+v (adds types and pointer addresses): - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Fprintf(someWriter, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(someWriter, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -Configuration Options - -Configuration of spew is handled by fields in the ConfigState type. For -convenience, all of the top-level functions use a global state available -via the spew.Config global. - -It is also possible to create a ConfigState instance that provides methods -equivalent to the top-level functions. This allows concurrent configuration -options. See the ConfigState documentation for more details. - -The following configuration options are available: - * Indent - String to use for each indentation level for Dump functions. - It is a single space by default. A popular alternative is "\t". - - * MaxDepth - Maximum number of levels to descend into nested data structures. - There is no limit by default. - - * DisableMethods - Disables invocation of error and Stringer interface methods. - Method invocation is enabled by default. - - * DisablePointerMethods - Disables invocation of error and Stringer interface methods on types - which only accept pointer receivers from non-pointer variables. - Pointer method invocation is enabled by default. - - * DisablePointerAddresses - DisablePointerAddresses specifies whether to disable the printing of - pointer addresses. This is useful when diffing data structures in tests. - - * DisableCapacities - DisableCapacities specifies whether to disable the printing of - capacities for arrays, slices, maps and channels. This is useful when - diffing data structures in tests. - - * ContinueOnMethod - Enables recursion into types after invoking error and Stringer interface - methods. Recursion after method invocation is disabled by default. - - * SortKeys - Specifies map keys should be sorted before being printed. Use - this to have a more deterministic, diffable output. Note that - only native types (bool, int, uint, floats, uintptr and string) - and types which implement error or Stringer interfaces are - supported with other types sorted according to the - reflect.Value.String() output which guarantees display - stability. Natural map order is used by default. - - * SpewKeys - Specifies that, as a last resort attempt, map keys should be - spewed to strings and sorted by those strings. This is only - considered if SortKeys is true. - -Dump Usage - -Simply call spew.Dump with a list of variables you want to dump: - - spew.Dump(myVar1, myVar2, ...) - -You may also call spew.Fdump if you would prefer to output to an arbitrary -io.Writer. For example, to dump to standard error: - - spew.Fdump(os.Stderr, myVar1, myVar2, ...) - -A third option is to call spew.Sdump to get the formatted output as a string: - - str := spew.Sdump(myVar1, myVar2, ...) - -Sample Dump Output - -See the Dump example for details on the setup of the types and variables being -shown here. - - (main.Foo) { - unexportedField: (*main.Bar)(0xf84002e210)({ - flag: (main.Flag) flagTwo, - data: (uintptr) - }), - ExportedField: (map[interface {}]interface {}) (len=1) { - (string) (len=3) "one": (bool) true - } - } - -Byte (and uint8) arrays and slices are displayed uniquely like the hexdump -C -command as shown. - ([]uint8) (len=32 cap=32) { - 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... | - 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0| - 00000020 31 32 |12| - } - -Custom Formatter - -Spew provides a custom formatter that implements the fmt.Formatter interface -so that it integrates cleanly with standard fmt package printing functions. The -formatter is useful for inline printing of smaller data types similar to the -standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Custom Formatter Usage - -The simplest way to make use of the spew custom formatter is to call one of the -convenience functions such as spew.Printf, spew.Println, or spew.Printf. The -functions have syntax you are most likely already familiar with: - - spew.Printf("myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Printf("myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - spew.Println(myVar, myVar2) - spew.Fprintf(os.Stderr, "myVar1: %v -- myVar2: %+v", myVar1, myVar2) - spew.Fprintf(os.Stderr, "myVar3: %#v -- myVar4: %#+v", myVar3, myVar4) - -See the Index for the full list convenience functions. - -Sample Formatter Output - -Double pointer to a uint8: - %v: <**>5 - %+v: <**>(0xf8400420d0->0xf8400420c8)5 - %#v: (**uint8)5 - %#+v: (**uint8)(0xf8400420d0->0xf8400420c8)5 - -Pointer to circular struct with a uint8 field and a pointer to itself: - %v: <*>{1 <*>} - %+v: <*>(0xf84003e260){ui8:1 c:<*>(0xf84003e260)} - %#v: (*main.circular){ui8:(uint8)1 c:(*main.circular)} - %#+v: (*main.circular)(0xf84003e260){ui8:(uint8)1 c:(*main.circular)(0xf84003e260)} - -See the Printf example for details on the setup of variables being shown -here. - -Errors - -Since it is possible for custom Stringer/error interfaces to panic, spew -detects them and handles them internally by printing the panic information -inline with the output. Since spew is intended to provide deep pretty printing -capabilities on structures, it intentionally does not return any errors. -*/ -package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/dump.go b/vendor/github.com/davecgh/go-spew/spew/dump.go deleted file mode 100644 index df1d582a7..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/dump.go +++ /dev/null @@ -1,509 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "encoding/hex" - "fmt" - "io" - "os" - "reflect" - "regexp" - "strconv" - "strings" -) - -var ( - // uint8Type is a reflect.Type representing a uint8. It is used to - // convert cgo types to uint8 slices for hexdumping. - uint8Type = reflect.TypeOf(uint8(0)) - - // cCharRE is a regular expression that matches a cgo char. - // It is used to detect character arrays to hexdump them. - cCharRE = regexp.MustCompile("^.*\\._Ctype_char$") - - // cUnsignedCharRE is a regular expression that matches a cgo unsigned - // char. It is used to detect unsigned character arrays to hexdump - // them. - cUnsignedCharRE = regexp.MustCompile("^.*\\._Ctype_unsignedchar$") - - // cUint8tCharRE is a regular expression that matches a cgo uint8_t. - // It is used to detect uint8_t arrays to hexdump them. - cUint8tCharRE = regexp.MustCompile("^.*\\._Ctype_uint8_t$") -) - -// dumpState contains information about the state of a dump operation. -type dumpState struct { - w io.Writer - depth int - pointers map[uintptr]int - ignoreNextType bool - ignoreNextIndent bool - cs *ConfigState -} - -// indent performs indentation according to the depth level and cs.Indent -// option. -func (d *dumpState) indent() { - if d.ignoreNextIndent { - d.ignoreNextIndent = false - return - } - d.w.Write(bytes.Repeat([]byte(d.cs.Indent), d.depth)) -} - -// unpackValue returns values inside of non-nil interfaces when possible. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (d *dumpState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface && !v.IsNil() { - v = v.Elem() - } - return v -} - -// dumpPtr handles formatting of pointers by indirecting them as necessary. -func (d *dumpState) dumpPtr(v reflect.Value) { - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range d.pointers { - if depth >= d.depth { - delete(d.pointers, k) - } - } - - // Keep list of all dereferenced pointers to show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by dereferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := d.pointers[addr]; ok && pd < d.depth { - cycleFound = true - indirects-- - break - } - d.pointers[addr] = d.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type information. - d.w.Write(openParenBytes) - d.w.Write(bytes.Repeat(asteriskBytes, indirects)) - d.w.Write([]byte(ve.Type().String())) - d.w.Write(closeParenBytes) - - // Display pointer information. - if !d.cs.DisablePointerAddresses && len(pointerChain) > 0 { - d.w.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - d.w.Write(pointerChainBytes) - } - printHexPtr(d.w, addr) - } - d.w.Write(closeParenBytes) - } - - // Display dereferenced value. - d.w.Write(openParenBytes) - switch { - case nilFound == true: - d.w.Write(nilAngleBytes) - - case cycleFound == true: - d.w.Write(circularBytes) - - default: - d.ignoreNextType = true - d.dump(ve) - } - d.w.Write(closeParenBytes) -} - -// dumpSlice handles formatting of arrays and slices. Byte (uint8 under -// reflection) arrays and slices are dumped in hexdump -C fashion. -func (d *dumpState) dumpSlice(v reflect.Value) { - // Determine whether this type should be hex dumped or not. Also, - // for types which should be hexdumped, try to use the underlying data - // first, then fall back to trying to convert them to a uint8 slice. - var buf []uint8 - doConvert := false - doHexDump := false - numEntries := v.Len() - if numEntries > 0 { - vt := v.Index(0).Type() - vts := vt.String() - switch { - // C types that need to be converted. - case cCharRE.MatchString(vts): - fallthrough - case cUnsignedCharRE.MatchString(vts): - fallthrough - case cUint8tCharRE.MatchString(vts): - doConvert = true - - // Try to use existing uint8 slices and fall back to converting - // and copying if that fails. - case vt.Kind() == reflect.Uint8: - // We need an addressable interface to convert the type - // to a byte slice. However, the reflect package won't - // give us an interface on certain things like - // unexported struct fields in order to enforce - // visibility rules. We use unsafe, when available, to - // bypass these restrictions since this package does not - // mutate the values. - vs := v - if !vs.CanInterface() || !vs.CanAddr() { - vs = unsafeReflectValue(vs) - } - if !UnsafeDisabled { - vs = vs.Slice(0, numEntries) - - // Use the existing uint8 slice if it can be - // type asserted. - iface := vs.Interface() - if slice, ok := iface.([]uint8); ok { - buf = slice - doHexDump = true - break - } - } - - // The underlying data needs to be converted if it can't - // be type asserted to a uint8 slice. - doConvert = true - } - - // Copy and convert the underlying type if needed. - if doConvert && vt.ConvertibleTo(uint8Type) { - // Convert and copy each element into a uint8 byte - // slice. - buf = make([]uint8, numEntries) - for i := 0; i < numEntries; i++ { - vv := v.Index(i) - buf[i] = uint8(vv.Convert(uint8Type).Uint()) - } - doHexDump = true - } - } - - // Hexdump the entire slice as needed. - if doHexDump { - indent := strings.Repeat(d.cs.Indent, d.depth) - str := indent + hex.Dump(buf) - str = strings.Replace(str, "\n", "\n"+indent, -1) - str = strings.TrimRight(str, d.cs.Indent) - d.w.Write([]byte(str)) - return - } - - // Recursively call dump for each item. - for i := 0; i < numEntries; i++ { - d.dump(d.unpackValue(v.Index(i))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } -} - -// dump is the main workhorse for dumping a value. It uses the passed reflect -// value to figure out what kind of object we are dealing with and formats it -// appropriately. It is a recursive function, however circular data structures -// are detected and handled properly. -func (d *dumpState) dump(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - d.w.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - d.indent() - d.dumpPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !d.ignoreNextType { - d.indent() - d.w.Write(openParenBytes) - d.w.Write([]byte(v.Type().String())) - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - d.ignoreNextType = false - - // Display length and capacity if the built-in len and cap functions - // work with the value's kind and the len/cap itself is non-zero. - valueLen, valueCap := 0, 0 - switch v.Kind() { - case reflect.Array, reflect.Slice, reflect.Chan: - valueLen, valueCap = v.Len(), v.Cap() - case reflect.Map, reflect.String: - valueLen = v.Len() - } - if valueLen != 0 || !d.cs.DisableCapacities && valueCap != 0 { - d.w.Write(openParenBytes) - if valueLen != 0 { - d.w.Write(lenEqualsBytes) - printInt(d.w, int64(valueLen), 10) - } - if !d.cs.DisableCapacities && valueCap != 0 { - if valueLen != 0 { - d.w.Write(spaceBytes) - } - d.w.Write(capEqualsBytes) - printInt(d.w, int64(valueCap), 10) - } - d.w.Write(closeParenBytes) - d.w.Write(spaceBytes) - } - - // Call Stringer/error interfaces if they exist and the handle methods flag - // is enabled - if !d.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(d.cs, d.w, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(d.w, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(d.w, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(d.w, v.Uint(), 10) - - case reflect.Float32: - printFloat(d.w, v.Float(), 32) - - case reflect.Float64: - printFloat(d.w, v.Float(), 64) - - case reflect.Complex64: - printComplex(d.w, v.Complex(), 32) - - case reflect.Complex128: - printComplex(d.w, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - d.dumpSlice(v) - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.String: - d.w.Write([]byte(strconv.Quote(v.String()))) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - d.w.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - d.w.Write(nilAngleBytes) - break - } - - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - numEntries := v.Len() - keys := v.MapKeys() - if d.cs.SortKeys { - sortValues(keys, d.cs) - } - for i, key := range keys { - d.dump(d.unpackValue(key)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.MapIndex(key))) - if i < (numEntries - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Struct: - d.w.Write(openBraceNewlineBytes) - d.depth++ - if (d.cs.MaxDepth != 0) && (d.depth > d.cs.MaxDepth) { - d.indent() - d.w.Write(maxNewlineBytes) - } else { - vt := v.Type() - numFields := v.NumField() - for i := 0; i < numFields; i++ { - d.indent() - vtf := vt.Field(i) - d.w.Write([]byte(vtf.Name)) - d.w.Write(colonSpaceBytes) - d.ignoreNextIndent = true - d.dump(d.unpackValue(v.Field(i))) - if i < (numFields - 1) { - d.w.Write(commaNewlineBytes) - } else { - d.w.Write(newlineBytes) - } - } - } - d.depth-- - d.indent() - d.w.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(d.w, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(d.w, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it in case any new - // types are added. - default: - if v.CanInterface() { - fmt.Fprintf(d.w, "%v", v.Interface()) - } else { - fmt.Fprintf(d.w, "%v", v.String()) - } - } -} - -// fdump is a helper function to consolidate the logic from the various public -// methods which take varying writers and config states. -func fdump(cs *ConfigState, w io.Writer, a ...interface{}) { - for _, arg := range a { - if arg == nil { - w.Write(interfaceBytes) - w.Write(spaceBytes) - w.Write(nilAngleBytes) - w.Write(newlineBytes) - continue - } - - d := dumpState{w: w, cs: cs} - d.pointers = make(map[uintptr]int) - d.dump(reflect.ValueOf(arg)) - d.w.Write(newlineBytes) - } -} - -// Fdump formats and displays the passed arguments to io.Writer w. It formats -// exactly the same as Dump. -func Fdump(w io.Writer, a ...interface{}) { - fdump(&Config, w, a...) -} - -// Sdump returns a string with the passed arguments formatted exactly the same -// as Dump. -func Sdump(a ...interface{}) string { - var buf bytes.Buffer - fdump(&Config, &buf, a...) - return buf.String() -} - -/* -Dump displays the passed parameters to standard out with newlines, customizable -indentation, and additional debug information such as complete types and all -pointer addresses used to indirect to the final value. It provides the -following features over the built-in printing facilities provided by the fmt -package: - - * Pointers are dereferenced and followed - * Circular data structures are detected and handled properly - * Custom Stringer/error interfaces are optionally invoked, including - on unexported types - * Custom types which only implement the Stringer/error interfaces via - a pointer receiver are optionally invoked when passing non-pointer - variables - * Byte arrays and slices are dumped like the hexdump -C command which - includes offsets, byte values in hex, and ASCII output - -The configuration options are controlled by an exported package global, -spew.Config. See ConfigState for options documentation. - -See Fdump if you would prefer dumping to an arbitrary io.Writer or Sdump to -get the formatted result as a string. -*/ -func Dump(a ...interface{}) { - fdump(&Config, os.Stdout, a...) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/format.go b/vendor/github.com/davecgh/go-spew/spew/format.go deleted file mode 100644 index c49875bac..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/format.go +++ /dev/null @@ -1,419 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "bytes" - "fmt" - "reflect" - "strconv" - "strings" -) - -// supportedFlags is a list of all the character flags supported by fmt package. -const supportedFlags = "0-+# " - -// formatState implements the fmt.Formatter interface and contains information -// about the state of a formatting operation. The NewFormatter function can -// be used to get a new Formatter which can be used directly as arguments -// in standard fmt package printing calls. -type formatState struct { - value interface{} - fs fmt.State - depth int - pointers map[uintptr]int - ignoreNextType bool - cs *ConfigState -} - -// buildDefaultFormat recreates the original format string without precision -// and width information to pass in to fmt.Sprintf in the case of an -// unrecognized type. Unless new types are added to the language, this -// function won't ever be called. -func (f *formatState) buildDefaultFormat() (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - buf.WriteRune('v') - - format = buf.String() - return format -} - -// constructOrigFormat recreates the original format string including precision -// and width information to pass along to the standard fmt package. This allows -// automatic deferral of all format strings this package doesn't support. -func (f *formatState) constructOrigFormat(verb rune) (format string) { - buf := bytes.NewBuffer(percentBytes) - - for _, flag := range supportedFlags { - if f.fs.Flag(int(flag)) { - buf.WriteRune(flag) - } - } - - if width, ok := f.fs.Width(); ok { - buf.WriteString(strconv.Itoa(width)) - } - - if precision, ok := f.fs.Precision(); ok { - buf.Write(precisionBytes) - buf.WriteString(strconv.Itoa(precision)) - } - - buf.WriteRune(verb) - - format = buf.String() - return format -} - -// unpackValue returns values inside of non-nil interfaces when possible and -// ensures that types for values which have been unpacked from an interface -// are displayed when the show types flag is also set. -// This is useful for data types like structs, arrays, slices, and maps which -// can contain varying types packed inside an interface. -func (f *formatState) unpackValue(v reflect.Value) reflect.Value { - if v.Kind() == reflect.Interface { - f.ignoreNextType = false - if !v.IsNil() { - v = v.Elem() - } - } - return v -} - -// formatPtr handles formatting of pointers by indirecting them as necessary. -func (f *formatState) formatPtr(v reflect.Value) { - // Display nil if top level pointer is nil. - showTypes := f.fs.Flag('#') - if v.IsNil() && (!showTypes || f.ignoreNextType) { - f.fs.Write(nilAngleBytes) - return - } - - // Remove pointers at or below the current depth from map used to detect - // circular refs. - for k, depth := range f.pointers { - if depth >= f.depth { - delete(f.pointers, k) - } - } - - // Keep list of all dereferenced pointers to possibly show later. - pointerChain := make([]uintptr, 0) - - // Figure out how many levels of indirection there are by derferencing - // pointers and unpacking interfaces down the chain while detecting circular - // references. - nilFound := false - cycleFound := false - indirects := 0 - ve := v - for ve.Kind() == reflect.Ptr { - if ve.IsNil() { - nilFound = true - break - } - indirects++ - addr := ve.Pointer() - pointerChain = append(pointerChain, addr) - if pd, ok := f.pointers[addr]; ok && pd < f.depth { - cycleFound = true - indirects-- - break - } - f.pointers[addr] = f.depth - - ve = ve.Elem() - if ve.Kind() == reflect.Interface { - if ve.IsNil() { - nilFound = true - break - } - ve = ve.Elem() - } - } - - // Display type or indirection level depending on flags. - if showTypes && !f.ignoreNextType { - f.fs.Write(openParenBytes) - f.fs.Write(bytes.Repeat(asteriskBytes, indirects)) - f.fs.Write([]byte(ve.Type().String())) - f.fs.Write(closeParenBytes) - } else { - if nilFound || cycleFound { - indirects += strings.Count(ve.Type().String(), "*") - } - f.fs.Write(openAngleBytes) - f.fs.Write([]byte(strings.Repeat("*", indirects))) - f.fs.Write(closeAngleBytes) - } - - // Display pointer information depending on flags. - if f.fs.Flag('+') && (len(pointerChain) > 0) { - f.fs.Write(openParenBytes) - for i, addr := range pointerChain { - if i > 0 { - f.fs.Write(pointerChainBytes) - } - printHexPtr(f.fs, addr) - } - f.fs.Write(closeParenBytes) - } - - // Display dereferenced value. - switch { - case nilFound == true: - f.fs.Write(nilAngleBytes) - - case cycleFound == true: - f.fs.Write(circularShortBytes) - - default: - f.ignoreNextType = true - f.format(ve) - } -} - -// format is the main workhorse for providing the Formatter interface. It -// uses the passed reflect value to figure out what kind of object we are -// dealing with and formats it appropriately. It is a recursive function, -// however circular data structures are detected and handled properly. -func (f *formatState) format(v reflect.Value) { - // Handle invalid reflect values immediately. - kind := v.Kind() - if kind == reflect.Invalid { - f.fs.Write(invalidAngleBytes) - return - } - - // Handle pointers specially. - if kind == reflect.Ptr { - f.formatPtr(v) - return - } - - // Print type information unless already handled elsewhere. - if !f.ignoreNextType && f.fs.Flag('#') { - f.fs.Write(openParenBytes) - f.fs.Write([]byte(v.Type().String())) - f.fs.Write(closeParenBytes) - } - f.ignoreNextType = false - - // Call Stringer/error interfaces if they exist and the handle methods - // flag is enabled. - if !f.cs.DisableMethods { - if (kind != reflect.Invalid) && (kind != reflect.Interface) { - if handled := handleMethods(f.cs, f.fs, v); handled { - return - } - } - } - - switch kind { - case reflect.Invalid: - // Do nothing. We should never get here since invalid has already - // been handled above. - - case reflect.Bool: - printBool(f.fs, v.Bool()) - - case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int: - printInt(f.fs, v.Int(), 10) - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uint: - printUint(f.fs, v.Uint(), 10) - - case reflect.Float32: - printFloat(f.fs, v.Float(), 32) - - case reflect.Float64: - printFloat(f.fs, v.Float(), 64) - - case reflect.Complex64: - printComplex(f.fs, v.Complex(), 32) - - case reflect.Complex128: - printComplex(f.fs, v.Complex(), 64) - - case reflect.Slice: - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - fallthrough - - case reflect.Array: - f.fs.Write(openBracketBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - numEntries := v.Len() - for i := 0; i < numEntries; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(v.Index(i))) - } - } - f.depth-- - f.fs.Write(closeBracketBytes) - - case reflect.String: - f.fs.Write([]byte(v.String())) - - case reflect.Interface: - // The only time we should get here is for nil interfaces due to - // unpackValue calls. - if v.IsNil() { - f.fs.Write(nilAngleBytes) - } - - case reflect.Ptr: - // Do nothing. We should never get here since pointers have already - // been handled above. - - case reflect.Map: - // nil maps should be indicated as different than empty maps - if v.IsNil() { - f.fs.Write(nilAngleBytes) - break - } - - f.fs.Write(openMapBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - keys := v.MapKeys() - if f.cs.SortKeys { - sortValues(keys, f.cs) - } - for i, key := range keys { - if i > 0 { - f.fs.Write(spaceBytes) - } - f.ignoreNextType = true - f.format(f.unpackValue(key)) - f.fs.Write(colonBytes) - f.ignoreNextType = true - f.format(f.unpackValue(v.MapIndex(key))) - } - } - f.depth-- - f.fs.Write(closeMapBytes) - - case reflect.Struct: - numFields := v.NumField() - f.fs.Write(openBraceBytes) - f.depth++ - if (f.cs.MaxDepth != 0) && (f.depth > f.cs.MaxDepth) { - f.fs.Write(maxShortBytes) - } else { - vt := v.Type() - for i := 0; i < numFields; i++ { - if i > 0 { - f.fs.Write(spaceBytes) - } - vtf := vt.Field(i) - if f.fs.Flag('+') || f.fs.Flag('#') { - f.fs.Write([]byte(vtf.Name)) - f.fs.Write(colonBytes) - } - f.format(f.unpackValue(v.Field(i))) - } - } - f.depth-- - f.fs.Write(closeBraceBytes) - - case reflect.Uintptr: - printHexPtr(f.fs, uintptr(v.Uint())) - - case reflect.UnsafePointer, reflect.Chan, reflect.Func: - printHexPtr(f.fs, v.Pointer()) - - // There were not any other types at the time this code was written, but - // fall back to letting the default fmt package handle it if any get added. - default: - format := f.buildDefaultFormat() - if v.CanInterface() { - fmt.Fprintf(f.fs, format, v.Interface()) - } else { - fmt.Fprintf(f.fs, format, v.String()) - } - } -} - -// Format satisfies the fmt.Formatter interface. See NewFormatter for usage -// details. -func (f *formatState) Format(fs fmt.State, verb rune) { - f.fs = fs - - // Use standard formatting for verbs that are not v. - if verb != 'v' { - format := f.constructOrigFormat(verb) - fmt.Fprintf(fs, format, f.value) - return - } - - if f.value == nil { - if fs.Flag('#') { - fs.Write(interfaceBytes) - } - fs.Write(nilAngleBytes) - return - } - - f.format(reflect.ValueOf(f.value)) -} - -// newFormatter is a helper function to consolidate the logic from the various -// public methods which take varying config states. -func newFormatter(cs *ConfigState, v interface{}) fmt.Formatter { - fs := &formatState{value: v, cs: cs} - fs.pointers = make(map[uintptr]int) - return fs -} - -/* -NewFormatter returns a custom formatter that satisfies the fmt.Formatter -interface. As a result, it integrates cleanly with standard fmt package -printing functions. The formatter is useful for inline printing of smaller data -types similar to the standard %v format specifier. - -The custom formatter only responds to the %v (most compact), %+v (adds pointer -addresses), %#v (adds types), or %#+v (adds types and pointer addresses) verb -combinations. Any other verbs such as %x and %q will be sent to the the -standard fmt package for formatting. In addition, the custom formatter ignores -the width and precision arguments (however they will still work on the format -specifiers not handled by the custom formatter). - -Typically this function shouldn't be called directly. It is much easier to make -use of the custom formatter by calling one of the convenience functions such as -Printf, Println, or Fprintf. -*/ -func NewFormatter(v interface{}) fmt.Formatter { - return newFormatter(&Config, v) -} diff --git a/vendor/github.com/davecgh/go-spew/spew/spew.go b/vendor/github.com/davecgh/go-spew/spew/spew.go deleted file mode 100644 index 32c0e3388..000000000 --- a/vendor/github.com/davecgh/go-spew/spew/spew.go +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2013-2016 Dave Collins - * - * Permission to use, copy, modify, and distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -package spew - -import ( - "fmt" - "io" -) - -// Errorf is a wrapper for fmt.Errorf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the formatted string as a value that satisfies error. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Errorf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Errorf(format string, a ...interface{}) (err error) { - return fmt.Errorf(format, convertArgs(a)...) -} - -// Fprint is a wrapper for fmt.Fprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprint(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprint(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprint(w, convertArgs(a)...) -} - -// Fprintf is a wrapper for fmt.Fprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintf(w, format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) { - return fmt.Fprintf(w, format, convertArgs(a)...) -} - -// Fprintln is a wrapper for fmt.Fprintln that treats each argument as if it -// passed with a default Formatter interface returned by NewFormatter. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Fprintln(w, spew.NewFormatter(a), spew.NewFormatter(b)) -func Fprintln(w io.Writer, a ...interface{}) (n int, err error) { - return fmt.Fprintln(w, convertArgs(a)...) -} - -// Print is a wrapper for fmt.Print that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Print(spew.NewFormatter(a), spew.NewFormatter(b)) -func Print(a ...interface{}) (n int, err error) { - return fmt.Print(convertArgs(a)...) -} - -// Printf is a wrapper for fmt.Printf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Printf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Printf(format string, a ...interface{}) (n int, err error) { - return fmt.Printf(format, convertArgs(a)...) -} - -// Println is a wrapper for fmt.Println that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the number of bytes written and any write error encountered. See -// NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Println(spew.NewFormatter(a), spew.NewFormatter(b)) -func Println(a ...interface{}) (n int, err error) { - return fmt.Println(convertArgs(a)...) -} - -// Sprint is a wrapper for fmt.Sprint that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprint(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprint(a ...interface{}) string { - return fmt.Sprint(convertArgs(a)...) -} - -// Sprintf is a wrapper for fmt.Sprintf that treats each argument as if it were -// passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintf(format, spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintf(format string, a ...interface{}) string { - return fmt.Sprintf(format, convertArgs(a)...) -} - -// Sprintln is a wrapper for fmt.Sprintln that treats each argument as if it -// were passed with a default Formatter interface returned by NewFormatter. It -// returns the resulting string. See NewFormatter for formatting details. -// -// This function is shorthand for the following syntax: -// -// fmt.Sprintln(spew.NewFormatter(a), spew.NewFormatter(b)) -func Sprintln(a ...interface{}) string { - return fmt.Sprintln(convertArgs(a)...) -} - -// convertArgs accepts a slice of arguments and returns a slice of the same -// length with each argument converted to a default spew Formatter interface. -func convertArgs(args []interface{}) (formatters []interface{}) { - formatters = make([]interface{}, len(args)) - for index, arg := range args { - formatters[index] = NewFormatter(arg) - } - return formatters -} diff --git a/vendor/github.com/decker502/dnspod-go/LICENSE b/vendor/github.com/decker502/dnspod-go/LICENSE deleted file mode 100644 index c5c9a4e37..000000000 --- a/vendor/github.com/decker502/dnspod-go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2017 decker - -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/decker502/dnspod-go/dnspod.go b/vendor/github.com/decker502/dnspod-go/dnspod.go deleted file mode 100644 index ad6671b2b..000000000 --- a/vendor/github.com/decker502/dnspod-go/dnspod.go +++ /dev/null @@ -1,209 +0,0 @@ -// Package dnspod implements a client for the dnspod API. -// -// In order to use this package you will need a dnspod account and your API Token. -package dnspod - -import ( - // "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "net/url" - "strings" - "time" -) - -const ( - libraryVersion = "0.1" - baseURL = "https://dnsapi.cn/" - userAgent = "dnspod-go/" + libraryVersion - - apiVersion = "v1" -) - -// dnspod API docs: https://www.dnspod.cn/docs/info.html - -type CommonParams struct { - LoginToken string - Format string - Lang string - ErrorOnEmpty string - UserID string -} - -func newPayLoad(params CommonParams) url.Values { - p := url.Values{} - - if params.LoginToken != "" { - p.Set("login_token", params.LoginToken) - } - if params.Format != "" { - p.Set("format", params.Format) - } - if params.Lang != "" { - p.Set("lang", params.Lang) - } - if params.ErrorOnEmpty != "" { - p.Set("error_on_empty", params.ErrorOnEmpty) - } - if params.UserID != "" { - p.Set("user_id", params.UserID) - - } - - return p -} - -type Status struct { - Code string `json:"code,omitempty"` - Message string `json:"message,omitempty"` - CreatedAt string `json:"created_at,omitempty"` -} - -type Client struct { - // HTTP client used to communicate with the API. - HttpClient *http.Client - - // CommonParams used communicating with the dnspod API. - CommonParams CommonParams - - // Base URL for API requests. - // Defaults to the public dnspod API, but can be set to a different endpoint (e.g. the sandbox). - // BaseURL should always be specified with a trailing slash. - BaseURL string - - // User agent used when communicating with the dnspod API. - UserAgent string - - // Services used for talking to different parts of the dnspod API. - Domains *DomainsService -} - -// NewClient returns a new dnspod API client. -func NewClient(CommonParams CommonParams) *Client { - c := &Client{HttpClient: &http.Client{}, CommonParams: CommonParams, BaseURL: baseURL, UserAgent: userAgent} - c.Domains = &DomainsService{client: c} - return c - -} - -// NewRequest creates an API request. -// The path is expected to be a relative path and will be resolved -// according to the BaseURL of the Client. Paths should always be specified without a preceding slash. -func (client *Client) NewRequest(method, path string, payload url.Values) (*http.Request, error) { - url := client.BaseURL + fmt.Sprintf("%s", path) - - req, err := http.NewRequest(method, url, strings.NewReader(payload.Encode())) - if err != nil { - return nil, err - } - - req.Header.Add("Content-Type", "application/x-www-form-urlencoded") - req.Header.Add("Accept", "application/json") - req.Header.Add("User-Agent", client.UserAgent) - - return req, nil -} - -func (c *Client) get(path string, v interface{}) (*Response, error) { - return c.Do("GET", path, nil, v) -} - -func (c *Client) post(path string, payload url.Values, v interface{}) (*Response, error) { - return c.Do("POST", path, payload, v) -} - -func (c *Client) put(path string, payload url.Values, v interface{}) (*Response, error) { - return c.Do("PUT", path, payload, v) -} - -func (c *Client) delete(path string, payload url.Values) (*Response, error) { - return c.Do("DELETE", path, payload, nil) -} - -// Do sends an API request and returns the API response. -// The API response is JSON decoded and stored in the value pointed by v, -// or returned as an error if an API error has occurred. -// If v implements the io.Writer interface, the raw response body will be written to v, -// without attempting to decode it. -func (c *Client) Do(method, path string, payload url.Values, v interface{}) (*Response, error) { - req, err := c.NewRequest(method, path, payload) - if err != nil { - return nil, err - } - - res, err := c.HttpClient.Do(req) - if err != nil { - return nil, err - } - defer res.Body.Close() - response := &Response{Response: res} - err = CheckResponse(res) - if err != nil { - return response, err - } - if v != nil { - if w, ok := v.(io.Writer); ok { - io.Copy(w, res.Body) - } else { - err = json.NewDecoder(res.Body).Decode(v) - } - } - - return response, err -} - -// A Response represents an API response. -type Response struct { - *http.Response -} - -// An ErrorResponse represents an error caused by an API request. -type ErrorResponse struct { - Response *http.Response // HTTP response that caused this error - Message string `json:"message"` // human-readable message -} - -// Error implements the error interface. -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %d %v", - r.Response.Request.Method, r.Response.Request.URL, - r.Response.StatusCode, r.Message) -} - -// CheckResponse checks the API response for errors, and returns them if present. -// A response is considered an error if the status code is different than 2xx. Specific requests -// may have additional requirements, but this is sufficient in most of the cases. -func CheckResponse(r *http.Response) error { - if code := r.StatusCode; 200 <= code && code <= 299 { - return nil - } - - errorResponse := &ErrorResponse{Response: r} - err := json.NewDecoder(r.Body).Decode(errorResponse) - if err != nil { - return err - } - - return errorResponse -} - -// Date custom type. -type Date struct { - time.Time -} - -// UnmarshalJSON handles the deserialization of the custom Date type. -func (d *Date) UnmarshalJSON(data []byte) error { - var s string - if err := json.Unmarshal(data, &s); err != nil { - return fmt.Errorf("date should be a string, got %s", data) - } - t, err := time.Parse("2006-01-02", s) - if err != nil { - return fmt.Errorf("invalid date: %v", err) - } - d.Time = t - return nil -} diff --git a/vendor/github.com/decker502/dnspod-go/domain_records.go b/vendor/github.com/decker502/dnspod-go/domain_records.go deleted file mode 100644 index c236ccbf3..000000000 --- a/vendor/github.com/decker502/dnspod-go/domain_records.go +++ /dev/null @@ -1,237 +0,0 @@ -package dnspod - -import ( - "fmt" -) - -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Line string `json:"line,omitempty"` - LineID string `json:"line_id,omitempty"` - Type string `json:"type,omitempty"` - TTL string `json:"ttl,omitempty"` - Value string `json:"value,omitempty"` - MX string `json:"mx,omitempty"` - Enabled string `json:"enabled,omitempty"` - Status string `json:"status,omitempty"` - MonitorStatus string `json:"monitor_status,omitempty"` - Remark string `json:"remark,omitempty"` - UpdateOn string `json:"updated_on,omitempty"` - UseAQB string `json:"use_aqb,omitempty"` -} - -type recordsWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Records []Record `json:"records"` -} - -type recordWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Record Record `json:"record"` -} - -// recordAction generates the resource path for given record that belongs to a domain. -func recordAction(action string) string { - if len(action) > 0 { - return fmt.Sprintf("Record.%s", action) - } - return "Record.List" -} - -// List the domain records. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-list -func (s *DomainsService) ListRecords(domain string, recordName string) ([]Record, *Response, error) { - path := recordAction("List") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - - if recordName != "" { - payload.Add("sub_domain", recordName) - } - - wrappedRecords := recordsWrapper{} - - res, err := s.client.post(path, payload, &wrappedRecords) - if err != nil { - return []Record{}, res, err - } - - if wrappedRecords.Status.Code != "1" { - return wrappedRecords.Records, nil, fmt.Errorf("Could not get domains: %s", wrappedRecords.Status.Message) - } - - records := []Record{} - for _, record := range wrappedRecords.Records { - records = append(records, record) - } - - return records, res, nil -} - -// CreateRecord creates a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-create -func (s *DomainsService) CreateRecord(domain string, recordAttributes Record) (Record, *Response, error) { - path := recordAction("Create") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - - if recordAttributes.Name != "" { - payload.Add("sub_domain", recordAttributes.Name) - } - - if recordAttributes.Type != "" { - payload.Add("record_type", recordAttributes.Type) - } - - if recordAttributes.Line != "" { - payload.Add("record_line", recordAttributes.Line) - } - - if recordAttributes.LineID != "" { - payload.Add("record_line_id", recordAttributes.LineID) - } - - if recordAttributes.Value != "" { - payload.Add("value", recordAttributes.Value) - } - - if recordAttributes.MX != "" { - payload.Add("mx", recordAttributes.MX) - } - - if recordAttributes.TTL != "" { - payload.Add("ttl", recordAttributes.TTL) - } - - if recordAttributes.Status != "" { - payload.Add("status", recordAttributes.Status) - } - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// GetRecord fetches the domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-info -func (s *DomainsService) GetRecord(domain string, recordID string) (Record, *Response, error) { - path := recordAction("Info") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - payload.Add("record_id", recordID) - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// UpdateRecord updates a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-modify -func (s *DomainsService) UpdateRecord(domain string, recordID string, recordAttributes Record) (Record, *Response, error) { - path := recordAction("Modify") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - - if recordAttributes.Name != "" { - payload.Add("sub_domain", recordAttributes.Name) - } - - if recordAttributes.Type != "" { - payload.Add("record_type", recordAttributes.Type) - } - - if recordAttributes.Line != "" { - payload.Add("record_line", recordAttributes.Line) - } - - if recordAttributes.LineID != "" { - payload.Add("record_line_id", recordAttributes.LineID) - } - - if recordAttributes.Value != "" { - payload.Add("value", recordAttributes.Value) - } - - if recordAttributes.MX != "" { - payload.Add("mx", recordAttributes.MX) - } - - if recordAttributes.TTL != "" { - payload.Add("ttl", recordAttributes.TTL) - } - - if recordAttributes.Status != "" { - payload.Add("status", recordAttributes.Status) - } - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return Record{}, res, err - } - - if returnedRecord.Status.Code != "1" { - return returnedRecord.Record, nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return returnedRecord.Record, res, nil -} - -// DeleteRecord deletes a domain record. -// -// dnspod API docs: https://www.dnspod.cn/docs/records.html#record-remove -func (s *DomainsService) DeleteRecord(domain string, recordID string) (*Response, error) { - path := recordAction("Remove") - - payload := newPayLoad(s.client.CommonParams) - - payload.Add("domain_id", domain) - payload.Add("record_id", recordID) - - returnedRecord := recordWrapper{} - - res, err := s.client.post(path, payload, &returnedRecord) - if err != nil { - return res, err - } - - if returnedRecord.Status.Code != "1" { - return nil, fmt.Errorf("Could not get domains: %s", returnedRecord.Status.Message) - } - - return res, nil -} diff --git a/vendor/github.com/decker502/dnspod-go/domains.go b/vendor/github.com/decker502/dnspod-go/domains.go deleted file mode 100644 index 8cd524639..000000000 --- a/vendor/github.com/decker502/dnspod-go/domains.go +++ /dev/null @@ -1,161 +0,0 @@ -package dnspod - -import ( - "fmt" - "strconv" - // "time" -) - -// DomainsService handles communication with the domain related -// methods of the dnspod API. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html -type DomainsService struct { - client *Client -} - -type DomainInfo struct { - DomainTotal int `json:"domain_total,omitempty"` - AllTotal int `json:"all_total,omitempty"` - MineTotal int `json:"mine_total,omitempty"` - ShareTotal string `json:"share_total,omitempty"` - VipTotal int `json:"vip_total,omitempty"` - IsMarkTotal int `json:"ismark_total,omitempty"` - PauseTotal int `json:"pause_total,omitempty"` - ErrorTotal int `json:"error_total,omitempty"` - LockTotal int `json:"lock_total,omitempty"` - SpamTotal int `json:"spam_total,omitempty"` - VipExpire int `json:"vip_expire,omitempty"` - ShareOutTotal int `json:"share_out_total,omitempty"` -} - -type Domain struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` - PunyCode string `json:"punycode,omitempty"` - Grade string `json:"grade,omitempty"` - GradeTitle string `json:"grade_title,omitempty"` - Status string `json:"status,omitempty"` - ExtStatus string `json:"ext_status,omitempty"` - Records string `json:"records,omitempty"` - GroupID string `json:"group_id,omitempty"` - IsMark string `json:"is_mark,omitempty"` - Remark string `json:"remark,omitempty"` - IsVIP string `json:"is_vip,omitempty"` - SearchenginePush string `json:"searchengine_push,omitempty"` - UserID string `json:"user_id,omitempty"` - CreatedOn string `json:"created_on,omitempty"` - UpdatedOn string `json:"updated_on,omitempty"` - TTL string `json:"ttl,omitempty"` - CNameSpeedUp string `json:"cname_speedup,omitempty"` - Owner string `json:"owner,omitempty"` - AuthToAnquanBao bool `json:"auth_to_anquanbao,omitempty"` -} - -type domainListWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Domains []Domain `json:"domains"` -} - -type domainWrapper struct { - Status Status `json:"status"` - Info DomainInfo `json:"info"` - Domain Domain `json:"domain"` -} - -// domainRequest represents a generic wrapper for a domain request, -// when domainWrapper cannot be used because of type constraint on Domain. -type domainRequest struct { - Domain interface{} `json:"domain"` -} - -// domainAction generates the resource path for given domain. -func domainAction(action string) string { - if len(action) > 0 { - return fmt.Sprintf("Domain.%s", action) - } - return "Domain.List" -} - -// List the domains. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-list -func (s *DomainsService) List() ([]Domain, *Response, error) { - path := domainAction("List") - returnedDomains := domainListWrapper{} - - payload := newPayLoad(s.client.CommonParams) - res, err := s.client.post(path, payload, &returnedDomains) - if err != nil { - return []Domain{}, res, err - } - - domains := []Domain{} - - if returnedDomains.Status.Code != "1" { - return domains, nil, fmt.Errorf("Could not get domains: %s", returnedDomains.Status.Message) - } - - for _, domain := range returnedDomains.Domains { - domains = append(domains, domain) - } - - return domains, res, nil -} - -// Create a new domain. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-create -func (s *DomainsService) Create(domainAttributes Domain) (Domain, *Response, error) { - path := domainAction("Create") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain", domainAttributes.Name) - payload.Set("group_id", domainAttributes.GroupID) - payload.Set("is_mark", domainAttributes.IsMark) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return Domain{}, res, err - } - - return returnedDomain.Domain, res, nil -} - -// Get fetches a domain. -// -// dnspod API docs: https://www.dnspod.cn/docs/domains.html#domain-info -func (s *DomainsService) Get(ID int) (Domain, *Response, error) { - path := domainAction("Info") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain_id", strconv.FormatInt(int64(ID), 10)) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return Domain{}, res, err - } - - return returnedDomain.Domain, res, nil -} - -// Delete a domain. -// -// dnspod API docs: https://dnsapi.cn/Domain.Remove -func (s *DomainsService) Delete(ID int) (*Response, error) { - path := domainAction("Remove") - returnedDomain := domainWrapper{} - - payload := newPayLoad(s.client.CommonParams) - payload.Set("domain_id", strconv.FormatInt(int64(ID), 10)) - - res, err := s.client.post(path, payload, &returnedDomain) - if err != nil { - return res, err - } - - return res, nil -} diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE deleted file mode 100644 index df83a9c2f..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/LICENSE +++ /dev/null @@ -1,8 +0,0 @@ -Copyright (c) 2012 Dave Grijalva - -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/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go deleted file mode 100644 index f0228f02e..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/claims.go +++ /dev/null @@ -1,134 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// For a type to be a Claims object, it must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// Structured version of Claims Section, as referenced at -// https://tools.ietf.org/html/rfc7519#section-4.1 -// See examples for how to use this with your own claim types -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if c.VerifyExpiresAt(now, false) == false { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("token is expired by %v", delta) - vErr.Errors |= ValidationErrorExpired - } - - if c.VerifyIssuedAt(now, false) == false { - vErr.Inner = fmt.Errorf("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if c.VerifyNotBefore(now, false) == false { - vErr.Inner = fmt.Errorf("token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - return verifyExp(c.ExpiresAt, cmp, req) -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - return verifyIat(c.IssuedAt, cmp, req) -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - return verifyNbf(c.NotBefore, cmp, req) -} - -// ----- helpers - -func verifyAud(aud string, cmp string, required bool) bool { - if aud == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyExp(exp int64, now int64, required bool) bool { - if exp == 0 { - return !required - } - return now <= exp -} - -func verifyIat(iat int64, now int64, required bool) bool { - if iat == 0 { - return !required - } - return now >= iat -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} - -func verifyNbf(nbf int64, now int64, required bool) bool { - if nbf == 0 { - return !required - } - return now >= nbf -} diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go deleted file mode 100644 index a86dc1a3b..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/doc.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html -// -// See README.md for more info. -package jwt diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go deleted file mode 100644 index f97738124..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rand" - "errors" - "math/big" -) - -var ( - // Sadly this is missing from crypto/ecdsa compared to crypto/rsa - ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") -) - -// Implements the ECDSA family of signing methods signing methods -// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification -type SigningMethodECDSA struct { - Name string - Hash crypto.Hash - KeySize int - CurveBits int -} - -// Specific instances for EC256 and company -var ( - SigningMethodES256 *SigningMethodECDSA - SigningMethodES384 *SigningMethodECDSA - SigningMethodES512 *SigningMethodECDSA -) - -func init() { - // ES256 - SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} - RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { - return SigningMethodES256 - }) - - // ES384 - SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} - RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { - return SigningMethodES384 - }) - - // ES512 - SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} - RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { - return SigningMethodES512 - }) -} - -func (m *SigningMethodECDSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an ecdsa.PublicKey struct -func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - // Get the key - var ecdsaKey *ecdsa.PublicKey - switch k := key.(type) { - case *ecdsa.PublicKey: - ecdsaKey = k - default: - return ErrInvalidKeyType - } - - if len(sig) != 2*m.KeySize { - return ErrECDSAVerification - } - - r := big.NewInt(0).SetBytes(sig[:m.KeySize]) - s := big.NewInt(0).SetBytes(sig[m.KeySize:]) - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { - return nil - } else { - return ErrECDSAVerification - } -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an ecdsa.PrivateKey struct -func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { - // Get the key - var ecdsaKey *ecdsa.PrivateKey - switch k := key.(type) { - case *ecdsa.PrivateKey: - ecdsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return r, s - if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { - curveBits := ecdsaKey.Curve.Params().BitSize - - if m.CurveBits != curveBits { - return "", ErrInvalidKey - } - - keyBytes := curveBits / 8 - if curveBits%8 > 0 { - keyBytes += 1 - } - - // We serialize the outpus (r and s) into big-endian byte arrays and pad - // them with zeros on the left to make sure the sizes work out. Both arrays - // must be keyBytes long, and the output must be 2*keyBytes long. - rBytes := r.Bytes() - rBytesPadded := make([]byte, keyBytes) - copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) - - sBytes := s.Bytes() - sBytesPadded := make([]byte, keyBytes) - copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) - - out := append(rBytesPadded, sBytesPadded...) - - return EncodeSegment(out), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go deleted file mode 100644 index d19624b72..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go +++ /dev/null @@ -1,67 +0,0 @@ -package jwt - -import ( - "crypto/ecdsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") - ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") -) - -// Parse PEM encoded Elliptic Curve Private Key Structure -func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { - return nil, err - } - - var pkey *ecdsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { - return nil, ErrNotECPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *ecdsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { - return nil, ErrNotECPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go deleted file mode 100644 index 1c93024aa..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/errors.go +++ /dev/null @@ -1,59 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// Helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// The error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Validation error is an error type -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go deleted file mode 100644 index addbe5d40..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/hmac.go +++ /dev/null @@ -1,95 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/hmac" - "errors" -) - -// Implements the HMAC-SHA family of signing methods signing methods -// Expects key type of []byte for both signing and validation -type SigningMethodHMAC struct { - Name string - Hash crypto.Hash -} - -// Specific instances for HS256 and company -var ( - SigningMethodHS256 *SigningMethodHMAC - SigningMethodHS384 *SigningMethodHMAC - SigningMethodHS512 *SigningMethodHMAC - ErrSignatureInvalid = errors.New("signature is invalid") -) - -func init() { - // HS256 - SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { - return SigningMethodHS256 - }) - - // HS384 - SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { - return SigningMethodHS384 - }) - - // HS512 - SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { - return SigningMethodHS512 - }) -} - -func (m *SigningMethodHMAC) Alg() string { - return m.Name -} - -// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. -func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { - // Verify the key is the right type - keyBytes, ok := key.([]byte) - if !ok { - return ErrInvalidKeyType - } - - // Decode signature, for comparison - sig, err := DecodeSegment(signature) - if err != nil { - return err - } - - // Can we use the specified hashing method? - if !m.Hash.Available() { - return ErrHashUnavailable - } - - // This signing method is symmetric, so we validate the signature - // by reproducing the signature from the signing string and key, then - // comparing that against the provided signature. - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - if !hmac.Equal(sig, hasher.Sum(nil)) { - return ErrSignatureInvalid - } - - // No validation errors. Signature is good. - return nil -} - -// Implements the Sign method from SigningMethod for this signing method. -// Key must be []byte -func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { - if keyBytes, ok := key.([]byte); ok { - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := hmac.New(m.Hash.New, keyBytes) - hasher.Write([]byte(signingString)) - - return EncodeSegment(hasher.Sum(nil)), nil - } - - return "", ErrInvalidKeyType -} diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go deleted file mode 100644 index 291213c46..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/map_claims.go +++ /dev/null @@ -1,94 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - // "fmt" -) - -// Claims type that uses the map[string]interface{} for JSON decoding -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - aud, _ := m["aud"].(string) - return verifyAud(aud, cmp, req) -} - -// Compares the exp claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - switch exp := m["exp"].(type) { - case float64: - return verifyExp(int64(exp), cmp, req) - case json.Number: - v, _ := exp.Int64() - return verifyExp(v, cmp, req) - } - return req == false -} - -// Compares the iat claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - switch iat := m["iat"].(type) { - case float64: - return verifyIat(int64(iat), cmp, req) - case json.Number: - v, _ := iat.Int64() - return verifyIat(v, cmp, req) - } - return req == false -} - -// Compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Compares the nbf claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - switch nbf := m["nbf"].(type) { - case float64: - return verifyNbf(int64(nbf), cmp, req) - case json.Number: - v, _ := nbf.Int64() - return verifyNbf(v, cmp, req) - } - return req == false -} - -// Validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if m.VerifyExpiresAt(now, false) == false { - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if m.VerifyIssuedAt(now, false) == false { - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if m.VerifyNotBefore(now, false) == false { - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go deleted file mode 100644 index f04d189d0..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/none.go +++ /dev/null @@ -1,52 +0,0 @@ -package jwt - -// Implements the none signing method. This is required by the spec -// but you probably should never use it. -var SigningMethodNone *signingMethodNone - -const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" - -var NoneSignatureTypeDisallowedError error - -type signingMethodNone struct{} -type unsafeNoneMagicConstant string - -func init() { - SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) - - RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { - return SigningMethodNone - }) -} - -func (m *signingMethodNone) Alg() string { - return "none" -} - -// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { - // Key must be UnsafeAllowNoneSignatureType to prevent accidentally - // accepting 'none' signing method - if _, ok := key.(unsafeNoneMagicConstant); !ok { - return NoneSignatureTypeDisallowedError - } - // If signing method is none, signature must be an empty string - if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) - } - - // Accept 'none' signing method. - return nil -} - -// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key -func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { - if _, ok := key.(unsafeNoneMagicConstant); ok { - return "", nil - } - return "", NoneSignatureTypeDisallowedError -} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go deleted file mode 100644 index d6901d9ad..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/parser.go +++ /dev/null @@ -1,148 +0,0 @@ -package jwt - -import ( - "bytes" - "encoding/json" - "fmt" - "strings" -) - -type Parser struct { - ValidMethods []string // If populated, only these methods will be considered valid - UseJSONNumber bool // Use JSON Number format in JSON decoder - SkipClaimsValidation bool // Skip claims validation during token parsing -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) -} - -func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - token, parts, err := p.ParseUnverified(tokenString, claims) - if err != nil { - return token, err - } - - // Verify signing method is in the required set - if p.ValidMethods != nil { - var signingMethodValid = false - var alg = token.Method.Alg() - for _, m := range p.ValidMethods { - if m == alg { - signingMethodValid = true - break - } - } - if !signingMethodValid { - // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) - } - } - - // Lookup key - var key interface{} - if keyFunc == nil { - // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) - } - if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} - } - - vErr := &ValidationError{} - - // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } - } - } - - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid - } - - if vErr.valid() { - token.Valid = true - return token, nil - } - - return token, vErr -} - -// WARNING: Don't use this method unless you know what you're doing -// -// This method parses the token but doesn't validate the signature. It's only -// ever useful in cases where you know the signature is valid (because it has -// been checked previously in the stack) and you want to extract values from -// it. -func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { - parts = strings.Split(tokenString, ".") - if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) - } - - token = &Token{Raw: tokenString} - - // parse Header - var headerBytes []byte - if headerBytes, err = DecodeSegment(parts[0]); err != nil { - if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) - } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // parse Claims - var claimBytes []byte - token.Claims = claims - - if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { - dec.UseNumber() - } - // JSON Decode. Special case for map type to avoid weird pointer behavior - if c, ok := token.Claims.(MapClaims); ok { - err = dec.Decode(&c) - } else { - err = dec.Decode(&claims) - } - // Handle decode error - if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} - } - - // Lookup signature method - if method, ok := token.Header["alg"].(string); ok { - if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) - } - } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) - } - - return token, parts, nil -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go deleted file mode 100644 index e4caf1ca4..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSA family of signing methods signing methods -// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation -type SigningMethodRSA struct { - Name string - Hash crypto.Hash -} - -// Specific instances for RS256 and company -var ( - SigningMethodRS256 *SigningMethodRSA - SigningMethodRS384 *SigningMethodRSA - SigningMethodRS512 *SigningMethodRSA -) - -func init() { - // RS256 - SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} - RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { - return SigningMethodRS256 - }) - - // RS384 - SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} - RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { - return SigningMethodRS384 - }) - - // RS512 - SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} - RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { - return SigningMethodRS512 - }) -} - -func (m *SigningMethodRSA) Alg() string { - return m.Name -} - -// Implements the Verify method from SigningMethod -// For this signing method, must be an *rsa.PublicKey structure. -func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - var ok bool - - if rsaKey, ok = key.(*rsa.PublicKey); !ok { - return ErrInvalidKeyType - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Verify the signature - return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) -} - -// Implements the Sign method from SigningMethod -// For this signing method, must be an *rsa.PrivateKey structure. -func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - var ok bool - - // Validate type of key - if rsaKey, ok = key.(*rsa.PrivateKey); !ok { - return "", ErrInvalidKey - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go deleted file mode 100644 index 10ee9db8a..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go +++ /dev/null @@ -1,126 +0,0 @@ -// +build go1.4 - -package jwt - -import ( - "crypto" - "crypto/rand" - "crypto/rsa" -) - -// Implements the RSAPSS family of signing methods signing methods -type SigningMethodRSAPSS struct { - *SigningMethodRSA - Options *rsa.PSSOptions -} - -// Specific instances for RS/PS and company -var ( - SigningMethodPS256 *SigningMethodRSAPSS - SigningMethodPS384 *SigningMethodRSAPSS - SigningMethodPS512 *SigningMethodRSAPSS -) - -func init() { - // PS256 - SigningMethodPS256 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS256", - Hash: crypto.SHA256, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA256, - }, - } - RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { - return SigningMethodPS256 - }) - - // PS384 - SigningMethodPS384 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS384", - Hash: crypto.SHA384, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA384, - }, - } - RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { - return SigningMethodPS384 - }) - - // PS512 - SigningMethodPS512 = &SigningMethodRSAPSS{ - &SigningMethodRSA{ - Name: "PS512", - Hash: crypto.SHA512, - }, - &rsa.PSSOptions{ - SaltLength: rsa.PSSSaltLengthAuto, - Hash: crypto.SHA512, - }, - } - RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { - return SigningMethodPS512 - }) -} - -// Implements the Verify method from SigningMethod -// For this verify method, key must be an rsa.PublicKey struct -func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { - var err error - - // Decode the signature - var sig []byte - if sig, err = DecodeSegment(signature); err != nil { - return err - } - - var rsaKey *rsa.PublicKey - switch k := key.(type) { - case *rsa.PublicKey: - rsaKey = k - default: - return ErrInvalidKey - } - - // Create hasher - if !m.Hash.Available() { - return ErrHashUnavailable - } - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) -} - -// Implements the Sign method from SigningMethod -// For this signing method, key must be an rsa.PrivateKey struct -func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { - var rsaKey *rsa.PrivateKey - - switch k := key.(type) { - case *rsa.PrivateKey: - rsaKey = k - default: - return "", ErrInvalidKeyType - } - - // Create the hasher - if !m.Hash.Available() { - return "", ErrHashUnavailable - } - - hasher := m.Hash.New() - hasher.Write([]byte(signingString)) - - // Sign the string and return the encoded bytes - if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { - return EncodeSegment(sigBytes), nil - } else { - return "", err - } -} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go deleted file mode 100644 index a5ababf95..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import ( - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" -) - -var ( - ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") - ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") - ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") -) - -// Parse PEM encoded PKCS1 or PKCS8 private key -func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 private key protected with password -func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - var parsedKey interface{} - - var blockDecrypted []byte - if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { - return nil, err - } - - if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { - if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { - return nil, err - } - } - - var pkey *rsa.PrivateKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { - return nil, ErrNotRSAPrivateKey - } - - return pkey, nil -} - -// Parse PEM encoded PKCS1 or PKCS8 public key -func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { - var err error - - // Parse PEM block - var block *pem.Block - if block, _ = pem.Decode(key); block == nil { - return nil, ErrKeyMustBePEMEncoded - } - - // Parse the key - var parsedKey interface{} - if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { - if cert, err := x509.ParseCertificate(block.Bytes); err == nil { - parsedKey = cert.PublicKey - } else { - return nil, err - } - } - - var pkey *rsa.PublicKey - var ok bool - if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { - return nil, ErrNotRSAPublicKey - } - - return pkey, nil -} diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go deleted file mode 100644 index ed1f212b2..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/signing_method.go +++ /dev/null @@ -1,35 +0,0 @@ -package jwt - -import ( - "sync" -) - -var signingMethods = map[string]func() SigningMethod{} -var signingMethodLock = new(sync.RWMutex) - -// Implement SigningMethod to add new methods for signing or verifying tokens. -type SigningMethod interface { - Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid - Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error - Alg() string // returns the alg identifier for this method (example: 'HS256') -} - -// Register the "alg" name and a factory function for signing method. -// This is typically done during init() in the method's implementation -func RegisterSigningMethod(alg string, f func() SigningMethod) { - signingMethodLock.Lock() - defer signingMethodLock.Unlock() - - signingMethods[alg] = f -} - -// Get a signing method from an "alg" string -func GetSigningMethod(alg string) (method SigningMethod) { - signingMethodLock.RLock() - defer signingMethodLock.RUnlock() - - if methodF, ok := signingMethods[alg]; ok { - method = methodF() - } - return -} diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go deleted file mode 100644 index d637e0867..000000000 --- a/vendor/github.com/dgrijalva/jwt-go/token.go +++ /dev/null @@ -1,108 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Parse methods use this callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// A JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// Create a new Token. Takes a signing method -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// Get the complete, signed token -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// Generate the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - parts := make([]string, 2) - for i, _ := range parts { - var jsonValue []byte - if i == 0 { - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - } else { - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - } - - parts[i] = EncodeSegment(jsonValue) - } - return strings.Join(parts, "."), nil -} - -// Parse, validate, and return a token. -// keyFunc will receive the parsed token and should return the key for validating. -// If everything is kosher, err will be nil -func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { - return new(Parser).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { - return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) -} - -// Encode JWT specific base64url encoding with padding stripped -func EncodeSegment(seg []byte) string { - return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") -} - -// Decode JWT specific base64url encoding with padding stripped -func DecodeSegment(seg string) ([]byte, error) { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - - return base64.URLEncoding.DecodeString(seg) -} diff --git a/vendor/github.com/dimchansky/utfbom/LICENSE b/vendor/github.com/dimchansky/utfbom/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/vendor/github.com/dimchansky/utfbom/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/dimchansky/utfbom/utfbom.go b/vendor/github.com/dimchansky/utfbom/utfbom.go deleted file mode 100644 index 77a303e56..000000000 --- a/vendor/github.com/dimchansky/utfbom/utfbom.go +++ /dev/null @@ -1,192 +0,0 @@ -// Package utfbom implements the detection of the BOM (Unicode Byte Order Mark) and removing as necessary. -// It wraps an io.Reader object, creating another object (Reader) that also implements the io.Reader -// interface but provides automatic BOM checking and removing as necessary. -package utfbom - -import ( - "errors" - "io" -) - -// Encoding is type alias for detected UTF encoding. -type Encoding int - -// Constants to identify detected UTF encodings. -const ( - // Unknown encoding, returned when no BOM was detected - Unknown Encoding = iota - - // UTF8, BOM bytes: EF BB BF - UTF8 - - // UTF-16, big-endian, BOM bytes: FE FF - UTF16BigEndian - - // UTF-16, little-endian, BOM bytes: FF FE - UTF16LittleEndian - - // UTF-32, big-endian, BOM bytes: 00 00 FE FF - UTF32BigEndian - - // UTF-32, little-endian, BOM bytes: FF FE 00 00 - UTF32LittleEndian -) - -// String returns a user-friendly string representation of the encoding. Satisfies fmt.Stringer interface. -func (e Encoding) String() string { - switch e { - case UTF8: - return "UTF8" - case UTF16BigEndian: - return "UTF16BigEndian" - case UTF16LittleEndian: - return "UTF16LittleEndian" - case UTF32BigEndian: - return "UTF32BigEndian" - case UTF32LittleEndian: - return "UTF32LittleEndian" - default: - return "Unknown" - } -} - -const maxConsecutiveEmptyReads = 100 - -// Skip creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -// It also returns the encoding detected by the BOM. -// If the detected encoding is not needed, you can call the SkipOnly function. -func Skip(rd io.Reader) (*Reader, Encoding) { - // Is it already a Reader? - b, ok := rd.(*Reader) - if ok { - return b, Unknown - } - - enc, left, err := detectUtf(rd) - return &Reader{ - rd: rd, - buf: left, - err: err, - }, enc -} - -// SkipOnly creates Reader which automatically detects BOM (Unicode Byte Order Mark) and removes it as necessary. -func SkipOnly(rd io.Reader) *Reader { - r, _ := Skip(rd) - return r -} - -// Reader implements automatic BOM (Unicode Byte Order Mark) checking and -// removing as necessary for an io.Reader object. -type Reader struct { - rd io.Reader // reader provided by the client - buf []byte // buffered data - err error // last error -} - -// Read is an implementation of io.Reader interface. -// The bytes are taken from the underlying Reader, but it checks for BOMs, removing them as necessary. -func (r *Reader) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - - if r.buf == nil { - if r.err != nil { - return 0, r.readErr() - } - - return r.rd.Read(p) - } - - // copy as much as we can - n = copy(p, r.buf) - r.buf = nilIfEmpty(r.buf[n:]) - return n, nil -} - -func (r *Reader) readErr() error { - err := r.err - r.err = nil - return err -} - -var errNegativeRead = errors.New("utfbom: reader returned negative count from Read") - -func detectUtf(rd io.Reader) (enc Encoding, buf []byte, err error) { - buf, err = readBOM(rd) - - if len(buf) >= 4 { - if isUTF32BigEndianBOM4(buf) { - return UTF32BigEndian, nilIfEmpty(buf[4:]), err - } - if isUTF32LittleEndianBOM4(buf) { - return UTF32LittleEndian, nilIfEmpty(buf[4:]), err - } - } - - if len(buf) > 2 && isUTF8BOM3(buf) { - return UTF8, nilIfEmpty(buf[3:]), err - } - - if (err != nil && err != io.EOF) || (len(buf) < 2) { - return Unknown, nilIfEmpty(buf), err - } - - if isUTF16BigEndianBOM2(buf) { - return UTF16BigEndian, nilIfEmpty(buf[2:]), err - } - if isUTF16LittleEndianBOM2(buf) { - return UTF16LittleEndian, nilIfEmpty(buf[2:]), err - } - - return Unknown, nilIfEmpty(buf), err -} - -func readBOM(rd io.Reader) (buf []byte, err error) { - const maxBOMSize = 4 - var bom [maxBOMSize]byte // used to read BOM - - // read as many bytes as possible - for nEmpty, n := 0, 0; err == nil && len(buf) < maxBOMSize; buf = bom[:len(buf)+n] { - if n, err = rd.Read(bom[len(buf):]); n < 0 { - panic(errNegativeRead) - } - if n > 0 { - nEmpty = 0 - } else { - nEmpty++ - if nEmpty >= maxConsecutiveEmptyReads { - err = io.ErrNoProgress - } - } - } - return -} - -func isUTF32BigEndianBOM4(buf []byte) bool { - return buf[0] == 0x00 && buf[1] == 0x00 && buf[2] == 0xFE && buf[3] == 0xFF -} - -func isUTF32LittleEndianBOM4(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE && buf[2] == 0x00 && buf[3] == 0x00 -} - -func isUTF8BOM3(buf []byte) bool { - return buf[0] == 0xEF && buf[1] == 0xBB && buf[2] == 0xBF -} - -func isUTF16BigEndianBOM2(buf []byte) bool { - return buf[0] == 0xFE && buf[1] == 0xFF -} - -func isUTF16LittleEndianBOM2(buf []byte) bool { - return buf[0] == 0xFF && buf[1] == 0xFE -} - -func nilIfEmpty(buf []byte) (res []byte) { - if len(buf) > 0 { - res = buf - } - return -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt b/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt deleted file mode 100644 index 3c2f300e1..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/LICENSE.txt +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014-2018 Aetrion LLC dba DNSimple - -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/dnsimple/dnsimple-go/dnsimple/accounts.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/accounts.go deleted file mode 100644 index 2f86ed305..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/accounts.go +++ /dev/null @@ -1,41 +0,0 @@ -package dnsimple - -type AccountsService struct { - client *Client -} - -// Account represents a DNSimple account. -type Account struct { - ID int64 `json:"id,omitempty"` - Email string `json:"email,omitempty"` - PlanIdentifier string `json:"plan_identifier,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// accountsResponse represents a response from an API method that returns a collection of Account struct. -type accountsResponse struct { - Response - Data []Account `json:"data"` -} - -// ListAccounts list the accounts for an user. -// -// See https://developer.dnsimple.com/v2/accounts/#list -func (s *AccountsService) ListAccounts(options *ListOptions) (*accountsResponse, error) { - path := versioned("/accounts") - accountsResponse := &accountsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, accountsResponse) - if err != nil { - return accountsResponse, err - } - - accountsResponse.HttpResponse = resp - return accountsResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go deleted file mode 100644 index dac6f51b3..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/authentication.go +++ /dev/null @@ -1,52 +0,0 @@ -package dnsimple - -import ( - "net/http" -) - -// BasicAuthTransport is an http.RoundTripper that authenticates all requests -// using HTTP Basic Authentication with the provided username and password. -type BasicAuthTransport struct { - Username string - Password string - - // Transport is the transport RoundTripper used to make HTTP requests. - // If nil, http.DefaultTransport is used. - Transport http.RoundTripper -} - -// RoundTrip implements the RoundTripper interface. We just add the -// basic auth and return the RoundTripper for this transport type. -func (t *BasicAuthTransport) RoundTrip(req *http.Request) (*http.Response, error) { - req2 := cloneRequest(req) // per RoundTripper contract - - req2.SetBasicAuth(t.Username, t.Password) - return t.transport().RoundTrip(req2) -} - -// Client returns an *http.Client that uses the BasicAuthTransport transport -// to authenticate the request via HTTP Basic Auth. -func (t *BasicAuthTransport) Client() *http.Client { - return &http.Client{Transport: t} -} - -func (t *BasicAuthTransport) transport() http.RoundTripper { - if t.Transport != nil { - return t.Transport - } - return http.DefaultTransport -} - -// 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 -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go deleted file mode 100644 index 84ddba094..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/certificates.go +++ /dev/null @@ -1,249 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// CertificatesService handles communication with the certificate related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/certificates -type CertificatesService struct { - client *Client -} - -// Certificate represents a Certificate in DNSimple. -type Certificate struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` - CommonName string `json:"common_name,omitempty"` - AlternateNames []string `json:"alternate_names,omitempty"` - Years int `json:"years,omitempty"` - State string `json:"state,omitempty"` - AuthorityIdentifier string `json:"authority_identifier,omitempty"` - AutoRenew bool `json:"auto_renew"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CertificateRequest string `json:"csr,omitempty"` -} - -// CertificateBundle represents a container for all the PEM-encoded X509 certificate entities, -// such as the private key, the server certificate and the intermediate chain. -type CertificateBundle struct { - // CertificateRequest string `json:"csr,omitempty"` - PrivateKey string `json:"private_key,omitempty"` - ServerCertificate string `json:"server,omitempty"` - RootCertificate string `json:"root,omitempty"` - IntermediateCertificates []string `json:"chain,omitempty"` -} - -// CertificatePurchase represents a Certificate Purchase in DNSimple. -type CertificatePurchase struct { - ID int64 `json:"id,omitempty"` - CertificateID int64 `json:"new_certificate_id,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// CertificateRenewal represents a Certificate Renewal in DNSimple. -type CertificateRenewal struct { - ID int64 `json:"id,omitempty"` - OldCertificateID int64 `json:"old_certificate_id,omitempty"` - NewCertificateID int64 `json:"new_certificate_id,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// LetsencryptCertificateAttributes is a set of attributes to purchase a Let's Encrypt certificate. -type LetsencryptCertificateAttributes struct { - ContactID int64 `json:"contact_id,omitempty"` - Name string `json:"name,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - AlternateNames []string `json:"alternate_names,omitempty"` -} - -func certificatePath(accountID, domainIdentifier string, certificateID int64) (path string) { - path = fmt.Sprintf("%v/certificates", domainPath(accountID, domainIdentifier)) - if certificateID != 0 { - path += fmt.Sprintf("/%v", certificateID) - } - return -} - -func letsencryptCertificatePath(accountID, domainIdentifier string, certificateID int64) (path string) { - path = fmt.Sprintf("%v/certificates/letsencrypt", domainPath(accountID, domainIdentifier)) - if certificateID != 0 { - path += fmt.Sprintf("/%v", certificateID) - } - return -} - -// certificateResponse represents a response from an API method that returns a Certificate struct. -type certificateResponse struct { - Response - Data *Certificate `json:"data"` -} - -// certificateBundleResponse represents a response from an API method that returns a CertificatBundle struct. -type certificateBundleResponse struct { - Response - Data *CertificateBundle `json:"data"` -} - -// certificatesResponse represents a response from an API method that returns a collection of Certificate struct. -type certificatesResponse struct { - Response - Data []Certificate `json:"data"` -} - -// certificatePurchaseResponse represents a response from an API method that returns a CertificatePurchase struct. -type certificatePurchaseResponse struct { - Response - Data *CertificatePurchase `json:"data"` -} - -// certificateRenewalResponse represents a response from an API method that returns a CertificateRenewal struct. -type certificateRenewalResponse struct { - Response - Data *CertificateRenewal `json:"data"` -} - -// ListCertificates lists the certificates for a domain in the account. -// -// See https://developer.dnsimple.com/v2/certificates#listCertificates -func (s *CertificatesService) ListCertificates(accountID, domainIdentifier string, options *ListOptions) (*certificatesResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, 0)) - certificatesResponse := &certificatesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, certificatesResponse) - if err != nil { - return certificatesResponse, err - } - - certificatesResponse.HttpResponse = resp - return certificatesResponse, nil -} - -// GetCertificate gets the details of a certificate. -// -// See https://developer.dnsimple.com/v2/certificates#getCertificate -func (s *CertificatesService) GetCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID)) - certificateResponse := &certificateResponse{} - - resp, err := s.client.get(path, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} - -// DownloadCertificate gets the PEM-encoded certificate, -// along with the root certificate and intermediate chain. -// -// See https://developer.dnsimple.com/v2/certificates#downloadCertificate -func (s *CertificatesService) DownloadCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateBundleResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID) + "/download") - certificateBundleResponse := &certificateBundleResponse{} - - resp, err := s.client.get(path, certificateBundleResponse) - if err != nil { - return nil, err - } - - certificateBundleResponse.HttpResponse = resp - return certificateBundleResponse, nil -} - -// GetCertificatePrivateKey gets the PEM-encoded certificate private key. -// -// See https://developer.dnsimple.com/v2/certificates#getCertificatePrivateKey -func (s *CertificatesService) GetCertificatePrivateKey(accountID, domainIdentifier string, certificateID int64) (*certificateBundleResponse, error) { - path := versioned(certificatePath(accountID, domainIdentifier, certificateID) + "/private_key") - certificateBundleResponse := &certificateBundleResponse{} - - resp, err := s.client.get(path, certificateBundleResponse) - if err != nil { - return nil, err - } - - certificateBundleResponse.HttpResponse = resp - return certificateBundleResponse, nil -} - -// PurchaseLetsencryptCertificate purchases a Let's Encrypt certificate. -// -// See https://developer.dnsimple.com/v2/certificates/#purchaseLetsencryptCertificate -func (s *CertificatesService) PurchaseLetsencryptCertificate(accountID, domainIdentifier string, certificateAttributes LetsencryptCertificateAttributes) (*certificatePurchaseResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, 0)) - certificatePurchaseResponse := &certificatePurchaseResponse{} - - resp, err := s.client.post(path, certificateAttributes, certificatePurchaseResponse) - if err != nil { - return nil, err - } - - certificatePurchaseResponse.HttpResponse = resp - return certificatePurchaseResponse, nil -} - -// IssueLetsencryptCertificate issues a pending Let's Encrypt certificate purchase order. -// -// See https://developer.dnsimple.com/v2/certificates/#issueLetsencryptCertificate -func (s *CertificatesService) IssueLetsencryptCertificate(accountID, domainIdentifier string, certificateID int64) (*certificateResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + "/issue") - certificateResponse := &certificateResponse{} - - resp, err := s.client.post(path, nil, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} - -// PurchaseLetsencryptCertificateRenewal purchases a Let's Encrypt certificate renewal. -// -// See https://developer.dnsimple.com/v2/certificates/#purchaseRenewalLetsencryptCertificate -func (s *CertificatesService) PurchaseLetsencryptCertificateRenewal(accountID, domainIdentifier string, certificateID int64, certificateAttributes LetsencryptCertificateAttributes) (*certificateRenewalResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + "/renewals") - certificateRenewalResponse := &certificateRenewalResponse{} - - resp, err := s.client.post(path, certificateAttributes, certificateRenewalResponse) - if err != nil { - return nil, err - } - - certificateRenewalResponse.HttpResponse = resp - return certificateRenewalResponse, nil -} - -// IssueLetsencryptCertificateRenewal issues a pending Let's Encrypt certificate renewal order. -// -// See https://developer.dnsimple.com/v2/certificates/#issueRenewalLetsencryptCertificate -func (s *CertificatesService) IssueLetsencryptCertificateRenewal(accountID, domainIdentifier string, certificateID, certificateRenewalID int64) (*certificateResponse, error) { - path := versioned(letsencryptCertificatePath(accountID, domainIdentifier, certificateID) + fmt.Sprintf("/renewals/%d/issue", certificateRenewalID)) - certificateResponse := &certificateResponse{} - - resp, err := s.client.post(path, nil, certificateResponse) - if err != nil { - return nil, err - } - - certificateResponse.HttpResponse = resp - return certificateResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go deleted file mode 100644 index d35cffef9..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/contacts.go +++ /dev/null @@ -1,140 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ContactsService handles communication with the contact related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/contacts/ -type ContactsService struct { - client *Client -} - -// Contact represents a Contact in DNSimple. -type Contact struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Label string `json:"label,omitempty"` - FirstName string `json:"first_name,omitempty"` - LastName string `json:"last_name,omitempty"` - JobTitle string `json:"job_title,omitempty"` - Organization string `json:"organization_name,omitempty"` - Address1 string `json:"address1,omitempty"` - Address2 string `json:"address2,omitempty"` - City string `json:"city,omitempty"` - StateProvince string `json:"state_province,omitempty"` - PostalCode string `json:"postal_code,omitempty"` - Country string `json:"country,omitempty"` - Phone string `json:"phone,omitempty"` - Fax string `json:"fax,omitempty"` - Email string `json:"email,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func contactPath(accountID string, contactID int64) (path string) { - path = fmt.Sprintf("/%v/contacts", accountID) - if contactID != 0 { - path += fmt.Sprintf("/%v", contactID) - } - return -} - -// contactResponse represents a response from an API method that returns a Contact struct. -type contactResponse struct { - Response - Data *Contact `json:"data"` -} - -// contactsResponse represents a response from an API method that returns a collection of Contact struct. -type contactsResponse struct { - Response - Data []Contact `json:"data"` -} - -// ListContacts list the contacts for an account. -// -// See https://developer.dnsimple.com/v2/contacts/#list -func (s *ContactsService) ListContacts(accountID string, options *ListOptions) (*contactsResponse, error) { - path := versioned(contactPath(accountID, 0)) - contactsResponse := &contactsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, contactsResponse) - if err != nil { - return contactsResponse, err - } - - contactsResponse.HttpResponse = resp - return contactsResponse, nil -} - -// CreateContact creates a new contact. -// -// See https://developer.dnsimple.com/v2/contacts/#create -func (s *ContactsService) CreateContact(accountID string, contactAttributes Contact) (*contactResponse, error) { - path := versioned(contactPath(accountID, 0)) - contactResponse := &contactResponse{} - - resp, err := s.client.post(path, contactAttributes, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// GetContact fetches a contact. -// -// See https://developer.dnsimple.com/v2/contacts/#get -func (s *ContactsService) GetContact(accountID string, contactID int64) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.get(path, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// UpdateContact updates a contact. -// -// See https://developer.dnsimple.com/v2/contacts/#update -func (s *ContactsService) UpdateContact(accountID string, contactID int64, contactAttributes Contact) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.patch(path, contactAttributes, contactResponse) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} - -// DeleteContact PERMANENTLY deletes a contact from the account. -// -// See https://developer.dnsimple.com/v2/contacts/#delete -func (s *ContactsService) DeleteContact(accountID string, contactID int64) (*contactResponse, error) { - path := versioned(contactPath(accountID, contactID)) - contactResponse := &contactResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - contactResponse.HttpResponse = resp - return contactResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go deleted file mode 100644 index 6c32e1632..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/dnsimple.go +++ /dev/null @@ -1,338 +0,0 @@ -// Package dnsimple provides a client for the DNSimple API. -// In order to use this package you will need a DNSimple account. -package dnsimple - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "log" - "net/http" - "net/url" - "reflect" - "strconv" - "strings" - "time" - - "github.com/google/go-querystring/query" -) - -const ( - // Version identifies the current library version. - // This is a pro-forma convention given that Go dependencies - // tends to be fetched directly from the repo. - // It is also used in the user-agent identify the client. - Version = "0.21.0" - - // defaultBaseURL to the DNSimple production API. - defaultBaseURL = "https://api.dnsimple.com" - - // userAgent represents the default user agent used - // when no other user agent is set. - defaultUserAgent = "dnsimple-go/" + Version - - apiVersion = "v2" -) - -// Client represents a client to the DNSimple API. -type Client struct { - // httpClient is the underlying HTTP client - // used to communicate with the API. - httpClient *http.Client - - // BaseURL for API requests. - // Defaults to the public DNSimple API, but can be set to a different endpoint (e.g. the sandbox). - BaseURL string - - // UserAgent used when communicating with the DNSimple API. - UserAgent string - - // Services used for talking to different parts of the DNSimple API. - Identity *IdentityService - Accounts *AccountsService - Certificates *CertificatesService - Contacts *ContactsService - Domains *DomainsService - Oauth *OauthService - Registrar *RegistrarService - Services *ServicesService - Templates *TemplatesService - Tlds *TldsService - VanityNameServers *VanityNameServersService - Webhooks *WebhooksService - Zones *ZonesService - - // Set to true to output debugging logs during API calls - Debug bool -} - -// ListOptions contains the common options you can pass to a List method -// in order to control parameters such as paginations and page number. -type ListOptions struct { - // The page to return - Page int `url:"page,omitempty"` - - // The number of entries to return per page - PerPage int `url:"per_page,omitempty"` - - // The order criteria to sort the results. - // The value is a comma-separated list of field[:direction], - // eg. name | name:desc | name:desc,expiration:desc - Sort string `url:"sort,omitempty"` -} - -// NewClient returns a new DNSimple API client. -// -// To authenticate you must provide an http.Client that will perform authentication -// for you with one of the currently supported mechanisms: OAuth or HTTP Basic. -func NewClient(httpClient *http.Client) *Client { - c := &Client{httpClient: httpClient, BaseURL: defaultBaseURL} - c.Identity = &IdentityService{client: c} - c.Accounts = &AccountsService{client: c} - c.Certificates = &CertificatesService{client: c} - c.Contacts = &ContactsService{client: c} - c.Domains = &DomainsService{client: c} - c.Oauth = &OauthService{client: c} - c.Registrar = &RegistrarService{client: c} - c.Services = &ServicesService{client: c} - c.Templates = &TemplatesService{client: c} - c.Tlds = &TldsService{client: c} - c.VanityNameServers = &VanityNameServersService{client: c} - c.Webhooks = &WebhooksService{client: c} - c.Zones = &ZonesService{client: c} - return c -} - -// NewRequest creates an API request. -// The path is expected to be a relative path and will be resolved -// according to the BaseURL of the Client. Paths should always be specified without a preceding slash. -func (c *Client) NewRequest(method, path string, payload interface{}) (*http.Request, error) { - url := c.BaseURL + path - - body := new(bytes.Buffer) - if payload != nil { - err := json.NewEncoder(body).Encode(payload) - if err != nil { - return nil, err - } - } - - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - req.Header.Add("User-Agent", formatUserAgent(c.UserAgent)) - - return req, nil -} - -// formatUserAgent builds the final user agent to use for HTTP requests. -// -// If no custom user agent is provided, the default user agent is used. -// -// dnsimple-go/1.0 -// -// If a custom user agent is provided, the final user agent is the combination of the custom user agent -// prepended by the default user agent. -// -// dnsimple-go/1.0 customAgentFlag -// -func formatUserAgent(customUserAgent string) string { - if customUserAgent == "" { - return defaultUserAgent - } - - return fmt.Sprintf("%s %s", defaultUserAgent, customUserAgent) -} - -func versioned(path string) string { - return fmt.Sprintf("/%s/%s", apiVersion, strings.Trim(path, "/")) -} - -func (c *Client) get(path string, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("GET", path, nil) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) post(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("POST", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) put(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("PUT", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) patch(path string, payload, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("PATCH", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -func (c *Client) delete(path string, payload interface{}, obj interface{}) (*http.Response, error) { - req, err := c.NewRequest("DELETE", path, payload) - if err != nil { - return nil, err - } - - return c.Do(req, obj) -} - -// Do sends an API request and returns the API response. -// -// The API response is JSON decoded and stored in the value pointed by obj, -// or returned as an error if an API error has occurred. -// If obj implements the io.Writer interface, the raw response body will be written to obj, -// without attempting to decode it. -func (c *Client) Do(req *http.Request, obj interface{}) (*http.Response, error) { - if c.Debug { - log.Printf("Executing request (%v): %#v", req.URL, req) - } - - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if c.Debug { - log.Printf("Response received: %#v", resp) - } - - err = CheckResponse(resp) - if err != nil { - return resp, err - } - - // If obj implements the io.Writer, - // the response body is decoded into v. - if obj != nil { - if w, ok := obj.(io.Writer); ok { - _, err = io.Copy(w, resp.Body) - } else { - err = json.NewDecoder(resp.Body).Decode(obj) - } - } - - return resp, err -} - -// A Response represents an API response. -type Response struct { - // HTTP response - HttpResponse *http.Response - - // If the response is paginated, the Pagination will store them. - Pagination *Pagination `json:"pagination"` -} - -// RateLimit returns the maximum amount of requests this account can send in an hour. -func (r *Response) RateLimit() int { - value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Limit")) - return value -} - -// RateLimitRemaining returns the remaining amount of requests this account can send within this hour window. -func (r *Response) RateLimitRemaining() int { - value, _ := strconv.Atoi(r.HttpResponse.Header.Get("X-RateLimit-Remaining")) - return value -} - -// RateLimitReset returns when the throttling window will be reset for this account. -func (r *Response) RateLimitReset() time.Time { - value, _ := strconv.ParseInt(r.HttpResponse.Header.Get("X-RateLimit-Reset"), 10, 64) - return time.Unix(value, 0) -} - -// If the response is paginated, Pagination represents the pagination information. -type Pagination struct { - CurrentPage int `json:"current_page"` - PerPage int `json:"per_page"` - TotalPages int `json:"total_pages"` - TotalEntries int `json:"total_entries"` -} - -// An ErrorResponse represents an API response that generated an error. -type ErrorResponse struct { - Response - - // human-readable message - Message string `json:"message"` -} - -// Error implements the error interface. -func (r *ErrorResponse) Error() string { - return fmt.Sprintf("%v %v: %v %v", - r.HttpResponse.Request.Method, r.HttpResponse.Request.URL, - r.HttpResponse.StatusCode, r.Message) -} - -// CheckResponse checks the API response for errors, and returns them if present. -// A response is considered an error if the status code is different than 2xx. Specific requests -// may have additional requirements, but this is sufficient in most of the cases. -func CheckResponse(resp *http.Response) error { - if code := resp.StatusCode; 200 <= code && code <= 299 { - return nil - } - - errorResponse := &ErrorResponse{} - errorResponse.HttpResponse = resp - - err := json.NewDecoder(resp.Body).Decode(errorResponse) - if err != nil { - return err - } - - return errorResponse -} - -// addOptions adds the parameters in opt as URL query parameters to s. opt -// must be a struct whose fields may contain "url" tags. -func addURLQueryOptions(path string, options interface{}) (string, error) { - opt := reflect.ValueOf(options) - - // options is a pointer - // return if the value of the pointer is nil, - if opt.Kind() == reflect.Ptr && opt.IsNil() { - return path, nil - } - - // append the options to the URL - u, err := url.Parse(path) - if err != nil { - return path, err - } - - qs, err := query.Values(options) - if err != nil { - return path, err - } - - uqs := u.Query() - for k, _ := range qs { - uqs.Set(k, qs.Get(k)) - } - u.RawQuery = uqs.Encode() - - return u.String(), nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go deleted file mode 100644 index 6cd8fd7fb..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains.go +++ /dev/null @@ -1,146 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// DomainsService handles communication with the domain related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/domains/ -type DomainsService struct { - client *Client -} - -// Domain represents a domain in DNSimple. -type Domain struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - RegistrantID int64 `json:"registrant_id,omitempty"` - Name string `json:"name,omitempty"` - UnicodeName string `json:"unicode_name,omitempty"` - Token string `json:"token,omitempty"` - State string `json:"state,omitempty"` - AutoRenew bool `json:"auto_renew,omitempty"` - PrivateWhois bool `json:"private_whois,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func domainPath(accountID string, domainIdentifier string) (path string) { - path = fmt.Sprintf("/%v/domains", accountID) - if domainIdentifier != "" { - path += fmt.Sprintf("/%v", domainIdentifier) - } - return -} - -// domainResponse represents a response from an API method that returns a Domain struct. -type domainResponse struct { - Response - Data *Domain `json:"data"` -} - -// domainsResponse represents a response from an API method that returns a collection of Domain struct. -type domainsResponse struct { - Response - Data []Domain `json:"data"` -} - -// DomainListOptions specifies the optional parameters you can provide -// to customize the DomainsService.ListDomains method. -type DomainListOptions struct { - // Select domains where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - // Select domains where the registrant matches given ID. - RegistrantID int `url:"registrant_id,omitempty"` - - ListOptions -} - -// ListDomains lists the domains for an account. -// -// See https://developer.dnsimple.com/v2/domains/#list -func (s *DomainsService) ListDomains(accountID string, options *DomainListOptions) (*domainsResponse, error) { - path := versioned(domainPath(accountID, "")) - domainsResponse := &domainsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, domainsResponse) - if err != nil { - return nil, err - } - - domainsResponse.HttpResponse = resp - return domainsResponse, nil -} - -// CreateDomain creates a new domain in the account. -// -// See https://developer.dnsimple.com/v2/domains/#create -func (s *DomainsService) CreateDomain(accountID string, domainAttributes Domain) (*domainResponse, error) { - path := versioned(domainPath(accountID, "")) - domainResponse := &domainResponse{} - - resp, err := s.client.post(path, domainAttributes, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// GetDomain fetches a domain. -// -// See https://developer.dnsimple.com/v2/domains/#get -func (s *DomainsService) GetDomain(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier)) - domainResponse := &domainResponse{} - - resp, err := s.client.get(path, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// DeleteDomain PERMANENTLY deletes a domain from the account. -// -// See https://developer.dnsimple.com/v2/domains/#delete -func (s *DomainsService) DeleteDomain(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier)) - domainResponse := &domainResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// ResetDomainToken resets the domain token. -// -// See https://developer.dnsimple.com/v2/domains/#reset-token -func (s *DomainsService) ResetDomainToken(accountID string, domainIdentifier string) (*domainResponse, error) { - path := versioned(domainPath(accountID, domainIdentifier) + "/token") - domainResponse := &domainResponse{} - - resp, err := s.client.post(path, nil, domainResponse) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go deleted file mode 100644 index da0513996..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_collaborators.go +++ /dev/null @@ -1,96 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Collaborator represents a Collaborator in DNSimple. -type Collaborator struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - DomainName string `json:"domain_name,omitempty"` - UserID int64 `json:"user_id,omitempty"` - UserEmail string `json:"user_email,omitempty"` - Invitation bool `json:"invitation,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - AcceptedAt string `json:"accepted_at,omitempty"` -} - -func collaboratorPath(accountID, domainIdentifier string, collaboratorID int64) (path string) { - path = fmt.Sprintf("%v/collaborators", domainPath(accountID, domainIdentifier)) - if collaboratorID != 0 { - path += fmt.Sprintf("/%v", collaboratorID) - } - return -} - -// CollaboratorAttributes represents Collaborator attributes for AddCollaborator operation. -type CollaboratorAttributes struct { - Email string `json:"email,omitempty"` -} - -// collaboratorResponse represents a response from an API method that returns a Collaborator struct. -type collaboratorResponse struct { - Response - Data *Collaborator `json:"data"` -} - -// collaboratorsResponse represents a response from an API method that returns a collection of Collaborator struct. -type collaboratorsResponse struct { - Response - Data []Collaborator `json:"data"` -} - -// ListCollaborators list the collaborators for a domain. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#list -func (s *DomainsService) ListCollaborators(accountID, domainIdentifier string, options *ListOptions) (*collaboratorsResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, 0)) - collaboratorsResponse := &collaboratorsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, collaboratorsResponse) - if err != nil { - return collaboratorsResponse, err - } - - collaboratorsResponse.HttpResponse = resp - return collaboratorsResponse, nil -} - -// AddCollaborator adds a new collaborator to the domain in the account. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#add -func (s *DomainsService) AddCollaborator(accountID string, domainIdentifier string, attributes CollaboratorAttributes) (*collaboratorResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, 0)) - collaboratorResponse := &collaboratorResponse{} - - resp, err := s.client.post(path, attributes, collaboratorResponse) - if err != nil { - return nil, err - } - - collaboratorResponse.HttpResponse = resp - return collaboratorResponse, nil -} - -// RemoveCollaborator PERMANENTLY deletes a domain from the account. -// -// See https://developer.dnsimple.com/v2/domains/collaborators#remove -func (s *DomainsService) RemoveCollaborator(accountID string, domainIdentifier string, collaboratorID int64) (*collaboratorResponse, error) { - path := versioned(collaboratorPath(accountID, domainIdentifier, collaboratorID)) - collaboratorResponse := &collaboratorResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - collaboratorResponse.HttpResponse = resp - return collaboratorResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go deleted file mode 100644 index f2f0092de..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_delegation_signer_records.go +++ /dev/null @@ -1,105 +0,0 @@ -package dnsimple - -import "fmt" - -// DelegationSignerRecord represents a delegation signer record for a domain in DNSimple. -type DelegationSignerRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Algorithm string `json:"algorithm"` - Digest string `json:"digest"` - DigestType string `json:"digest_type"` - Keytag string `json:"keytag"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func delegationSignerRecordPath(accountID string, domainIdentifier string, dsRecordID int64) (path string) { - path = fmt.Sprintf("%v/ds_records", domainPath(accountID, domainIdentifier)) - if dsRecordID != 0 { - path += fmt.Sprintf("/%v", dsRecordID) - } - return -} - -// delegationSignerRecordResponse represents a response from an API method that returns a DelegationSignerRecord struct. -type delegationSignerRecordResponse struct { - Response - Data *DelegationSignerRecord `json:"data"` -} - -// delegationSignerRecordResponse represents a response from an API method that returns a DelegationSignerRecord struct. -type delegationSignerRecordsResponse struct { - Response - Data []DelegationSignerRecord `json:"data"` -} - -// ListDelegationSignerRecords lists the delegation signer records for a domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-list -func (s *DomainsService) ListDelegationSignerRecords(accountID string, domainIdentifier string, options *ListOptions) (*delegationSignerRecordsResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0)) - dsRecordsResponse := &delegationSignerRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, dsRecordsResponse) - if err != nil { - return nil, err - } - - dsRecordsResponse.HttpResponse = resp - return dsRecordsResponse, nil -} - -// CreateDelegationSignerRecord creates a new delegation signer record. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-create -func (s *DomainsService) CreateDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordAttributes DelegationSignerRecord) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, 0)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.post(path, dsRecordAttributes, dsRecordResponse) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} - -// GetDelegationSignerRecord fetches a delegation signer record. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-get -func (s *DomainsService) GetDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordID int64) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, dsRecordID)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.get(path, dsRecordResponse) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} - -// DeleteDelegationSignerRecord PERMANENTLY deletes a delegation signer record -// from the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#ds-record-delete -func (s *DomainsService) DeleteDelegationSignerRecord(accountID string, domainIdentifier string, dsRecordID int64) (*delegationSignerRecordResponse, error) { - path := versioned(delegationSignerRecordPath(accountID, domainIdentifier, dsRecordID)) - dsRecordResponse := &delegationSignerRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - dsRecordResponse.HttpResponse = resp - return dsRecordResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go deleted file mode 100644 index 1ef054bcc..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_dnssec.go +++ /dev/null @@ -1,70 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Dnssec represents the current DNSSEC settings for a domain in DNSimple. -type Dnssec struct { - Enabled bool `json:"enabled"` -} - -func dnssecPath(accountID string, domainIdentifier string) (path string) { - path = fmt.Sprintf("%v/dnssec", domainPath(accountID, domainIdentifier)) - return -} - -// dnssecResponse represents a response from an API method that returns a Dnssec struct. -type dnssecResponse struct { - Response - Data *Dnssec `json:"data"` -} - -// EnableDnssec enables DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#enable - -func (s *DomainsService) EnableDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.post(path, dnssecResponse, nil) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} - -// DisableDnssec disables DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#disable -func (s *DomainsService) DisableDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.delete(path, dnssecResponse, nil) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} - -// GetDnssec retrieves the current status of DNSSEC on the domain. -// -// See https://developer.dnsimple.com/v2/domains/dnssec/#get -func (s *DomainsService) GetDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) { - path := versioned(dnssecPath(accountID, domainIdentifier)) - dnssecResponse := &dnssecResponse{} - - resp, err := s.client.get(path, dnssecResponse) - if err != nil { - return nil, err - } - - dnssecResponse.HttpResponse = resp - return dnssecResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go deleted file mode 100644 index 3d4299ac5..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_email_forwards.go +++ /dev/null @@ -1,104 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// EmailForward represents an email forward in DNSimple. -type EmailForward struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - From string `json:"from,omitempty"` - To string `json:"to,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func emailForwardPath(accountID string, domainIdentifier string, forwardID int64) (path string) { - path = fmt.Sprintf("%v/email_forwards", domainPath(accountID, domainIdentifier)) - if forwardID != 0 { - path += fmt.Sprintf("/%v", forwardID) - } - return -} - -// emailForwardResponse represents a response from an API method that returns an EmailForward struct. -type emailForwardResponse struct { - Response - Data *EmailForward `json:"data"` -} - -// emailForwardsResponse represents a response from an API method that returns a collection of EmailForward struct. -type emailForwardsResponse struct { - Response - Data []EmailForward `json:"data"` -} - -// ListEmailForwards lists the email forwards for a domain. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#list -func (s *DomainsService) ListEmailForwards(accountID string, domainIdentifier string, options *ListOptions) (*emailForwardsResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, 0)) - forwardsResponse := &emailForwardsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, forwardsResponse) - if err != nil { - return nil, err - } - - forwardsResponse.HttpResponse = resp - return forwardsResponse, nil -} - -// CreateEmailForward creates a new email forward. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#create -func (s *DomainsService) CreateEmailForward(accountID string, domainIdentifier string, forwardAttributes EmailForward) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, 0)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.post(path, forwardAttributes, forwardResponse) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} - -// GetEmailForward fetches an email forward. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#get -func (s *DomainsService) GetEmailForward(accountID string, domainIdentifier string, forwardID int64) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, forwardID)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.get(path, forwardResponse) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} - -// DeleteEmailForward PERMANENTLY deletes an email forward from the domain. -// -// See https://developer.dnsimple.com/v2/domains/email-forwards/#delete -func (s *DomainsService) DeleteEmailForward(accountID string, domainIdentifier string, forwardID int64) (*emailForwardResponse, error) { - path := versioned(emailForwardPath(accountID, domainIdentifier, forwardID)) - forwardResponse := &emailForwardResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - forwardResponse.HttpResponse = resp - return forwardResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go deleted file mode 100644 index b965c7daf..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/domains_pushes.go +++ /dev/null @@ -1,111 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// DomainPush represents a domain push in DNSimple. -type DomainPush struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - AcceptedAt string `json:"accepted_at,omitempty"` -} - -func domainPushPath(accountID string, pushID int64) (path string) { - path = fmt.Sprintf("/%v/pushes", accountID) - if pushID != 0 { - path += fmt.Sprintf("/%v", pushID) - } - return -} - -// domainPushResponse represents a response from an API method that returns a DomainPush struct. -type domainPushResponse struct { - Response - Data *DomainPush `json:"data"` -} - -// domainPushesResponse represents a response from an API method that returns a collection of DomainPush struct. -type domainPushesResponse struct { - Response - Data []DomainPush `json:"data"` -} - -// DomainPushAttributes represent a domain push payload (see initiate). -type DomainPushAttributes struct { - NewAccountEmail string `json:"new_account_email,omitempty"` - ContactID int64 `json:"contact_id,omitempty"` -} - -// InitiatePush initiate a new domain push. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#initiate -func (s *DomainsService) InitiatePush(accountID, domainID string, pushAttributes DomainPushAttributes) (*domainPushResponse, error) { - path := versioned(fmt.Sprintf("/%v/pushes", domainPath(accountID, domainID))) - pushResponse := &domainPushResponse{} - - resp, err := s.client.post(path, pushAttributes, pushResponse) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} - -// ListPushes lists the pushes for an account. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#list -func (s *DomainsService) ListPushes(accountID string, options *ListOptions) (*domainPushesResponse, error) { - path := versioned(domainPushPath(accountID, 0)) - pushesResponse := &domainPushesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, pushesResponse) - if err != nil { - return nil, err - } - - pushesResponse.HttpResponse = resp - return pushesResponse, nil -} - -// AcceptPush accept a push for a domain. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#accept -func (s *DomainsService) AcceptPush(accountID string, pushID int64, pushAttributes DomainPushAttributes) (*domainPushResponse, error) { - path := versioned(domainPushPath(accountID, pushID)) - pushResponse := &domainPushResponse{} - - resp, err := s.client.post(path, pushAttributes, nil) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} - -// RejectPush reject a push for a domain. -// -// See https://developer.dnsimple.com/v2/domains/pushes/#reject -func (s *DomainsService) RejectPush(accountID string, pushID int64) (*domainPushResponse, error) { - path := versioned(domainPushPath(accountID, pushID)) - pushResponse := &domainPushResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - pushResponse.HttpResponse = resp - return pushResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go deleted file mode 100644 index be7ca9ea8..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/identity.go +++ /dev/null @@ -1,48 +0,0 @@ -package dnsimple - -// IdentityService handles communication with several authentication identity -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/identity/ -type IdentityService struct { - client *Client -} - -// WhoamiData represents an authenticated context -// that contains information about the current logged User and/or Account. -type WhoamiData struct { - User *User `json:"user,omitempty"` - Account *Account `json:"account,omitempty"` -} - -// whoamiResponse represents a response from an API method that returns a Whoami struct. -type whoamiResponse struct { - Response - Data *WhoamiData `json:"data"` -} - -// Whoami gets the current authenticate context. -// -// See https://developer.dnsimple.com/v2/whoami -func (s *IdentityService) Whoami() (*whoamiResponse, error) { - path := versioned("/whoami") - whoamiResponse := &whoamiResponse{} - - resp, err := s.client.get(path, whoamiResponse) - if err != nil { - return nil, err - } - - whoamiResponse.HttpResponse = resp - return whoamiResponse, nil -} - -// Whoami is a state-less shortcut to client.Whoami() -// that returns only the relevant Data. -func Whoami(c *Client) (data *WhoamiData, err error) { - resp, err := c.Identity.Whoami() - if resp != nil { - data = resp.Data - } - return -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go deleted file mode 100644 index 74a2b34a2..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/oauth.go +++ /dev/null @@ -1,113 +0,0 @@ -package dnsimple - -import ( - "encoding/json" - "fmt" - "net/http" - "net/url" - "strings" -) - -// GrantType is a string that identifies a particular grant type in the exchange request. -type GrantType string - -const ( - // AuthorizationCodeGrant is the type of access token request - // for an Authorization Code Grant flow. - // https://tools.ietf.org/html/rfc6749#section-4.1 - AuthorizationCodeGrant = GrantType("authorization_code") -) - -// OauthService handles communication with the authorization related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/oauth/ -type OauthService struct { - client *Client -} - -// AccessToken represents a DNSimple Oauth access token. -type AccessToken struct { - Token string `json:"access_token"` - Type string `json:"token_type"` - AccountID int `json:"account_id"` -} - -// ExchangeAuthorizationRequest represents a request to exchange -// an authorization code for an access token. -// RedirectURI is optional, all the other fields are mandatory. -type ExchangeAuthorizationRequest struct { - Code string `json:"code"` - ClientID string `json:"client_id"` - ClientSecret string `json:"client_secret"` - RedirectURI string `json:"redirect_uri,omitempty"` - State string `json:"state,omitempty"` - GrantType GrantType `json:"grant_type,omitempty"` -} - -// ExchangeAuthorizationError represents a failed request to exchange -// an authorization code for an access token. -type ExchangeAuthorizationError struct { - // HTTP response - HttpResponse *http.Response - - ErrorCode string `json:"error"` - ErrorDescription string `json:"error_description"` -} - -// Error implements the error interface. -func (r *ExchangeAuthorizationError) Error() string { - return fmt.Sprintf("%v %v: %v %v", - r.HttpResponse.Request.Method, r.HttpResponse.Request.URL, - r.ErrorCode, r.ErrorDescription) -} - -// ExchangeAuthorizationForToken exchanges the short-lived authorization code for an access token -// you can use to authenticate your API calls. -func (s *OauthService) ExchangeAuthorizationForToken(authorization *ExchangeAuthorizationRequest) (*AccessToken, error) { - path := versioned("/oauth/access_token") - - req, err := s.client.NewRequest("POST", path, authorization) - if err != nil { - return nil, err - } - - resp, err := s.client.httpClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - errorResponse := &ExchangeAuthorizationError{} - errorResponse.HttpResponse = resp - json.NewDecoder(resp.Body).Decode(errorResponse) - return nil, errorResponse - } - - accessToken := &AccessToken{} - err = json.NewDecoder(resp.Body).Decode(accessToken) - - return accessToken, err -} - -// AuthorizationOptions represents the option you can use to generate an authorization URL. -type AuthorizationOptions struct { - RedirectURI string `url:"redirect_uri,omitempty"` - // A randomly generated string to verify the validity of the request. - // Currently "state" is required by the DNSimple OAuth implementation, so you must specify it. - State string `url:"state,omitempty"` -} - -// AuthorizeURL generates the URL to authorize an user for an application via the OAuth2 flow. -func (s *OauthService) AuthorizeURL(clientID string, options *AuthorizationOptions) string { - uri, _ := url.Parse(strings.Replace(s.client.BaseURL, "api.", "", 1)) - uri.Path = "/oauth/authorize" - query := uri.Query() - query.Add("client_id", clientID) - query.Add("response_type", "code") - uri.RawQuery = query.Encode() - - path, _ := addURLQueryOptions(uri.String(), options) - return path -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go deleted file mode 100644 index 625bbb2dc..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar.go +++ /dev/null @@ -1,261 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// RegistrarService handles communication with the registrar related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/registrar/ -type RegistrarService struct { - client *Client -} - -// DomainCheck represents the result of a domain check. -type DomainCheck struct { - Domain string `json:"domain"` - Available bool `json:"available"` - Premium bool `json:"premium"` -} - -// domainCheckResponse represents a response from a domain check request. -type domainCheckResponse struct { - Response - Data *DomainCheck `json:"data"` -} - -// CheckDomain checks a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#check -func (s *RegistrarService) CheckDomain(accountID string, domainName string) (*domainCheckResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/check", accountID, domainName)) - checkResponse := &domainCheckResponse{} - - resp, err := s.client.get(path, checkResponse) - if err != nil { - return nil, err - } - - checkResponse.HttpResponse = resp - return checkResponse, nil -} - -// DomainPremiumPrice represents the premium price for a premium domain. -type DomainPremiumPrice struct { - // The domain premium price - PremiumPrice string `json:"premium_price"` - // The registrar action. - // Possible values are registration|transfer|renewal - Action string `json:"action"` -} - -// domainPremiumPriceResponse represents a response from a domain premium price request. -type domainPremiumPriceResponse struct { - Response - Data *DomainPremiumPrice `json:"data"` -} - -// DomainPremiumPriceOptions specifies the optional parameters you can provide -// to customize the RegistrarService.GetDomainPremiumPrice method. -type DomainPremiumPriceOptions struct { - Action string `url:"action,omitempty"` -} - -// Gets the premium price for a domain. -// -// You must specify an action to get the price for. Valid actions are: -// - registration -// - transfer -// - renewal -// -// See https://developer.dnsimple.com/v2/registrar/#premium-price -func (s *RegistrarService) GetDomainPremiumPrice(accountID string, domainName string, options *DomainPremiumPriceOptions) (*domainPremiumPriceResponse, error) { - var err error - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/premium_price", accountID, domainName)) - priceResponse := &domainPremiumPriceResponse{} - - if options != nil { - path, err = addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - } - - resp, err := s.client.get(path, priceResponse) - if err != nil { - return nil, err - } - - priceResponse.HttpResponse = resp - return priceResponse, nil -} - -// DomainRegistration represents the result of a domain renewal call. -type DomainRegistration struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - RegistrantID int `json:"registrant_id"` - Period int `json:"period"` - State string `json:"state"` - AutoRenew bool `json:"auto_renew"` - WhoisPrivacy bool `json:"whois_privacy"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainRegistrationResponse represents a response from an API method that results in a domain registration. -type domainRegistrationResponse struct { - Response - Data *DomainRegistration `json:"data"` -} - -// DomainRegisterRequest represents the attributes you can pass to a register API request. -// Some attributes are mandatory. -type DomainRegisterRequest struct { - // The ID of the Contact to use as registrant for the domain - RegistrantID int `json:"registrant_id"` - // Set to true to enable the whois privacy service. An extra cost may apply. - // Default to false. - EnableWhoisPrivacy bool `json:"whois_privacy,omitempty"` - // Set to true to enable the auto-renewal of the domain. - // Default to true. - EnableAutoRenewal bool `json:"auto_renew,omitempty"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// RegisterDomain registers a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#register -func (s *RegistrarService) RegisterDomain(accountID string, domainName string, request *DomainRegisterRequest) (*domainRegistrationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/registrations", accountID, domainName)) - registrationResponse := &domainRegistrationResponse{} - - // TODO: validate mandatory attributes RegistrantID - - resp, err := s.client.post(path, request, registrationResponse) - if err != nil { - return nil, err - } - - registrationResponse.HttpResponse = resp - return registrationResponse, nil -} - -// DomainTransfer represents the result of a domain renewal call. -type DomainTransfer struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - RegistrantID int `json:"registrant_id"` - State string `json:"state"` - AutoRenew bool `json:"auto_renew"` - WhoisPrivacy bool `json:"whois_privacy"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainTransferResponse represents a response from an API method that results in a domain transfer. -type domainTransferResponse struct { - Response - Data *DomainTransfer `json:"data"` -} - -// DomainTransferRequest represents the attributes you can pass to a transfer API request. -// Some attributes are mandatory. -type DomainTransferRequest struct { - // The ID of the Contact to use as registrant for the domain - RegistrantID int `json:"registrant_id"` - // The Auth-Code required to transfer the domain. - // This is provided by the current registrar of the domain. - AuthCode string `json:"auth_code,omitempty"` - // Set to true to enable the whois privacy service. An extra cost may apply. - // Default to false. - EnableWhoisPrivacy bool `json:"whois_privacy,omitempty"` - // Set to true to enable the auto-renewal of the domain. - // Default to true. - EnableAutoRenewal bool `json:"auto_renew,omitempty"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// TransferDomain transfers a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#transfer -func (s *RegistrarService) TransferDomain(accountID string, domainName string, request *DomainTransferRequest) (*domainTransferResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/transfers", accountID, domainName)) - transferResponse := &domainTransferResponse{} - - // TODO: validate mandatory attributes RegistrantID - - resp, err := s.client.post(path, request, transferResponse) - if err != nil { - return nil, err - } - - transferResponse.HttpResponse = resp - return transferResponse, nil -} - -// domainTransferOutResponse represents a response from an API method that results in a domain transfer out. -type domainTransferOutResponse struct { - Response - Data *Domain `json:"data"` -} - -// Transfer out a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#transfer-out -func (s *RegistrarService) TransferDomainOut(accountID string, domainName string) (*domainTransferOutResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/authorize_transfer_out", accountID, domainName)) - transferResponse := &domainTransferOutResponse{} - - resp, err := s.client.post(path, nil, nil) - if err != nil { - return nil, err - } - - transferResponse.HttpResponse = resp - return transferResponse, nil -} - -// DomainRenewal represents the result of a domain renewal call. -type DomainRenewal struct { - ID int `json:"id"` - DomainID int `json:"domain_id"` - Period int `json:"period"` - State string `json:"state"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// domainRenewalResponse represents a response from an API method that returns a domain renewal. -type domainRenewalResponse struct { - Response - Data *DomainRenewal `json:"data"` -} - -// DomainRenewRequest represents the attributes you can pass to a renew API request. -// Some attributes are mandatory. -type DomainRenewRequest struct { - // The number of years - Period int `json:"period"` - // Required as confirmation of the price, only if the domain is premium. - PremiumPrice string `json:"premium_price,omitempty"` -} - -// RenewDomain renews a domain name. -// -// See https://developer.dnsimple.com/v2/registrar/#register -func (s *RegistrarService) RenewDomain(accountID string, domainName string, request *DomainRenewRequest) (*domainRenewalResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/renewals", accountID, domainName)) - renewalResponse := &domainRenewalResponse{} - - resp, err := s.client.post(path, request, renewalResponse) - if err != nil { - return nil, err - } - - renewalResponse.HttpResponse = resp - return renewalResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go deleted file mode 100644 index c98f8d5cd..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_auto_renewal.go +++ /dev/null @@ -1,37 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// EnableDomainAutoRenewal enables auto-renewal for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/auto-renewal/#enable -func (s *RegistrarService) EnableDomainAutoRenewal(accountID string, domainName string) (*domainResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/auto_renewal", accountID, domainName)) - domainResponse := &domainResponse{} - - resp, err := s.client.put(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} - -// DisableDomainAutoRenewal disables auto-renewal for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/auto-renewal/#enable -func (s *RegistrarService) DisableDomainAutoRenewal(accountID string, domainName string) (*domainResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/auto_renewal", accountID, domainName)) - domainResponse := &domainResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - domainResponse.HttpResponse = resp - return domainResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go deleted file mode 100644 index 4ebd3454c..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_delegation.go +++ /dev/null @@ -1,84 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// Delegation represents a list of name servers that correspond to a domain delegation. -type Delegation []string - -// delegationResponse represents a response from an API method that returns a delegation struct. -type delegationResponse struct { - Response - Data *Delegation `json:"data"` -} - -// vanityDelegationResponse represents a response for vanity name server enable and disable operations. -type vanityDelegationResponse struct { - Response - Data []VanityNameServer `json:"data"` -} - -// GetDomainDelegation gets the current delegated name servers for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#get -func (s *RegistrarService) GetDomainDelegation(accountID string, domainName string) (*delegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation", accountID, domainName)) - delegationResponse := &delegationResponse{} - - resp, err := s.client.get(path, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegation updates the delegated name severs for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#get -func (s *RegistrarService) ChangeDomainDelegation(accountID string, domainName string, newDelegation *Delegation) (*delegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation", accountID, domainName)) - delegationResponse := &delegationResponse{} - - resp, err := s.client.put(path, newDelegation, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegationToVanity enables vanity name servers for the given domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#delegateToVanity -func (s *RegistrarService) ChangeDomainDelegationToVanity(accountID string, domainName string, newDelegation *Delegation) (*vanityDelegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation/vanity", accountID, domainName)) - delegationResponse := &vanityDelegationResponse{} - - resp, err := s.client.put(path, newDelegation, delegationResponse) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} - -// ChangeDomainDelegationFromVanity disables vanity name servers for the given domain. -// -// See https://developer.dnsimple.com/v2/registrar/delegation/#dedelegateFromVanity -func (s *RegistrarService) ChangeDomainDelegationFromVanity(accountID string, domainName string) (*vanityDelegationResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/delegation/vanity", accountID, domainName)) - delegationResponse := &vanityDelegationResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - delegationResponse.HttpResponse = resp - return delegationResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go deleted file mode 100644 index edf47b12a..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/registrar_whois_privacy.go +++ /dev/null @@ -1,69 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// WhoisPrivacy represents a whois privacy in DNSimple. -type WhoisPrivacy struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Enabled bool `json:"enabled,omitempty"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// whoisPrivacyResponse represents a response from an API method that returns a WhoisPrivacy struct. -type whoisPrivacyResponse struct { - Response - Data *WhoisPrivacy `json:"data"` -} - -// GetWhoisPrivacy gets the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#get -func (s *RegistrarService) GetWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.get(path, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} - -// EnableWhoisPrivacy enables the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#enable -func (s *RegistrarService) EnableWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.put(path, nil, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} - -// DisablePrivacy disables the whois privacy for the domain. -// -// See https://developer.dnsimple.com/v2/registrar/whois-privacy/#enable -func (s *RegistrarService) DisableWhoisPrivacy(accountID string, domainName string) (*whoisPrivacyResponse, error) { - path := versioned(fmt.Sprintf("/%v/registrar/domains/%v/whois_privacy", accountID, domainName)) - privacyResponse := &whoisPrivacyResponse{} - - resp, err := s.client.delete(path, nil, privacyResponse) - if err != nil { - return nil, err - } - - privacyResponse.HttpResponse = resp - return privacyResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go deleted file mode 100644 index 18afd1185..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services.go +++ /dev/null @@ -1,94 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ServicesService handles communication with the service related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/services/ -type ServicesService struct { - client *Client -} - -// Service represents a Service in DNSimple. -type Service struct { - ID int64 `json:"id,omitempty"` - SID string `json:"sid,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - SetupDescription string `json:"setup_description,omitempty"` - RequiresSetup bool `json:"requires_setup,omitempty"` - DefaultSubdomain string `json:"default_subdomain,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Settings []ServiceSetting `json:"settings,omitempty"` -} - -// ServiceSetting represents a single group of settings for a DNSimple Service. -type ServiceSetting struct { - Name string `json:"name,omitempty"` - Label string `json:"label,omitempty"` - Append string `json:"append,omitempty"` - Description string `json:"description,omitempty"` - Example string `json:"example,omitempty"` - Password bool `json:"password,omitempty"` -} - -func servicePath(serviceIdentifier string) (path string) { - path = "/services" - if serviceIdentifier != "" { - path += fmt.Sprintf("/%v", serviceIdentifier) - } - return -} - -// serviceResponse represents a response from an API method that returns a Service struct. -type serviceResponse struct { - Response - Data *Service `json:"data"` -} - -// servicesResponse represents a response from an API method that returns a collection of Service struct. -type servicesResponse struct { - Response - Data []Service `json:"data"` -} - -// ListServices lists the one-click services available in DNSimple. -// -// See https://developer.dnsimple.com/v2/services/#list -func (s *ServicesService) ListServices(options *ListOptions) (*servicesResponse, error) { - path := versioned(servicePath("")) - servicesResponse := &servicesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, servicesResponse) - if err != nil { - return servicesResponse, err - } - - servicesResponse.HttpResponse = resp - return servicesResponse, nil -} - -// GetService fetches a one-click service. -// -// See https://developer.dnsimple.com/v2/services/#get -func (s *ServicesService) GetService(serviceIdentifier string) (*serviceResponse, error) { - path := versioned(servicePath(serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.get(path, serviceResponse) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go deleted file mode 100644 index 0426dd620..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/services_domains.go +++ /dev/null @@ -1,70 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -func domainServicesPath(accountID string, domainIdentifier string, serviceIdentifier string) string { - if serviceIdentifier != "" { - return fmt.Sprintf("/%v/domains/%v/services/%v", accountID, domainIdentifier, serviceIdentifier) - } - return fmt.Sprintf("/%v/domains/%v/services", accountID, domainIdentifier) -} - -// DomainServiceSettings represents optional settings when applying a DNSimple one-click service to a domain. -type DomainServiceSettings struct { - Settings map[string]string `url:"settings,omitempty"` -} - -// AppliedServices lists the applied one-click services for a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#applied -func (s *ServicesService) AppliedServices(accountID string, domainIdentifier string, options *ListOptions) (*servicesResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, "")) - servicesResponse := &servicesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, servicesResponse) - if err != nil { - return servicesResponse, err - } - - servicesResponse.HttpResponse = resp - return servicesResponse, nil -} - -// ApplyService applies a one-click services to a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#apply -func (s *ServicesService) ApplyService(accountID string, serviceIdentifier string, domainIdentifier string, settings DomainServiceSettings) (*serviceResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.post(path, settings, nil) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} - -// UnapplyService unapplies a one-click services from a domain. -// -// See https://developer.dnsimple.com/v2/services/domains/#unapply -func (s *ServicesService) UnapplyService(accountID string, serviceIdentifier string, domainIdentifier string) (*serviceResponse, error) { - path := versioned(domainServicesPath(accountID, domainIdentifier, serviceIdentifier)) - serviceResponse := &serviceResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - serviceResponse.HttpResponse = resp - return serviceResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go deleted file mode 100644 index 0cd2ec859..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates.go +++ /dev/null @@ -1,129 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TemplatesService handles communication with the template related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/templates/ -type TemplatesService struct { - client *Client -} - -// Template represents a Template in DNSimple. -type Template struct { - ID int64 `json:"id,omitempty"` - SID string `json:"sid,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Name string `json:"name,omitempty"` - Description string `json:"description,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func templatePath(accountID string, templateIdentifier string) (path string) { - path = fmt.Sprintf("/%v/templates", accountID) - if templateIdentifier != "" { - path += fmt.Sprintf("/%v", templateIdentifier) - } - return -} - -// templateResponse represents a response from an API method that returns a Template struct. -type templateResponse struct { - Response - Data *Template `json:"data"` -} - -// templatesResponse represents a response from an API method that returns a collection of Template struct. -type templatesResponse struct { - Response - Data []Template `json:"data"` -} - -// ListTemplates list the templates for an account. -// -// See https://developer.dnsimple.com/v2/templates/#list -func (s *TemplatesService) ListTemplates(accountID string, options *ListOptions) (*templatesResponse, error) { - path := versioned(templatePath(accountID, "")) - templatesResponse := &templatesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, templatesResponse) - if err != nil { - return templatesResponse, err - } - - templatesResponse.HttpResponse = resp - return templatesResponse, nil -} - -// CreateTemplate creates a new template. -// -// See https://developer.dnsimple.com/v2/templates/#create -func (s *TemplatesService) CreateTemplate(accountID string, templateAttributes Template) (*templateResponse, error) { - path := versioned(templatePath(accountID, "")) - templateResponse := &templateResponse{} - - resp, err := s.client.post(path, templateAttributes, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// GetTemplate fetches a template. -// -// See https://developer.dnsimple.com/v2/templates/#get -func (s *TemplatesService) GetTemplate(accountID string, templateIdentifier string) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.get(path, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// UpdateTemplate updates a template. -// -// See https://developer.dnsimple.com/v2/templates/#update -func (s *TemplatesService) UpdateTemplate(accountID string, templateIdentifier string, templateAttributes Template) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.patch(path, templateAttributes, templateResponse) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} - -// DeleteTemplate deletes a template. -// -// See https://developer.dnsimple.com/v2/templates/#delete -func (s *TemplatesService) DeleteTemplate(accountID string, templateIdentifier string) (*templateResponse, error) { - path := versioned(templatePath(accountID, templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go deleted file mode 100644 index 01901bb08..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_domains.go +++ /dev/null @@ -1,21 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ApplyTemplate applies a template to the given domain. -// -// See https://developer.dnsimple.com/v2/templates/domains/#apply -func (s *TemplatesService) ApplyTemplate(accountID string, templateIdentifier string, domainIdentifier string) (*templateResponse, error) { - path := versioned(fmt.Sprintf("%v/templates/%v", domainPath(accountID, domainIdentifier), templateIdentifier)) - templateResponse := &templateResponse{} - - resp, err := s.client.post(path, nil, nil) - if err != nil { - return nil, err - } - - templateResponse.HttpResponse = resp - return templateResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go deleted file mode 100644 index 74f6fd65a..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/templates_records.go +++ /dev/null @@ -1,107 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TemplateRecord represents a DNS record for a template in DNSimple. -type TemplateRecord struct { - ID int64 `json:"id,omitempty"` - TemplateID int64 `json:"template_id,omitempty"` - Name string `json:"name"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Type string `json:"type,omitempty"` - Priority int `json:"priority,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func templateRecordPath(accountID string, templateIdentifier string, templateRecordID int64) string { - if templateRecordID != 0 { - return fmt.Sprintf("%v/records/%v", templatePath(accountID, templateIdentifier), templateRecordID) - } - - return templatePath(accountID, templateIdentifier) + "/records" -} - -// templateRecordResponse represents a response from an API method that returns a TemplateRecord struct. -type templateRecordResponse struct { - Response - Data *TemplateRecord `json:"data"` -} - -// templateRecordsResponse represents a response from an API method that returns a collection of TemplateRecord struct. -type templateRecordsResponse struct { - Response - Data []TemplateRecord `json:"data"` -} - -// ListTemplateRecords list the templates for an account. -// -// See https://developer.dnsimple.com/v2/templates/records/#list -func (s *TemplatesService) ListTemplateRecords(accountID string, templateIdentifier string, options *ListOptions) (*templateRecordsResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, 0)) - templateRecordsResponse := &templateRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, templateRecordsResponse) - if err != nil { - return templateRecordsResponse, err - } - - templateRecordsResponse.HttpResponse = resp - return templateRecordsResponse, nil -} - -// CreateTemplateRecord creates a new template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#create -func (s *TemplatesService) CreateTemplateRecord(accountID string, templateIdentifier string, templateRecordAttributes TemplateRecord) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, 0)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.post(path, templateRecordAttributes, templateRecordResponse) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} - -// GetTemplateRecord fetches a template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#get -func (s *TemplatesService) GetTemplateRecord(accountID string, templateIdentifier string, templateRecordID int64) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, templateRecordID)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.get(path, templateRecordResponse) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} - -// DeleteTemplateRecord deletes a template record. -// -// See https://developer.dnsimple.com/v2/templates/records/#delete -func (s *TemplatesService) DeleteTemplateRecord(accountID string, templateIdentifier string, templateRecordID int64) (*templateRecordResponse, error) { - path := versioned(templateRecordPath(accountID, templateIdentifier, templateRecordID)) - templateRecordResponse := &templateRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - templateRecordResponse.HttpResponse = resp - return templateRecordResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go deleted file mode 100644 index ee0da04fe..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/tlds.go +++ /dev/null @@ -1,117 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// TldsService handles communication with the Tld related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldsService struct { - client *Client -} - -// Tld represents a TLD in DNSimple. -type Tld struct { - Tld string `json:"tld"` - TldType int `json:"tld_type"` - WhoisPrivacy bool `json:"whois_privacy"` - AutoRenewOnly bool `json:"auto_renew_only"` - MinimumRegistration int `json:"minimum_registration"` - RegistrationEnabled bool `json:"registration_enabled"` - RenewalEnabled bool `json:"renewal_enabled"` - TransferEnabled bool `json:"transfer_enabled"` -} - -// TldExtendedAttribute represents an extended attributes supported or required -// by a specific TLD. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldExtendedAttribute struct { - Name string `json:"name"` - Description string `json:"description"` - Required bool `json:"required"` - Options []TldExtendedAttributeOption `json:"options"` -} - -// TldExtendedAttributeOption represents a single option you can assign to an extended attributes. -// -// See https://developer.dnsimple.com/v2/tlds/ -type TldExtendedAttributeOption struct { - Title string `json:"title"` - Value string `json:"value"` - Description string `json:"description"` -} - -// tldResponse represents a response from an API method that returns a Tld struct. -type tldResponse struct { - Response - Data *Tld `json:"data"` -} - -// tldsResponse represents a response from an API method that returns a collection of Tld struct. -type tldsResponse struct { - Response - Data []Tld `json:"data"` -} - -// tldExtendedAttributesResponse represents a response from an API method that returns -// a collection of Tld extended attributes. -type tldExtendedAttributesResponse struct { - Response - Data []TldExtendedAttribute `json:"data"` -} - -// ListTlds lists the supported TLDs. -// -// See https://developer.dnsimple.com/v2/tlds/#list -func (s *TldsService) ListTlds(options *ListOptions) (*tldsResponse, error) { - path := versioned("/tlds") - tldsResponse := &tldsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, tldsResponse) - if err != nil { - return tldsResponse, err - } - - tldsResponse.HttpResponse = resp - return tldsResponse, nil -} - -// GetTld fetches a TLD. -// -// See https://developer.dnsimple.com/v2/tlds/#get -func (s *TldsService) GetTld(tld string) (*tldResponse, error) { - path := versioned(fmt.Sprintf("/tlds/%s", tld)) - tldResponse := &tldResponse{} - - resp, err := s.client.get(path, tldResponse) - if err != nil { - return nil, err - } - - tldResponse.HttpResponse = resp - return tldResponse, nil -} - -// GetTld fetches the extended attributes of a TLD. -// -// See https://developer.dnsimple.com/v2/tlds/#get -func (s *TldsService) GetTldExtendedAttributes(tld string) (*tldExtendedAttributesResponse, error) { - path := versioned(fmt.Sprintf("/tlds/%s/extended_attributes", tld)) - tldResponse := &tldExtendedAttributesResponse{} - - resp, err := s.client.get(path, tldResponse) - if err != nil { - return nil, err - } - - tldResponse.HttpResponse = resp - return tldResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go deleted file mode 100644 index 9c33f4083..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/users.go +++ /dev/null @@ -1,7 +0,0 @@ -package dnsimple - -// User represents a DNSimple user. -type User struct { - ID int64 `json:"id,omitempty"` - Email string `json:"email,omitempty"` -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go deleted file mode 100644 index cd1314a4c..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/vanity_name_server.go +++ /dev/null @@ -1,65 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// VanityNameServersService handles communication with Vanity Name Servers -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/vanity/ -type VanityNameServersService struct { - client *Client -} - -// VanityNameServer represents data for a single vanity name server -type VanityNameServer struct { - ID int64 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - IPv4 string `json:"ipv4,omitempty"` - IPv6 string `json:"ipv6,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func vanityNameServerPath(accountID string, domainIdentifier string) string { - return fmt.Sprintf("/%v/vanity/%v", accountID, domainIdentifier) -} - -// vanityNameServerResponse represents a response for vanity name server enable and disable operations. -type vanityNameServerResponse struct { - Response - Data []VanityNameServer `json:"data"` -} - -// EnableVanityNameServers Vanity Name Servers for the given domain -// -// See https://developer.dnsimple.com/v2/vanity/#enable -func (s *VanityNameServersService) EnableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) { - path := versioned(vanityNameServerPath(accountID, domainIdentifier)) - vanityNameServerResponse := &vanityNameServerResponse{} - - resp, err := s.client.put(path, nil, vanityNameServerResponse) - if err != nil { - return nil, err - } - - vanityNameServerResponse.HttpResponse = resp - return vanityNameServerResponse, nil -} - -// DisableVanityNameServers Vanity Name Servers for the given domain -// -// See https://developer.dnsimple.com/v2/vanity/#disable -func (s *VanityNameServersService) DisableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) { - path := versioned(vanityNameServerPath(accountID, domainIdentifier)) - vanityNameServerResponse := &vanityNameServerResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - vanityNameServerResponse.HttpResponse = resp - return vanityNameServerResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go deleted file mode 100644 index 14263338d..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/webhooks.go +++ /dev/null @@ -1,103 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// WebhooksService handles communication with the webhook related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/webhooks -type WebhooksService struct { - client *Client -} - -// Webhook represents a DNSimple webhook. -type Webhook struct { - ID int64 `json:"id,omitempty"` - URL string `json:"url,omitempty"` -} - -func webhookPath(accountID string, webhookID int64) (path string) { - path = fmt.Sprintf("/%v/webhooks", accountID) - if webhookID != 0 { - path = fmt.Sprintf("%v/%v", path, webhookID) - } - return -} - -// webhookResponse represents a response from an API method that returns a Webhook struct. -type webhookResponse struct { - Response - Data *Webhook `json:"data"` -} - -// webhookResponse represents a response from an API method that returns a collection of Webhook struct. -type webhooksResponse struct { - Response - Data []Webhook `json:"data"` -} - -// ListWebhooks lists the webhooks for an account. -// -// See https://developer.dnsimple.com/v2/webhooks#list -func (s *WebhooksService) ListWebhooks(accountID string, _ *ListOptions) (*webhooksResponse, error) { - path := versioned(webhookPath(accountID, 0)) - webhooksResponse := &webhooksResponse{} - - resp, err := s.client.get(path, webhooksResponse) - if err != nil { - return webhooksResponse, err - } - - webhooksResponse.HttpResponse = resp - return webhooksResponse, nil -} - -// CreateWebhook creates a new webhook. -// -// See https://developer.dnsimple.com/v2/webhooks#create -func (s *WebhooksService) CreateWebhook(accountID string, webhookAttributes Webhook) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, 0)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.post(path, webhookAttributes, webhookResponse) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} - -// GetWebhook fetches a webhook. -// -// See https://developer.dnsimple.com/v2/webhooks#get -func (s *WebhooksService) GetWebhook(accountID string, webhookID int64) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, webhookID)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.get(path, webhookResponse) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} - -// DeleteWebhook PERMANENTLY deletes a webhook from the account. -// -// See https://developer.dnsimple.com/v2/webhooks#delete -func (s *WebhooksService) DeleteWebhook(accountID string, webhookID int64) (*webhookResponse, error) { - path := versioned(webhookPath(accountID, webhookID)) - webhookResponse := &webhookResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - webhookResponse.HttpResponse = resp - return webhookResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go deleted file mode 100644 index f92d75790..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zone_distributions.go +++ /dev/null @@ -1,46 +0,0 @@ -package dnsimple - -import "fmt" - -// ZoneDistribution is the result of the zone distribution check. -type ZoneDistribution struct { - Distributed bool `json:"distributed"` -} - -// zoneDistributionResponse represents a response from an API method that returns a ZoneDistribution struct. -type zoneDistributionResponse struct { - Response - Data *ZoneDistribution `json:"data"` -} - -// CheckZoneDistribution checks if a zone is fully distributed across DNSimple nodes. -// -// See https://developer.dnsimple.com/v2/zones/#checkZoneDistribution -func (s *ZonesService) CheckZoneDistribution(accountID string, zoneName string) (*zoneDistributionResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/distribution", accountID, zoneName)) - zoneDistributionResponse := &zoneDistributionResponse{} - - resp, err := s.client.get(path, zoneDistributionResponse) - if err != nil { - return nil, err - } - - zoneDistributionResponse.HttpResponse = resp - return zoneDistributionResponse, nil -} - -// CheckZoneRecordDistribution checks if a zone is fully distributed across DNSimple nodes. -// -// See https://developer.dnsimple.com/v2/zones/#checkZoneRecordDistribution -func (s *ZonesService) CheckZoneRecordDistribution(accountID string, zoneName string, recordID int64) (*zoneDistributionResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/records/%v/distribution", accountID, zoneName, recordID)) - zoneDistributionResponse := &zoneDistributionResponse{} - - resp, err := s.client.get(path, zoneDistributionResponse) - if err != nil { - return nil, err - } - - zoneDistributionResponse.HttpResponse = resp - return zoneDistributionResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go deleted file mode 100644 index f521fcfac..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones.go +++ /dev/null @@ -1,108 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ZonesService handles communication with the zone related -// methods of the DNSimple API. -// -// See https://developer.dnsimple.com/v2/zones/ -type ZonesService struct { - client *Client -} - -// Zone represents a Zone in DNSimple. -type Zone struct { - ID int64 `json:"id,omitempty"` - AccountID int64 `json:"account_id,omitempty"` - Name string `json:"name,omitempty"` - Reverse bool `json:"reverse,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -// ZoneFile represents a Zone File in DNSimple. -type ZoneFile struct { - Zone string `json:"zone,omitempty"` -} - -// zoneResponse represents a response from an API method that returns a Zone struct. -type zoneResponse struct { - Response - Data *Zone `json:"data"` -} - -// zonesResponse represents a response from an API method that returns a collection of Zone struct. -type zonesResponse struct { - Response - Data []Zone `json:"data"` -} - -// zoneFileResponse represents a response from an API method that returns a ZoneFile struct. -type zoneFileResponse struct { - Response - Data *ZoneFile `json:"data"` -} - -// ZoneListOptions specifies the optional parameters you can provide -// to customize the ZonesService.ListZones method. -type ZoneListOptions struct { - // Select domains where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - ListOptions -} - -// ListZones the zones for an account. -// -// See https://developer.dnsimple.com/v2/zones/#list -func (s *ZonesService) ListZones(accountID string, options *ZoneListOptions) (*zonesResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones", accountID)) - zonesResponse := &zonesResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, zonesResponse) - if err != nil { - return zonesResponse, err - } - - zonesResponse.HttpResponse = resp - return zonesResponse, nil -} - -// GetZone fetches a zone. -// -// See https://developer.dnsimple.com/v2/zones/#get -func (s *ZonesService) GetZone(accountID string, zoneName string) (*zoneResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v", accountID, zoneName)) - zoneResponse := &zoneResponse{} - - resp, err := s.client.get(path, zoneResponse) - if err != nil { - return nil, err - } - - zoneResponse.HttpResponse = resp - return zoneResponse, nil -} - -// GetZoneFile fetches a zone file. -// -// See https://developer.dnsimple.com/v2/zones/#get-file -func (s *ZonesService) GetZoneFile(accountID string, zoneName string) (*zoneFileResponse, error) { - path := versioned(fmt.Sprintf("/%v/zones/%v/file", accountID, zoneName)) - zoneFileResponse := &zoneFileResponse{} - - resp, err := s.client.get(path, zoneFileResponse) - if err != nil { - return nil, err - } - - zoneFileResponse.HttpResponse = resp - return zoneFileResponse, nil -} diff --git a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go b/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go deleted file mode 100644 index fbb432d5a..000000000 --- a/vendor/github.com/dnsimple/dnsimple-go/dnsimple/zones_records.go +++ /dev/null @@ -1,142 +0,0 @@ -package dnsimple - -import ( - "fmt" -) - -// ZoneRecord represents a DNS record in DNSimple. -type ZoneRecord struct { - ID int64 `json:"id,omitempty"` - ZoneID string `json:"zone_id,omitempty"` - ParentID int64 `json:"parent_id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Priority int `json:"priority,omitempty"` - SystemRecord bool `json:"system_record,omitempty"` - Regions []string `json:"regions,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` -} - -func zoneRecordPath(accountID string, zoneName string, recordID int64) (path string) { - path = fmt.Sprintf("/%v/zones/%v/records", accountID, zoneName) - if recordID != 0 { - path += fmt.Sprintf("/%v", recordID) - } - return -} - -// zoneRecordResponse represents a response from an API method that returns a ZoneRecord struct. -type zoneRecordResponse struct { - Response - Data *ZoneRecord `json:"data"` -} - -// zoneRecordsResponse represents a response from an API method that returns a collection of ZoneRecord struct. -type zoneRecordsResponse struct { - Response - Data []ZoneRecord `json:"data"` -} - -// ZoneRecordListOptions specifies the optional parameters you can provide -// to customize the ZonesService.ListZoneRecords method. -type ZoneRecordListOptions struct { - // Select records where the name matches given string. - Name string `url:"name,omitempty"` - - // Select records where the name contains given string. - NameLike string `url:"name_like,omitempty"` - - // Select records of given type. - // Eg. TXT, A, NS. - Type string `url:"type,omitempty"` - - ListOptions -} - -// ListRecords lists the zone records for a zone. -// -// See https://developer.dnsimple.com/v2/zones/records/#listZoneRecords -func (s *ZonesService) ListRecords(accountID string, zoneName string, options *ZoneRecordListOptions) (*zoneRecordsResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, 0)) - recordsResponse := &zoneRecordsResponse{} - - path, err := addURLQueryOptions(path, options) - if err != nil { - return nil, err - } - - resp, err := s.client.get(path, recordsResponse) - if err != nil { - return nil, err - } - - recordsResponse.HttpResponse = resp - return recordsResponse, nil -} - -// CreateRecord creates a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#createZoneRecord -func (s *ZonesService) CreateRecord(accountID string, zoneName string, recordAttributes ZoneRecord) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, 0)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.post(path, recordAttributes, recordResponse) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// GetRecord fetches a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#getZoneRecord -func (s *ZonesService) GetRecord(accountID string, zoneName string, recordID int64) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.get(path, recordResponse) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// UpdateRecord updates a zone record. -// -// See https://developer.dnsimple.com/v2/zones/records/#updateZoneRecord -func (s *ZonesService) UpdateRecord(accountID string, zoneName string, recordID int64, recordAttributes ZoneRecord) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - resp, err := s.client.patch(path, recordAttributes, recordResponse) - - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} - -// DeleteRecord PERMANENTLY deletes a zone record from the zone. -// -// See https://developer.dnsimple.com/v2/zones/records/#deleteZoneRecord -func (s *ZonesService) DeleteRecord(accountID string, zoneName string, recordID int64) (*zoneRecordResponse, error) { - path := versioned(zoneRecordPath(accountID, zoneName, recordID)) - recordResponse := &zoneRecordResponse{} - - resp, err := s.client.delete(path, nil, nil) - if err != nil { - return nil, err - } - - recordResponse.HttpResponse = resp - return recordResponse, nil -} 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 0c74e15b0..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/kr/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context.go b/vendor/github.com/docker/cli/cli/command/image/build/context.go deleted file mode 100644 index e9af9bd35..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/build/context.go +++ /dev/null @@ -1,440 +0,0 @@ -package build - -import ( - "archive/tar" - "bufio" - "bytes" - "fmt" - "io" - "io/ioutil" - "net/http" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "time" - - "github.com/docker/docker/builder/remotecontext/git" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/fileutils" - "github.com/docker/docker/pkg/ioutils" - "github.com/docker/docker/pkg/pools" - "github.com/docker/docker/pkg/progress" - "github.com/docker/docker/pkg/streamformatter" - "github.com/docker/docker/pkg/stringid" - "github.com/pkg/errors" -) - -const ( - // DefaultDockerfileName is the Default filename with Docker commands, read by docker build - DefaultDockerfileName string = "Dockerfile" - // archiveHeaderSize is the number of bytes in an archive header - archiveHeaderSize = 512 -) - -// ValidateContextDirectory checks if all the contents of the directory -// can be read and returns an error if some files can't be read -// symlinks which point to non-existing files don't trigger an error -func ValidateContextDirectory(srcPath string, excludes []string) error { - contextRoot, err := getContextRoot(srcPath) - if err != nil { - return err - } - - pm, err := fileutils.NewPatternMatcher(excludes) - if err != nil { - return err - } - - return filepath.Walk(contextRoot, func(filePath string, f os.FileInfo, err error) error { - if err != nil { - if os.IsPermission(err) { - return errors.Errorf("can't stat '%s'", filePath) - } - if os.IsNotExist(err) { - return errors.Errorf("file ('%s') not found or excluded by .dockerignore", filePath) - } - return err - } - - // skip this directory/file if it's not in the path, it won't get added to the context - if relFilePath, err := filepath.Rel(contextRoot, filePath); err != nil { - return err - } else if skip, err := filepathMatches(pm, relFilePath); err != nil { - return err - } else if skip { - if f.IsDir() { - return filepath.SkipDir - } - return nil - } - - // skip checking if symlinks point to non-existing files, such symlinks can be useful - // also skip named pipes, because they hanging on open - if f.Mode()&(os.ModeSymlink|os.ModeNamedPipe) != 0 { - return nil - } - - if !f.IsDir() { - currentFile, err := os.Open(filePath) - if err != nil && os.IsPermission(err) { - return errors.Errorf("no permission to read from '%s'", filePath) - } - currentFile.Close() - } - return nil - }) -} - -func filepathMatches(matcher *fileutils.PatternMatcher, file string) (bool, error) { - file = filepath.Clean(file) - if file == "." { - // Don't let them exclude everything, kind of silly. - return false, nil - } - return matcher.Matches(file) -} - -// DetectArchiveReader detects whether the input stream is an archive or a -// Dockerfile and returns a buffered version of input, safe to consume in lieu -// of input. If an archive is detected, isArchive is set to true, and to false -// otherwise, in which case it is safe to assume input represents the contents -// of a Dockerfile. -func DetectArchiveReader(input io.ReadCloser) (rc io.ReadCloser, isArchive bool, err error) { - buf := bufio.NewReader(input) - - magic, err := buf.Peek(archiveHeaderSize * 2) - if err != nil && err != io.EOF { - return nil, false, errors.Errorf("failed to peek context header from STDIN: %v", err) - } - - return ioutils.NewReadCloserWrapper(buf, func() error { return input.Close() }), IsArchive(magic), nil -} - -// WriteTempDockerfile writes a Dockerfile stream to a temporary file with a -// name specified by DefaultDockerfileName and returns the path to the -// temporary directory containing the Dockerfile. -func WriteTempDockerfile(rc io.ReadCloser) (dockerfileDir string, err error) { - // err is a named return value, due to the defer call below. - dockerfileDir, err = ioutil.TempDir("", "docker-build-tempdockerfile-") - if err != nil { - return "", errors.Errorf("unable to create temporary context directory: %v", err) - } - defer func() { - if err != nil { - os.RemoveAll(dockerfileDir) - } - }() - - f, err := os.Create(filepath.Join(dockerfileDir, DefaultDockerfileName)) - if err != nil { - return "", err - } - defer f.Close() - if _, err := io.Copy(f, rc); err != nil { - return "", err - } - return dockerfileDir, rc.Close() -} - -// GetContextFromReader will read the contents of the given reader as either a -// Dockerfile or tar archive. Returns a tar archive used as a context and a -// path to the Dockerfile inside the tar. -func GetContextFromReader(rc io.ReadCloser, dockerfileName string) (out io.ReadCloser, relDockerfile string, err error) { - rc, isArchive, err := DetectArchiveReader(rc) - if err != nil { - return nil, "", err - } - - if isArchive { - return rc, dockerfileName, nil - } - - // Input should be read as a Dockerfile. - - if dockerfileName == "-" { - return nil, "", errors.New("build context is not an archive") - } - - dockerfileDir, err := WriteTempDockerfile(rc) - if err != nil { - return nil, "", err - } - - tar, err := archive.Tar(dockerfileDir, archive.Uncompressed) - if err != nil { - return nil, "", err - } - - return ioutils.NewReadCloserWrapper(tar, func() error { - err := tar.Close() - os.RemoveAll(dockerfileDir) - return err - }), DefaultDockerfileName, nil -} - -// IsArchive checks for the magic bytes of a tar or any supported compression -// algorithm. -func IsArchive(header []byte) bool { - compression := archive.DetectCompression(header) - if compression != archive.Uncompressed { - return true - } - r := tar.NewReader(bytes.NewBuffer(header)) - _, err := r.Next() - return err == nil -} - -// GetContextFromGitURL uses a Git URL as context for a `docker build`. The -// git repo is cloned into a temporary directory used as the context directory. -// Returns the absolute path to the temporary context directory, the relative -// path of the dockerfile in that context directory, and a non-nil error on -// success. -func GetContextFromGitURL(gitURL, dockerfileName string) (string, string, error) { - if _, err := exec.LookPath("git"); err != nil { - return "", "", errors.Wrapf(err, "unable to find 'git'") - } - absContextDir, err := git.Clone(gitURL) - if err != nil { - return "", "", errors.Wrapf(err, "unable to 'git clone' to temporary context directory") - } - - absContextDir, err = ResolveAndValidateContextPath(absContextDir) - if err != nil { - return "", "", err - } - relDockerfile, err := getDockerfileRelPath(absContextDir, dockerfileName) - if err == nil && strings.HasPrefix(relDockerfile, ".."+string(filepath.Separator)) { - return "", "", errors.Errorf("the Dockerfile (%s) must be within the build context", dockerfileName) - } - - return absContextDir, relDockerfile, err -} - -// GetContextFromURL uses a remote URL as context for a `docker build`. The -// remote resource is downloaded as either a Dockerfile or a tar archive. -// Returns the tar archive used for the context and a path of the -// dockerfile inside the tar. -func GetContextFromURL(out io.Writer, remoteURL, dockerfileName string) (io.ReadCloser, string, error) { - response, err := getWithStatusError(remoteURL) - if err != nil { - return nil, "", errors.Errorf("unable to download remote context %s: %v", remoteURL, err) - } - progressOutput := streamformatter.NewProgressOutput(out) - - // Pass the response body through a progress reader. - progReader := progress.NewProgressReader(response.Body, progressOutput, response.ContentLength, "", fmt.Sprintf("Downloading build context from remote url: %s", remoteURL)) - - return GetContextFromReader(ioutils.NewReadCloserWrapper(progReader, func() error { return response.Body.Close() }), dockerfileName) -} - -// getWithStatusError does an http.Get() and returns an error if the -// status code is 4xx or 5xx. -func getWithStatusError(url string) (resp *http.Response, err error) { - if resp, err = http.Get(url); err != nil { - return nil, err - } - if resp.StatusCode < 400 { - return resp, nil - } - msg := fmt.Sprintf("failed to GET %s with status %s", url, resp.Status) - body, err := ioutil.ReadAll(resp.Body) - resp.Body.Close() - if err != nil { - return nil, errors.Wrapf(err, msg+": error reading body") - } - return nil, errors.Errorf(msg+": %s", bytes.TrimSpace(body)) -} - -// GetContextFromLocalDir uses the given local directory as context for a -// `docker build`. Returns the absolute path to the local context directory, -// the relative path of the dockerfile in that context directory, and a non-nil -// error on success. -func GetContextFromLocalDir(localDir, dockerfileName string) (string, string, error) { - localDir, err := ResolveAndValidateContextPath(localDir) - if err != nil { - return "", "", err - } - - // When using a local context directory, and the Dockerfile is specified - // with the `-f/--file` option then it is considered relative to the - // current directory and not the context directory. - if dockerfileName != "" && dockerfileName != "-" { - if dockerfileName, err = filepath.Abs(dockerfileName); err != nil { - return "", "", errors.Errorf("unable to get absolute path to Dockerfile: %v", err) - } - } - - relDockerfile, err := getDockerfileRelPath(localDir, dockerfileName) - return localDir, relDockerfile, err -} - -// ResolveAndValidateContextPath uses the given context directory for a `docker build` -// and returns the absolute path to the context directory. -func ResolveAndValidateContextPath(givenContextDir string) (string, error) { - absContextDir, err := filepath.Abs(givenContextDir) - if err != nil { - return "", errors.Errorf("unable to get absolute context directory of given context directory %q: %v", givenContextDir, err) - } - - // The context dir might be a symbolic link, so follow it to the actual - // target directory. - // - // FIXME. We use isUNC (always false on non-Windows platforms) to workaround - // an issue in golang. On Windows, EvalSymLinks does not work on UNC file - // paths (those starting with \\). This hack means that when using links - // on UNC paths, they will not be followed. - if !isUNC(absContextDir) { - absContextDir, err = filepath.EvalSymlinks(absContextDir) - if err != nil { - return "", errors.Errorf("unable to evaluate symlinks in context path: %v", err) - } - } - - stat, err := os.Lstat(absContextDir) - if err != nil { - return "", errors.Errorf("unable to stat context directory %q: %v", absContextDir, err) - } - - if !stat.IsDir() { - return "", errors.Errorf("context must be a directory: %s", absContextDir) - } - return absContextDir, err -} - -// getDockerfileRelPath returns the dockerfile path relative to the context -// directory -func getDockerfileRelPath(absContextDir, givenDockerfile string) (string, error) { - var err error - - if givenDockerfile == "-" { - return givenDockerfile, nil - } - - absDockerfile := givenDockerfile - if absDockerfile == "" { - // No -f/--file was specified so use the default relative to the - // context directory. - absDockerfile = filepath.Join(absContextDir, DefaultDockerfileName) - - // Just to be nice ;-) look for 'dockerfile' too but only - // use it if we found it, otherwise ignore this check - if _, err = os.Lstat(absDockerfile); os.IsNotExist(err) { - altPath := filepath.Join(absContextDir, strings.ToLower(DefaultDockerfileName)) - if _, err = os.Lstat(altPath); err == nil { - absDockerfile = altPath - } - } - } - - // If not already an absolute path, the Dockerfile path should be joined to - // the base directory. - if !filepath.IsAbs(absDockerfile) { - absDockerfile = filepath.Join(absContextDir, absDockerfile) - } - - // Evaluate symlinks in the path to the Dockerfile too. - // - // FIXME. We use isUNC (always false on non-Windows platforms) to workaround - // an issue in golang. On Windows, EvalSymLinks does not work on UNC file - // paths (those starting with \\). This hack means that when using links - // on UNC paths, they will not be followed. - if !isUNC(absDockerfile) { - absDockerfile, err = filepath.EvalSymlinks(absDockerfile) - if err != nil { - return "", errors.Errorf("unable to evaluate symlinks in Dockerfile path: %v", err) - - } - } - - if _, err := os.Lstat(absDockerfile); err != nil { - if os.IsNotExist(err) { - return "", errors.Errorf("Cannot locate Dockerfile: %q", absDockerfile) - } - return "", errors.Errorf("unable to stat Dockerfile: %v", err) - } - - relDockerfile, err := filepath.Rel(absContextDir, absDockerfile) - if err != nil { - return "", errors.Errorf("unable to get relative Dockerfile path: %v", err) - } - - return relDockerfile, nil -} - -// isUNC returns true if the path is UNC (one starting \\). It always returns -// false on Linux. -func isUNC(path string) bool { - return runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`) -} - -// AddDockerfileToBuildContext from a ReadCloser, returns a new archive and -// the relative path to the dockerfile in the context. -func AddDockerfileToBuildContext(dockerfileCtx io.ReadCloser, buildCtx io.ReadCloser) (io.ReadCloser, string, error) { - file, err := ioutil.ReadAll(dockerfileCtx) - dockerfileCtx.Close() - if err != nil { - return nil, "", err - } - now := time.Now() - hdrTmpl := &tar.Header{ - Mode: 0600, - Uid: 0, - Gid: 0, - ModTime: now, - Typeflag: tar.TypeReg, - AccessTime: now, - ChangeTime: now, - } - randomName := ".dockerfile." + stringid.GenerateRandomID()[:20] - - buildCtx = archive.ReplaceFileTarWrapper(buildCtx, map[string]archive.TarModifierFunc{ - // Add the dockerfile with a random filename - randomName: func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) { - return hdrTmpl, file, nil - }, - // Update .dockerignore to include the random filename - ".dockerignore": func(_ string, h *tar.Header, content io.Reader) (*tar.Header, []byte, error) { - if h == nil { - h = hdrTmpl - } - - b := &bytes.Buffer{} - if content != nil { - if _, err := b.ReadFrom(content); err != nil { - return nil, nil, err - } - } else { - b.WriteString(".dockerignore") - } - b.WriteString("\n" + randomName + "\n") - return h, b.Bytes(), nil - }, - }) - return buildCtx, randomName, nil -} - -// Compress the build context for sending to the API -func Compress(buildCtx io.ReadCloser) (io.ReadCloser, error) { - pipeReader, pipeWriter := io.Pipe() - - go func() { - compressWriter, err := archive.CompressStream(pipeWriter, archive.Gzip) - if err != nil { - pipeWriter.CloseWithError(err) - } - defer buildCtx.Close() - - if _, err := pools.Copy(compressWriter, buildCtx); err != nil { - pipeWriter.CloseWithError( - errors.Wrap(err, "failed to compress context")) - compressWriter.Close() - return - } - compressWriter.Close() - pipeWriter.Close() - }() - - return pipeReader, nil -} diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go b/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go deleted file mode 100644 index cb2634f07..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/build/context_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +build !windows - -package build - -import ( - "path/filepath" -) - -func getContextRoot(srcPath string) (string, error) { - return filepath.Join(srcPath, "."), nil -} diff --git a/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go b/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go deleted file mode 100644 index c577cfa7b..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/build/context_windows.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build windows - -package build - -import ( - "path/filepath" - - "github.com/docker/docker/pkg/longpath" -) - -func getContextRoot(srcPath string) (string, error) { - cr, err := filepath.Abs(srcPath) - if err != nil { - return "", err - } - return longpath.AddPrefix(cr), nil -} diff --git a/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go b/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go deleted file mode 100644 index 497c3f24f..000000000 --- a/vendor/github.com/docker/cli/cli/command/image/build/dockerignore.go +++ /dev/null @@ -1,39 +0,0 @@ -package build - -import ( - "os" - "path/filepath" - - "github.com/docker/docker/builder/dockerignore" - "github.com/docker/docker/pkg/fileutils" -) - -// ReadDockerignore reads the .dockerignore file in the context directory and -// returns the list of paths to exclude -func ReadDockerignore(contextDir string) ([]string, error) { - var excludes []string - - f, err := os.Open(filepath.Join(contextDir, ".dockerignore")) - switch { - case os.IsNotExist(err): - return excludes, nil - case err != nil: - return nil, err - } - defer f.Close() - - return dockerignore.ReadAll(f) -} - -// TrimBuildFilesFromExcludes removes the named Dockerfile and .dockerignore from -// the list of excluded files. The daemon will remove them from the final context -// but they must be in available in the context when passed to the API. -func TrimBuildFilesFromExcludes(excludes []string, dockerfile string, dockerfileFromStdin bool) []string { - if keep, _ := fileutils.Matches(".dockerignore", excludes); keep { - excludes = append(excludes, "!.dockerignore") - } - if keep, _ := fileutils.Matches(dockerfile, excludes); keep && !dockerfileFromStdin { - excludes = append(excludes, "!"+dockerfile) - } - return excludes -} 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 f5e33f2b3..000000000 --- a/vendor/github.com/docker/cli/cli/config/config.go +++ /dev/null @@ -1,136 +0,0 @@ -package config - -import ( - "fmt" - "io" - "os" - "path/filepath" - "strings" - - "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" - contextsDir = "contexts" -) - -var ( - configDir = os.Getenv("DOCKER_CONFIG") -) - -func init() { - if configDir == "" { - configDir = filepath.Join(homedir.Get(), configFileDir) - } -} - -// Dir returns the directory the configuration file is stored in -func Dir() string { - 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 -} - -// LegacyLoadFromReader is a convenience function that creates a ConfigFile object from -// a non-nested reader -func LegacyLoadFromReader(configData io.Reader) (*configfile.ConfigFile, error) { - configFile := configfile.ConfigFile{ - AuthConfigs: make(map[string]types.AuthConfig), - } - err := configFile.LegacyLoadFromReader(configData) - return &configFile, err -} - -// 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) { - if configDir == "" { - configDir = Dir() - } - - filename := filepath.Join(configDir, ConfigFileName) - configFile := configfile.New(filename) - - // Try happy path first - latest config file - if _, err := os.Stat(filename); err == nil { - file, err := os.Open(filename) - if err != nil { - return configFile, errors.Wrap(err, filename) - } - defer file.Close() - err = configFile.LoadFromReader(file) - if err != nil { - err = errors.Wrap(err, filename) - } - return configFile, 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, errors.Wrap(err, filename) - } - - // Can't find latest config file so check for the old one - confFile := filepath.Join(homedir.Get(), oldConfigfile) - if _, err := os.Stat(confFile); err != nil { - return configFile, nil //missing file is not an error - } - file, err := os.Open(confFile) - if err != nil { - return configFile, errors.Wrap(err, filename) - } - defer file.Close() - err = configFile.LegacyLoadFromReader(file) - if err != nil { - return configFile, errors.Wrap(err, filename) - } - return configFile, 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, err := Load(Dir()) - if err != nil { - fmt.Fprintf(stderr, "WARNING: Error loading config file: %v\n", err) - } - 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 67ae655b0..000000000 --- a/vendor/github.com/docker/cli/cli/config/configfile/file.go +++ /dev/null @@ -1,385 +0,0 @@ -package configfile - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/config/credentials" - "github.com/docker/cli/cli/config/types" - "github.com/pkg/errors" -) - -const ( - // This constant is only used for really old config files when the - // URL wasn't saved as part of the config file and it was just - // assumed to be this value. - defaultIndexServer = "https://index.docker.io/v1/" -) - -// 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"` - StackOrchestrator string `json:"stackOrchestrator,omitempty"` - Kubernetes *KubernetesConfig `json:"kubernetes,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"` -} - -// KubernetesConfig contains Kubernetes orchestrator settings -type KubernetesConfig struct { - AllNamespaces string `json:"allNamespaces,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), - } -} - -// LegacyLoadFromReader reads the non-nested configuration data given and sets up the -// auth config information with given directory and populates the receiver object -func (configFile *ConfigFile) LegacyLoadFromReader(configData io.Reader) error { - b, err := ioutil.ReadAll(configData) - if err != nil { - return err - } - - if err := json.Unmarshal(b, &configFile.AuthConfigs); err != nil { - arr := strings.Split(string(b), "\n") - if len(arr) < 2 { - return errors.Errorf("The Auth config file is empty") - } - authConfig := types.AuthConfig{} - origAuth := strings.Split(arr[0], " = ") - if len(origAuth) != 2 { - return errors.Errorf("Invalid Auth config file") - } - authConfig.Username, authConfig.Password, err = decodeAuth(origAuth[1]) - if err != nil { - return err - } - authConfig.ServerAddress = defaultIndexServer - configFile.AuthConfigs[defaultIndexServer] = authConfig - } else { - for k, authConfig := range configFile.AuthConfigs { - authConfig.Username, authConfig.Password, err = decodeAuth(authConfig.Auth) - if err != nil { - return err - } - authConfig.Auth = "" - authConfig.ServerAddress = k - configFile.AuthConfigs[k] = authConfig - } - } - return nil -} - -// 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 { - return err - } - var err error - for addr, ac := range configFile.AuthConfigs { - ac.Username, ac.Password, err = decodeAuth(ac.Auth) - if err != nil { - return err - } - ac.Auth = "" - ac.ServerAddress = addr - configFile.AuthConfigs[addr] = ac - } - return checkKubernetesConfiguration(configFile.Kubernetes) -} - -// 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 { - 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 }() - - 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() error { - if configFile.Filename == "" { - return errors.Errorf("Can't save config with empty filename") - } - - dir := filepath.Dir(configFile.Filename) - if err := os.MkdirAll(dir, 0700); err != nil { - return err - } - temp, err := ioutil.TempFile(dir, filepath.Base(configFile.Filename)) - if err != nil { - return err - } - err = configFile.SaveToWriter(temp) - temp.Close() - if err != nil { - os.Remove(temp.Name()) - return err - } - return os.Rename(temp.Name(), configFile.Filename) -} - -// 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, - } - 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") - } - arr := strings.SplitN(string(decoded), ":", 2) - if len(arr) != 2 { - return "", "", errors.Errorf("Invalid auth configuration file") - } - password := strings.Trim(arr[1], "\x00") - return arr[0], password, 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 { - return nil, err - } - 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) - } -} - -func checkKubernetesConfiguration(kubeConfig *KubernetesConfig) error { - if kubeConfig == nil { - return nil - } - switch kubeConfig.AllNamespaces { - case "": - case "enabled": - case "disabled": - default: - return fmt.Errorf("invalid 'kubernetes.allNamespaces' value, should be 'enabled' or 'disabled': %s", kubeConfig.AllNamespaces) - } - return nil -} 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 7a760f1a9..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store.go +++ /dev/null @@ -1,21 +0,0 @@ -package credentials - -import ( - "os/exec" -) - -// 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 3028168ac..000000000 --- a/vendor/github.com/docker/cli/cli/config/credentials/default_store_unsupported.go +++ /dev/null @@ -1,7 +0,0 @@ -// +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 e509820b7..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 { - c.file.GetAuthConfigs()[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://") - } - - nameParts := strings.SplitN(stripped, "/", 2) - - return nameParts[0] -} 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 afe542cc3..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-" - 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/opts/config.go b/vendor/github.com/docker/cli/opts/config.go deleted file mode 100644 index 82fd2bce4..000000000 --- a/vendor/github.com/docker/cli/opts/config.go +++ /dev/null @@ -1,98 +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: 0444, - }, - } - - // support a simple syntax of --config foo - if len(fields) == 1 { - options.File.Name = fields[0] - options.ConfigName = fields[0] - o.values = append(o.values, options) - return nil - } - - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - key := strings.ToLower(parts[0]) - - if len(parts) != 2 { - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - - value := parts[1] - switch key { - case "source", "src": - options.ConfigName = value - case "target": - options.File.Name = value - case "uid": - options.File.UID = value - case "gid": - options.File.GID = value - case "mode": - m, err := strconv.ParseUint(value, 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") - } - - 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 e6ddd7330..000000000 --- a/vendor/github.com/docker/cli/opts/env.go +++ /dev/null @@ -1,46 +0,0 @@ -package opts - -import ( - "fmt" - "os" - "runtime" - "strings" -) - -// ValidateEnv validates an environment variable and returns it. -// If no value is specified, it returns the current value using os.Getenv. -// -// As on ParseEnvFile and related to #16585, environment variable names -// are not validate what so ever, it's up to application inside docker -// to validate them or not. -// -// The only validation here is to check if name is empty, per #25099 -func ValidateEnv(val string) (string, error) { - arr := strings.Split(val, "=") - if arr[0] == "" { - return "", fmt.Errorf("invalid environment variable: %s", val) - } - if len(arr) > 1 { - return val, nil - } - if !doesEnvExist(val) { - return val, nil - } - return fmt.Sprintf("%s=%s", val, os.Getenv(val)), nil -} - -func doesEnvExist(name string) bool { - for _, entry := range os.Environ() { - parts := strings.SplitN(entry, "=", 2) - if runtime.GOOS == "windows" { - // Environment variable are case-insensitive on Windows. PaTh, path and PATH are equivalent. - if strings.EqualFold(parts[0], name) { - return true - } - } - if parts[0] == name { - return true - } - } - return false -} 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 69d3ca6f6..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 2346cc167..000000000 --- a/vendor/github.com/docker/cli/opts/file.go +++ /dev/null @@ -1,77 +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, "#") { - data := strings.SplitN(line, "=", 2) - - // trim the front of a variable, but nothing else - variable := strings.TrimLeft(data[0], 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 len(data) > 1 { - // pass the value through, no trimming - lines = append(lines, fmt.Sprintf("%s=%s", variable, data[1])) - } else { - var value string - 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, fmt.Sprintf("%s=%s", strings.TrimSpace(line), 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 e110a4771..000000000 --- a/vendor/github.com/docker/cli/opts/gpus.go +++ /dev/null @@ -1,112 +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 { - parts := strings.SplitN(field, "=", 2) - key := parts[0] - if _, ok := seen[key]; ok { - return fmt.Errorf("gpu request key '%s' can be specified only once", key) - } - seen[key] = struct{}{} - - if len(parts) == 1 { - seen["count"] = struct{}{} - req.Count, err = parseCount(key) - if err != nil { - return err - } - continue - } - - value := parts[1] - switch key { - case "driver": - req.Driver = value - case "count": - req.Count, err = parseCount(value) - if err != nil { - return err - } - case "device": - req.DeviceIDs = strings.Split(value, ",") - case "capabilities": - req.Capabilities = [][]string{append(strings.Split(value, ","), "gpu")} - case "options": - r := csv.NewReader(strings.NewReader(value)) - 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 408bc24a0..000000000 --- a/vendor/github.com/docker/cli/opts/hosts.go +++ /dev/null @@ -1,167 +0,0 @@ -package opts - -import ( - "fmt" - "net" - "net/url" - "strconv" - "strings" -) - -var ( - // 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 = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultHTTPPort) - // DefaultTLSHost constant defines the default host string used by docker for TLS sockets - DefaultTLSHost = fmt.Sprintf("tcp://%s:%d", DefaultHTTPHost, DefaultTLSHTTPPort) - // DefaultNamedPipe defines the default named pipe used by docker on Windows - DefaultNamedPipe = `//./pipe/docker_engine` -) - -// ValidateHost validates that the specified string is a valid host and returns 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) { - addrParts := strings.SplitN(addr, "://", 2) - if len(addrParts) == 1 && addrParts[0] != "" { - addrParts = []string{"tcp", addrParts[0]} - } - - switch addrParts[0] { - case "tcp": - return ParseTCPAddr(addrParts[1], DefaultTCPHost) - case "unix": - return parseSimpleProtoAddr("unix", addrParts[1], DefaultUnixSocket) - case "npipe": - return parseSimpleProtoAddr("npipe", addrParts[1], 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). -func ValidateExtraHost(val string) (string, error) { - // allow for IPv6 addresses in extra hosts by only splitting on first ":" - arr := strings.SplitN(val, ":", 2) - if len(arr) != 2 || len(arr[0]) == 0 { - return "", fmt.Errorf("bad format for add-host: %q", val) - } - if _, err := ValidateIPAddress(arr[1]); err != nil { - return "", fmt.Errorf("invalid IP address in add-host: %q", arr[1]) - } - 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 611407a9d..000000000 --- a/vendor/github.com/docker/cli/opts/hosts_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows - -package opts - -import "fmt" - -// DefaultHost constant defines the default host string used by docker on other hosts than Windows -var DefaultHost = fmt.Sprintf("unix://%s", DefaultUnixSocket) 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 7c239e00f..000000000 --- a/vendor/github.com/docker/cli/opts/hosts_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build windows - -package opts - -// DefaultHost constant defines the default host string used by docker on Windows -var DefaultHost = "npipe://" + DefaultNamedPipe 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 ef661dd51..000000000 --- a/vendor/github.com/docker/cli/opts/mount.go +++ /dev/null @@ -1,182 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "os" - "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) { - parts := strings.SplitN(value, "=", 2) - if len(parts) == 1 { - target[value] = "" - } else { - target[parts[0]] = parts[1] - } - } - - mount.Type = mounttypes.TypeVolume // default to volume mounts - // Set writable as the default - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - key := strings.ToLower(parts[0]) - - if len(parts) == 1 { - switch key { - case "readonly", "ro": - mount.ReadOnly = true - continue - case "volume-nocopy": - volumeOptions().NoCopy = true - continue - case "bind-nonrecursive": - bindOptions().NonRecursive = true - continue - } - } - - if len(parts) != 2 { - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - - value := parts[1] - switch key { - case "type": - mount.Type = mounttypes.Type(strings.ToLower(value)) - case "source", "src": - mount.Source = value - case "target", "dst", "destination": - mount.Target = value - case "readonly", "ro": - mount.ReadOnly, err = strconv.ParseBool(value) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - case "consistency": - mount.Consistency = mounttypes.Consistency(strings.ToLower(value)) - case "bind-propagation": - bindOptions().Propagation = mounttypes.Propagation(strings.ToLower(value)) - case "bind-nonrecursive": - bindOptions().NonRecursive, err = strconv.ParseBool(value) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - case "volume-nocopy": - volumeOptions().NoCopy, err = strconv.ParseBool(value) - if err != nil { - return fmt.Errorf("invalid value for volume-nocopy: %s", value) - } - case "volume-label": - setValueOnMap(volumeOptions().Labels, value) - case "volume-driver": - volumeOptions().DriverConfig.Name = value - case "volume-opt": - if volumeOptions().DriverConfig.Options == nil { - volumeOptions().DriverConfig.Options = make(map[string]string) - } - setValueOnMap(volumeOptions().DriverConfig.Options, value) - case "tmpfs-size": - sizeBytes, err := units.RAMInBytes(value) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - tmpfsOptions().SizeBytes = sizeBytes - case "tmpfs-mode": - ui64, err := strconv.ParseUint(value, 8, 32) - if err != nil { - return fmt.Errorf("invalid value for %s: %s", key, value) - } - 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 4f5b53b1b..000000000 --- a/vendor/github.com/docker/cli/opts/network.go +++ /dev/null @@ -1,120 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "regexp" - "strings" -) - -const ( - networkOptName = "name" - networkOptAlias = "alias" - 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 // TODO add support for IPv4-address in the csv notation of `--network` - IPv6Address string // TODO add support for IPv6-address in the csv notation of `--network` - 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 { - parts := strings.SplitN(field, "=", 2) - - if len(parts) < 2 { - return fmt.Errorf("invalid field %s", field) - } - - key := strings.TrimSpace(strings.ToLower(parts[0])) - value := strings.TrimSpace(strings.ToLower(parts[1])) - - switch key { - case networkOptName: - netOpt.Target = value - case networkOptAlias: - netOpt.Aliases = append(netOpt.Aliases, value) - case driverOpt: - key, value, err = parseDriverOpt(value) - if err == nil { - if netOpt.DriverOpts == nil { - netOpt.DriverOpts = make(map[string]string) - } - netOpt.DriverOpts[key] = value - } else { - return err - } - 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) { - parts := strings.SplitN(driverOpt, "=", 2) - if len(parts) != 2 { - return "", "", fmt.Errorf("invalid key value pair format in driver options") - } - key := strings.TrimSpace(strings.ToLower(parts[0])) - value := strings.TrimSpace(strings.ToLower(parts[1])) - 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 765548f6b..000000000 --- a/vendor/github.com/docker/cli/opts/opts.go +++ /dev/null @@ -1,523 +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 - } - vals := strings.SplitN(value, "=", 2) - if len(vals) == 1 { - (opts.values)[vals[0]] = "" - } else { - (opts.values)[vals[0]] = vals[1] - } - 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) { - var 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(val string) (string, error) { - arr := strings.SplitN(val, "=", 2) - key := strings.TrimLeft(arr[0], whiteSpaces) - if key == "" { - return "", fmt.Errorf("invalid label '%s': empty name", val) - } - if strings.ContainsAny(key, whiteSpaces) { - return "", fmt.Errorf("label '%s' contains whitespaces", key) - } - return val, 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.", - } - arr := strings.Split(val, "=") - if len(arr) < 2 { - return "", fmt.Errorf("sysctl '%s' is not whitelisted", val) - } - if validSysctlMap[arr[0]] { - return val, nil - } - - for _, vp := range validSysctlPrefixes { - if strings.HasPrefix(arr[0], vp) { - return val, nil - } - } - return "", fmt.Errorf("sysctl '%s' is not whitelisted", val) -} - -// ValidateProgressOutput errors out if an invalid value is passed to --progress -func ValidateProgressOutput(val string) error { - valid := []string{"auto", "plain", "tty"} - for _, s := range valid { - if s == val { - return nil - } - } - return fmt.Errorf("invalid value %q passed to --progress, valid values are: %s", val, strings.Join(valid, ", ")) -} - -// 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)") - } - f := strings.SplitN(value, "=", 2) - name := strings.ToLower(strings.TrimSpace(f[0])) - value = strings.TrimSpace(f[1]) - - o.filter.Add(name, value) - 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") - } - arr := strings.Split(val, ":") - if len(arr) > 2 { - return "", "", fmt.Errorf("bad format for links: %s", val) - } - 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], "/") { - _, 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/opts_unix.go b/vendor/github.com/docker/cli/opts/opts_unix.go deleted file mode 100644 index 2766a43a0..000000000 --- a/vendor/github.com/docker/cli/opts/opts_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +build !windows - -package opts - -// 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/opts_windows.go b/vendor/github.com/docker/cli/opts/opts_windows.go deleted file mode 100644 index 98b7251a9..000000000 --- a/vendor/github.com/docker/cli/opts/opts_windows.go +++ /dev/null @@ -1,56 +0,0 @@ -package opts - -// 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/parse.go b/vendor/github.com/docker/cli/opts/parse.go deleted file mode 100644 index 70b60e142..000000000 --- a/vendor/github.com/docker/cli/opts/parse.go +++ /dev/null @@ -1,99 +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) { - 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 { - kv := strings.SplitN(value, "=", 2) - if len(kv) == 1 { - result[kv[0]] = "" - } else { - result[kv[0]] = kv[1] - } - } - - 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 { - kv := strings.SplitN(value, "=", 2) - if len(kv) == 1 { - result[kv[0]] = nil - } else { - result[kv[0]] = &kv[1] - } - } - - 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 - } - - parts := strings.Split(policy, ":") - - if len(parts) > 2 { - return p, fmt.Errorf("invalid restart policy format") - } - if len(parts) == 2 { - count, err := strconv.Atoi(parts[1]) - if err != nil { - return p, fmt.Errorf("maximum retry count must be an integer") - } - - p.MaximumRetryCount = count - } - - p.Name = parts[0] - - 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 a4a91b1d5..000000000 --- a/vendor/github.com/docker/cli/opts/port.go +++ /dev/null @@ -1,172 +0,0 @@ -package opts - -import ( - "encoding/csv" - "fmt" - "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 { - parts := strings.SplitN(field, "=", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid field %s", field) - } - - key := strings.ToLower(parts[0]) - value := strings.ToLower(parts[1]) - - switch key { - case portOptProtocol: - if value != string(swarm.PortConfigProtocolTCP) && value != string(swarm.PortConfigProtocolUDP) && value != string(swarm.PortConfigProtocolSCTP) { - return fmt.Errorf("invalid protocol value %s", value) - } - - pConfig.Protocol = swarm.PortConfigProtocol(value) - case portOptMode: - if value != string(swarm.PortConfigPublishModeIngress) && value != string(swarm.PortConfigPublishModeHost) { - return fmt.Errorf("invalid publish mode value %s", value) - } - - pConfig.PublishMode = swarm.PortConfigPublishMode(value) - case portOptTargetPort: - tPort, err := strconv.ParseUint(value, 10, 16) - if err != nil { - return err - } - - pConfig.TargetPort = uint32(tPort) - case portOptPublishedPort: - pPort, err := strconv.ParseUint(value, 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 binding.HostIP != "" && binding.HostIP != "0.0.0.0" { - logrus.Warnf("ignoring IP-address (%s:%s:%s) service will listen on '0.0.0.0'", 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 09c68a526..000000000 --- a/vendor/github.com/docker/cli/opts/quotedstring.go +++ /dev/null @@ -1,37 +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 { - 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/runtime.go b/vendor/github.com/docker/cli/opts/runtime.go deleted file mode 100644 index 4361b3ce0..000000000 --- a/vendor/github.com/docker/cli/opts/runtime.go +++ /dev/null @@ -1,79 +0,0 @@ -package opts - -import ( - "fmt" - "strings" - - "github.com/docker/docker/api/types" -) - -// RuntimeOpt defines a map of Runtimes -type RuntimeOpt struct { - name string - stockRuntimeName string - values *map[string]types.Runtime -} - -// NewNamedRuntimeOpt creates a new RuntimeOpt -func NewNamedRuntimeOpt(name string, ref *map[string]types.Runtime, stockRuntime string) *RuntimeOpt { - if ref == nil { - ref = &map[string]types.Runtime{} - } - return &RuntimeOpt{name: name, values: ref, stockRuntimeName: stockRuntime} -} - -// Name returns the name of the NamedListOpts in the configuration. -func (o *RuntimeOpt) Name() string { - return o.name -} - -// Set validates and updates the list of Runtimes -func (o *RuntimeOpt) Set(val string) error { - parts := strings.SplitN(val, "=", 2) - if len(parts) != 2 { - return fmt.Errorf("invalid runtime argument: %s", val) - } - - parts[0] = strings.TrimSpace(parts[0]) - parts[1] = strings.TrimSpace(parts[1]) - if parts[0] == "" || parts[1] == "" { - return fmt.Errorf("invalid runtime argument: %s", val) - } - - parts[0] = strings.ToLower(parts[0]) - if parts[0] == o.stockRuntimeName { - return fmt.Errorf("runtime name '%s' is reserved", o.stockRuntimeName) - } - - if _, ok := (*o.values)[parts[0]]; ok { - return fmt.Errorf("runtime '%s' was already defined", parts[0]) - } - - (*o.values)[parts[0]] = types.Runtime{Path: parts[1]} - - return nil -} - -// String returns Runtime values as a string. -func (o *RuntimeOpt) String() string { - var out []string - for k := range *o.values { - out = append(out, k) - } - - return fmt.Sprintf("%v", out) -} - -// GetMap returns a map of Runtimes (name: path) -func (o *RuntimeOpt) GetMap() map[string]types.Runtime { - if o.values != nil { - return *o.values - } - - return map[string]types.Runtime{} -} - -// Type returns the type of the option -func (o *RuntimeOpt) Type() string { - return "runtime" -} 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 a1fde54d9..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: 0444, - }, - } - - // support a simple syntax of --secret foo - if len(fields) == 1 { - options.File.Name = fields[0] - options.SecretName = fields[0] - o.values = append(o.values, options) - return nil - } - - for _, field := range fields { - parts := strings.SplitN(field, "=", 2) - key := strings.ToLower(parts[0]) - - if len(parts) != 2 { - return fmt.Errorf("invalid field '%s' must be a key=value pair", field) - } - - value := parts[1] - switch key { - case "source", "src": - options.SecretName = value - case "target": - options.File.Name = value - case "uid": - options.File.UID = value - case "gid": - options.File.GID = value - case "mode": - m, err := strconv.ParseUint(value, 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") - } - - 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 0959efae3..000000000 --- a/vendor/github.com/docker/cli/opts/throttledevice.go +++ /dev/null @@ -1,108 +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) { - split := strings.SplitN(val, ":", 2) - if len(split) != 2 { - return nil, fmt.Errorf("bad format: %s", val) - } - if !strings.HasPrefix(split[0], "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - rate, err := units.RAMInBytes(split[1]) - 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: split[0], - Rate: uint64(rate), - }, nil -} - -// ValidateThrottleIOpsDevice validates that the specified string has a valid device-rate format. -func ValidateThrottleIOpsDevice(val string) (*blkiodev.ThrottleDevice, error) { - split := strings.SplitN(val, ":", 2) - if len(split) != 2 { - return nil, fmt.Errorf("bad format: %s", val) - } - if !strings.HasPrefix(split[0], "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - rate, err := strconv.ParseUint(split[1], 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) - } - if rate < 0 { - return nil, fmt.Errorf("invalid rate for device: %s. The correct format is :. Number must be a positive integer", val) - } - - return &blkiodev.ThrottleDevice{Path: split[0], 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 { - var throttledevice []*blkiodev.ThrottleDevice - throttledevice = append(throttledevice, opt.values...) - - return throttledevice -} - -// 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 5adfe3085..000000000 --- a/vendor/github.com/docker/cli/opts/ulimit.go +++ /dev/null @@ -1,57 +0,0 @@ -package opts - -import ( - "fmt" - - "github.com/docker/go-units" -) - -// UlimitOpt defines a map of Ulimits -type UlimitOpt struct { - values *map[string]*units.Ulimit -} - -// NewUlimitOpt creates a new UlimitOpt -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. -func (o *UlimitOpt) String() string { - var out []string - for _, v := range *o.values { - out = append(out, v.String()) - } - - return fmt.Sprintf("%v", out) -} - -// GetList returns a slice of pointers to Ulimits. -func (o *UlimitOpt) GetList() []*units.Ulimit { - var ulimits []*units.Ulimit - for _, v := range *o.values { - ulimits = append(ulimits, v) - } - - 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 46ce9b656..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) { - split := strings.SplitN(val, ":", 2) - if len(split) != 2 { - return nil, fmt.Errorf("bad format: %s", val) - } - if !strings.HasPrefix(split[0], "/dev/") { - return nil, fmt.Errorf("bad format for device path: %s", val) - } - weight, err := strconv.ParseUint(split[1], 10, 0) - 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: split[0], - 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 { - values := []*blkiodev.WeightDevice{} - return WeightdeviceOpt{ - values: values, - 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/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/blobs.go b/vendor/github.com/docker/distribution/blobs.go deleted file mode 100644 index c0e9261be..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/docker/distribution/reference" - "github.com/opencontainers/go-digest" - "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/digestset/set.go b/vendor/github.com/docker/distribution/digestset/set.go deleted file mode 100644 index 71327dca7..000000000 --- a/vendor/github.com/docker/distribution/digestset/set.go +++ /dev/null @@ -1,247 +0,0 @@ -package digestset - -import ( - "errors" - "sort" - "strings" - "sync" - - digest "github.com/opencontainers/go-digest" -) - -var ( - // ErrDigestNotFound is used when a matching digest - // could not be found in a set. - ErrDigestNotFound = errors.New("digest not found") - - // ErrDigestAmbiguous is used when multiple digests - // are found in a set. None of the matching digests - // should be considered valid matches. - ErrDigestAmbiguous = errors.New("ambiguous digest string") -) - -// Set is used to hold a unique set of digests which -// may be easily referenced by easily referenced by a string -// representation of the digest as well as short representation. -// The uniqueness of the short representation is based on other -// digests in the set. If digests are omitted from this set, -// collisions in a larger set may not be detected, therefore it -// is important to always do short representation lookups on -// the complete set of digests. To mitigate collisions, an -// appropriately long short code should be used. -type Set struct { - mutex sync.RWMutex - entries digestEntries -} - -// NewSet creates an empty set of digests -// which may have digests added. -func NewSet() *Set { - return &Set{ - entries: digestEntries{}, - } -} - -// checkShortMatch checks whether two digests match as either whole -// values or short values. This function does not test equality, -// rather whether the second value could match against the first -// value. -func checkShortMatch(alg digest.Algorithm, hex, shortAlg, shortHex string) bool { - if len(hex) == len(shortHex) { - if hex != shortHex { - return false - } - if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - } else if !strings.HasPrefix(hex, shortHex) { - return false - } else if len(shortAlg) > 0 && string(alg) != shortAlg { - return false - } - return true -} - -// Lookup looks for a digest matching the given string representation. -// If no digests could be found ErrDigestNotFound will be returned -// with an empty digest value. If multiple matches are found -// ErrDigestAmbiguous will be returned with an empty digest value. -func (dst *Set) Lookup(d string) (digest.Digest, error) { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - if len(dst.entries) == 0 { - return "", ErrDigestNotFound - } - var ( - searchFunc func(int) bool - alg digest.Algorithm - hex string - ) - dgst, err := digest.Parse(d) - if err == digest.ErrDigestInvalidFormat { - hex = d - searchFunc = func(i int) bool { - return dst.entries[i].val >= d - } - } else { - hex = dgst.Hex() - alg = dgst.Algorithm() - searchFunc = func(i int) bool { - if dst.entries[i].val == hex { - return dst.entries[i].alg >= alg - } - return dst.entries[i].val >= hex - } - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) || !checkShortMatch(dst.entries[idx].alg, dst.entries[idx].val, string(alg), hex) { - return "", ErrDigestNotFound - } - if dst.entries[idx].alg == alg && dst.entries[idx].val == hex { - return dst.entries[idx].digest, nil - } - if idx+1 < len(dst.entries) && checkShortMatch(dst.entries[idx+1].alg, dst.entries[idx+1].val, string(alg), hex) { - return "", ErrDigestAmbiguous - } - - return dst.entries[idx].digest, nil -} - -// Add adds the given digest to the set. An error will be returned -// if the given digest is invalid. If the digest already exists in the -// set, this operation will be a no-op. -func (dst *Set) Add(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - if idx == len(dst.entries) { - dst.entries = append(dst.entries, entry) - return nil - } else if dst.entries[idx].digest == d { - return nil - } - - entries := append(dst.entries, nil) - copy(entries[idx+1:], entries[idx:len(entries)-1]) - entries[idx] = entry - dst.entries = entries - return nil -} - -// Remove removes the given digest from the set. An err will be -// returned if the given digest is invalid. If the digest does -// not exist in the set, this operation will be a no-op. -func (dst *Set) Remove(d digest.Digest) error { - if err := d.Validate(); err != nil { - return err - } - dst.mutex.Lock() - defer dst.mutex.Unlock() - entry := &digestEntry{alg: d.Algorithm(), val: d.Hex(), digest: d} - searchFunc := func(i int) bool { - if dst.entries[i].val == entry.val { - return dst.entries[i].alg >= entry.alg - } - return dst.entries[i].val >= entry.val - } - idx := sort.Search(len(dst.entries), searchFunc) - // Not found if idx is after or value at idx is not digest - if idx == len(dst.entries) || dst.entries[idx].digest != d { - return nil - } - - entries := dst.entries - copy(entries[idx:], entries[idx+1:]) - entries = entries[:len(entries)-1] - dst.entries = entries - - return nil -} - -// All returns all the digests in the set -func (dst *Set) All() []digest.Digest { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - retValues := make([]digest.Digest, len(dst.entries)) - for i := range dst.entries { - retValues[i] = dst.entries[i].digest - } - - return retValues -} - -// ShortCodeTable returns a map of Digest to unique short codes. The -// length represents the minimum value, the maximum length may be the -// entire value of digest if uniqueness cannot be achieved without the -// full value. This function will attempt to make short codes as short -// as possible to be unique. -func ShortCodeTable(dst *Set, length int) map[digest.Digest]string { - dst.mutex.RLock() - defer dst.mutex.RUnlock() - m := make(map[digest.Digest]string, len(dst.entries)) - l := length - resetIdx := 0 - for i := 0; i < len(dst.entries); i++ { - var short string - extended := true - for extended { - extended = false - if len(dst.entries[i].val) <= l { - short = dst.entries[i].digest.String() - } else { - short = dst.entries[i].val[:l] - for j := i + 1; j < len(dst.entries); j++ { - if checkShortMatch(dst.entries[j].alg, dst.entries[j].val, "", short) { - if j > resetIdx { - resetIdx = j - } - extended = true - } else { - break - } - } - if extended { - l++ - } - } - } - m[dst.entries[i].digest] = short - if i >= resetIdx { - l = length - } - } - return m -} - -type digestEntry struct { - alg digest.Algorithm - val string - digest digest.Digest -} - -type digestEntries []*digestEntry - -func (d digestEntries) Len() int { - return len(d) -} - -func (d digestEntries) Less(i, j int) bool { - if d[i].val != d[j].val { - return d[i].val < d[j].val - } - return d[i].alg < d[j].alg -} - -func (d digestEntries) Swap(i, j int) { - d[i], d[j] = d[j], d[i] -} 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/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/manifests.go b/vendor/github.com/docker/distribution/manifests.go deleted file mode 100644 index 1816baea1..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, 0) - -// 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.go b/vendor/github.com/docker/distribution/reference/helpers.go deleted file mode 100644 index 978df7eab..000000000 --- a/vendor/github.com/docker/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 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/docker/distribution/reference/normalize.go b/vendor/github.com/docker/distribution/reference/normalize.go deleted file mode 100644 index 2d71fc5e9..000000000 --- a/vendor/github.com/docker/distribution/reference/normalize.go +++ /dev/null @@ -1,170 +0,0 @@ -package reference - -import ( - "errors" - "fmt" - "strings" - - "github.com/docker/distribution/digestset" - "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, errors.New("invalid reference format: repository name must be lowercase") - } - - 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 -} - -// 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") { - 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 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) -} - -// ParseAnyReferenceWithSet parses a reference string as a possible short -// identifier to be matched in a digest set, a full digest, or familiar name. -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 ParseNormalizedNamed(ref) -} diff --git a/vendor/github.com/docker/distribution/reference/reference.go b/vendor/github.com/docker/distribution/reference/reference.go deleted file mode 100644 index 2f66cca87..000000000 --- a/vendor/github.com/docker/distribution/reference/reference.go +++ /dev/null @@ -1,433 +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 '/'] path-component ['/' path-component]* -// domain := domain-component ['.' domain-component]* [':' port-number] -// 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 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. -// 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 nameMatch != nil && 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 { - domain, path := SplitHostname(ref) - return repository{ - domain: domain, - path: path, - } -} - -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/docker/distribution/reference/regexp.go b/vendor/github.com/docker/distribution/reference/regexp.go deleted file mode 100644 index 786034932..000000000 --- a/vendor/github.com/docker/distribution/reference/regexp.go +++ /dev/null @@ -1,143 +0,0 @@ -package reference - -import "regexp" - -var ( - // alphaNumericRegexp defines the alpha numeric atom, typically a - // component of names. This only allows lower case characters and digits. - alphaNumericRegexp = match(`[a-z0-9]+`) - - // separatorRegexp defines the separators allowed to be embedded in name - // components. This allow one period, one or two underscore and multiple - // dashes. - separatorRegexp = match(`(?:[._]|__|[-]*)`) - - // nameComponentRegexp 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. - nameComponentRegexp = expression( - alphaNumericRegexp, - optional(repeated(separatorRegexp, alphaNumericRegexp))) - - // domainComponentRegexp restricts the registry domain component of a - // repository name to start with a component as defined by DomainRegexp - // and followed by an optional port. - domainComponentRegexp = match(`(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-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 = expression( - domainComponentRegexp, - optional(repeated(literal(`.`), domainComponentRegexp)), - optional(literal(`:`), match(`[0-9]+`))) - - // TagRegexp matches valid tag names. From docker/docker:graph/tags.go. - TagRegexp = match(`[\w][\w.-]{0,127}`) - - // anchoredTagRegexp matches valid tag names, anchored at the start and - // end of the matched string. - anchoredTagRegexp = anchored(TagRegexp) - - // DigestRegexp matches valid digests. - DigestRegexp = match(`[A-Za-z][A-Za-z0-9]*(?:[-_+.][A-Za-z][A-Za-z0-9]*)*[:][[:xdigit:]]{32,}`) - - // anchoredDigestRegexp matches valid digests, anchored at the start and - // end of the matched string. - anchoredDigestRegexp = anchored(DigestRegexp) - - // 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 = expression( - optional(DomainRegexp, literal(`/`)), - nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp))) - - // anchoredNameRegexp is used to parse a name value, capturing the - // domain and trailing components. - anchoredNameRegexp = anchored( - optional(capture(DomainRegexp), literal(`/`)), - capture(nameComponentRegexp, - optional(repeated(literal(`/`), nameComponentRegexp)))) - - // ReferenceRegexp is the full supported format of a reference. The regexp - // is anchored and has capturing groups for name, tag, and digest - // components. - ReferenceRegexp = anchored(capture(NameRegexp), - optional(literal(":"), capture(TagRegexp)), - optional(literal("@"), capture(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. - IdentifierRegexp = match(`([a-f0-9]{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 = match(`([a-f0-9]{6,64})`) - - // anchoredIdentifierRegexp is used to check or match an - // identifier value, anchored at start and end of string. - anchoredIdentifierRegexp = anchored(IdentifierRegexp) - - // anchoredShortIdentifierRegexp is used to check if a value - // is a possible identifier prefix, anchored at start and end - // of string. - anchoredShortIdentifierRegexp = anchored(ShortIdentifierRegexp) -) - -// match compiles the string to a regular expression. -var match = regexp.MustCompile - -// literal compiles s into a literal regular expression, escaping any regexp -// reserved characters. -func literal(s string) *regexp.Regexp { - re := match(regexp.QuoteMeta(s)) - - if _, complete := re.LiteralPrefix(); !complete { - panic("must be a literal") - } - - return re -} - -// expression defines a full expression, where each regular expression must -// follow the previous. -func expression(res ...*regexp.Regexp) *regexp.Regexp { - var s string - for _, re := range res { - s += re.String() - } - - return match(s) -} - -// optional wraps the expression in a non-capturing group and makes the -// production optional. -func optional(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `?`) -} - -// repeated wraps the regexp in a non-capturing group to get one or more -// matches. -func repeated(res ...*regexp.Regexp) *regexp.Regexp { - return match(group(expression(res...)).String() + `+`) -} - -// group wraps the regexp in a non-capturing group. -func group(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(?:` + expression(res...).String() + `)`) -} - -// capture wraps the expression in a capturing group. -func capture(res ...*regexp.Regexp) *regexp.Regexp { - return match(`(` + expression(res...).String() + `)`) -} - -// anchored anchors the regular expression by adding start and end delimiters. -func anchored(res ...*regexp.Regexp) *regexp.Regexp { - return match(`^` + expression(res...).String() + `$`) -} diff --git a/vendor/github.com/docker/distribution/registry.go b/vendor/github.com/docker/distribution/registry.go deleted file mode 100644 index 6c3210989..000000000 --- a/vendor/github.com/docker/distribution/registry.go +++ /dev/null @@ -1,118 +0,0 @@ -package distribution - -import ( - "context" - - "github.com/docker/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 6d9bb4b62..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.(type) { - case ErrorCode: - err = daErr.(ErrorCode).WithDetail(nil) - case Error: - err = daErr.(Error) - 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 a9616c58a..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/descriptors.go +++ /dev/null @@ -1,1596 +0,0 @@ -package v2 - -import ( - "net/http" - "regexp" - - "github.com/docker/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, - }, - } - - 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{ - 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, - }, - }, - }, - }, - }, - }, - }, - }, -} - -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 97d6923aa..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/errors.go +++ /dev/null @@ -1,136 +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, - }) -) 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 1337bdb12..000000000 --- a/vendor/github.com/docker/distribution/registry/api/v2/urls.go +++ /dev/null @@ -1,266 +0,0 @@ -package v2 - -import ( - "fmt" - "net/http" - "net/url" - "strings" - - "github.com/docker/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 -} - -// appendValues appends the parameters to the url. Panics if the string is not -// a url. -func appendValues(u string, values ...url.Values) string { - up, err := url.Parse(u) - - if err != nil { - panic(err) // should never happen - } - - return appendValuesURL(up, values...).String() -} 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 6e3f1ccc4..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.IndexRune(" \t\"(),/:;<=>?@[]\\{}", rune(c)) >= 0 - if strings.IndexRune(" \t\r\n", rune(c)) >= 0 { - 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 695bf852f..000000000 --- a/vendor/github.com/docker/distribution/registry/client/blob_writer.go +++ /dev/null @@ -1,162 +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() - - 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 52d49d5d2..000000000 --- a/vendor/github.com/docker/distribution/registry/client/errors.go +++ /dev/null @@ -1,139 +0,0 @@ -package client - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "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(statusCode int, r io.Reader) error { - var errors errcode.Errors - body, err := ioutil.ReadAll(r) - if err != nil { - return err - } - - // 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 != "" { - switch statusCode { - case http.StatusUnauthorized: - return errcode.ErrorCodeUnauthorized.WithMessage(detailsErr.Details) - case http.StatusTooManyRequests: - return errcode.ErrorCodeTooManyRequests.WithMessage(detailsErr.Details) - default: - return errcode.ErrorCodeUnknown.WithMessage(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 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.StatusCode, resp.Body)) - } - } - err := parseHTTPErrorResponse(resp.StatusCode, resp.Body) - 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 aa442e654..000000000 --- a/vendor/github.com/docker/distribution/registry/client/repository.go +++ /dev/null @@ -1,867 +0,0 @@ -package client - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - "time" - - "github.com/docker/distribution" - "github.com/docker/distribution/reference" - "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 - } - - for cnt := range ctlg.Repositories { - entries[cnt] = ctlg.Repositories[cnt] - } - 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 - } - - resp, err := bs.client.Post(u, "", nil) - 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 1d0b382fb..000000000 --- a/vendor/github.com/docker/distribution/registry/client/transport/http_reader.go +++ /dev/null @@ -1,250 +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")) - } - - req.Header.Add("Accept-Encoding", "identity") - 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 42d94d9bd..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/docker/distribution" - "github.com/docker/distribution/reference" - "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/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 d1d0434cb..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/client.go +++ /dev/null @@ -1,121 +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("store") - - 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 { - t := strings.TrimSpace(string(out)) - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return fmt.Errorf("error storing credentials - err: %v, out: `%s`", err, t) - } - - 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("get") - cmd.Input(strings.NewReader(serverURL)) - - out, err := cmd.Output() - if err != nil { - t := strings.TrimSpace(string(out)) - - if credentials.IsErrCredentialsNotFoundMessage(t) { - return nil, credentials.NewErrCredentialsNotFound() - } - - if isValidErr := isValidCredsMessage(t); isValidErr != nil { - err = isValidErr - } - - return nil, fmt.Errorf("error getting credentials - err: %v, out: `%s`", err, t) - } - - 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("erase") - 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("list") - 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 8da334306..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/client/command.go +++ /dev/null @@ -1,56 +0,0 @@ -package client - -import ( - "fmt" - "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...) - programCmd.Env = os.Environ() - if env != nil { - for k, v := range *env { - programCmd.Env = append(programCmd.Env, fmt.Sprintf("%s=%s", 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 da8b594e7..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/credentials.go +++ /dev/null @@ -1,186 +0,0 @@ -package credentials - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "io" - "os" - "strings" -) - -// 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) { - var err error - if len(os.Args) != 2 { - err = fmt.Errorf("Usage: %s ", os.Args[0]) - } - - if err == nil { - err = HandleCommand(helper, os.Args[1], os.Stdin, os.Stdout) - } - - if err != nil { - fmt.Fprintf(os.Stdout, "%v\n", err) - os.Exit(1) - } -} - -// HandleCommand uses a helper and a key to run a credential action. -func HandleCommand(helper Helper, key string, in io.Reader, out io.Writer) error { - switch key { - case "store": - return Store(helper, in) - case "get": - return Get(helper, in, out) - case "erase": - return Erase(helper, in) - case "list": - return List(helper, out) - case "version": - return PrintVersion(out) - } - return fmt.Errorf("Unknown credential action `%s`", key) -} - -// 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 - } - - resp := Credentials{ - ServerURL: serverURL, - Username: username, - Secret: secret, - } - - buffer.Reset() - if err := json.NewEncoder(buffer).Encode(resp); 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.Fprintln(writer, 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 fe6a5aef4..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/error.go +++ /dev/null @@ -1,102 +0,0 @@ -package credentials - -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 -} - -// 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 { - _, ok := err.(errCredentialsNotFound) - return ok -} - -// 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 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 -} - -// 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 -} - -// 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 { - _, ok := err.(errCredentialsMissingServerURL) - return ok -} - -// IsCredentialsMissingServerURLMessage checks for an -// errCredentialsMissingServerURL in the error message. -func IsCredentialsMissingServerURLMessage(err string) bool { - return err == errCredentialsMissingServerURLMessage -} - -// IsCredentialsMissingUsername returns true if the error -// was an errCredentialsMissingUsername. -func IsCredentialsMissingUsername(err error) bool { - _, ok := err.(errCredentialsMissingUsername) - return ok -} - -// IsCredentialsMissingUsernameMessage checks for an -// errCredentialsMissingUsername in the error message. -func IsCredentialsMissingUsernameMessage(err string) bool { - return 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 033a5fee5..000000000 --- a/vendor/github.com/docker/docker-credential-helpers/credentials/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package credentials - -// Version holds a string describing the current version -const Version = "0.6.0" 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 0c74e15b0..000000000 --- a/vendor/github.com/docker/docker/NOTICE +++ /dev/null @@ -1,19 +0,0 @@ -Docker -Copyright 2012-2017 Docker, Inc. - -This product includes software developed at Docker, Inc. (https://www.docker.com). - -This product contains software (https://github.com/kr/pty) developed -by Keith Rarick, licensed under the MIT License. - -The following is courtesy of our legal counsel: - - -Use and transfer of Docker may be subject to certain restrictions by the -United States and other governments. -It is your responsibility to ensure that your use and/or transfer does not -violate applicable laws. - -For more information, please see https://www.bis.doc.gov - -See also https://www.apache.org/dev/crypto.html and/or seek legal counsel. diff --git a/vendor/github.com/docker/docker/api/common.go b/vendor/github.com/docker/docker/api/common.go deleted file mode 100644 index aa146cdae..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.40" - - // 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 504b0c90d..000000000 --- a/vendor/github.com/docker/docker/api/common_unix.go +++ /dev/null @@ -1,6 +0,0 @@ -// +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/types/auth.go b/vendor/github.com/docker/docker/api/types/auth.go deleted file mode 100644 index ddf15bb18..000000000 --- a/vendor/github.com/docker/docker/api/types/auth.go +++ /dev/null @@ -1,22 +0,0 @@ -package types // import "github.com/docker/docker/api/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/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 4b9f50282..000000000 --- a/vendor/github.com/docker/docker/api/types/client.go +++ /dev/null @@ -1,415 +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" - 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 - ContainerID string - Running bool - ExitCode int - Pid int -} - -// ContainerListOptions holds parameters to list containers with. -type ContainerListOptions struct { - Quiet bool - 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 -} - -// HijackedResponse holds connection information for a hijacked request. -type HijackedResponse struct { - Conn net.Conn - Reader *bufio.Reader -} - -// Close closes the hijacked connection and reader. -func (h *HijackedResponse) Close() { - h.Conn.Close() -} - -// 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]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 = "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 filter the list of images with. -type ImageListOptions struct { - All bool - Filters filters.Args -} - -// 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 -} - -// 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 178e911a7..000000000 --- a/vendor/github.com/docker/docker/api/types/configs.go +++ /dev/null @@ -1,64 +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" -) - -// 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 - 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. - 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/config.go b/vendor/github.com/docker/docker/api/types/container/config.go deleted file mode 100644 index f767195b9..000000000 --- a/vendor/github.com/docker/docker/api/types/container/config.go +++ /dev/null @@ -1,69 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -import ( - "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 - -// 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"` -} - -// 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_changes.go b/vendor/github.com/docker/docker/api/types/container/container_changes.go deleted file mode 100644 index 222d14100..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_changes.go +++ /dev/null @@ -1,21 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerChangeResponseItem change item in response to ContainerChanges operation -// swagger:model ContainerChangeResponseItem -type ContainerChangeResponseItem struct { - - // Kind of change - // Required: true - Kind uint8 `json:"Kind"` - - // Path to file that has changed - // Required: true - Path string `json:"Path"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/container_create.go b/vendor/github.com/docker/docker/api/types/container/container_create.go deleted file mode 100644 index 1ec9c3728..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_create.go +++ /dev/null @@ -1,21 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerCreateCreatedBody OK response to ContainerCreate operation -// swagger:model ContainerCreateCreatedBody -type ContainerCreateCreatedBody 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/container_top.go b/vendor/github.com/docker/docker/api/types/container/container_top.go deleted file mode 100644 index f8a606687..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_top.go +++ /dev/null @@ -1,21 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// 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 33addedf7..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_update.go +++ /dev/null @@ -1,17 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// 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/container_wait.go b/vendor/github.com/docker/docker/api/types/container/container_wait.go deleted file mode 100644 index 94b6a20e1..000000000 --- a/vendor/github.com/docker/docker/api/types/container/container_wait.go +++ /dev/null @@ -1,29 +0,0 @@ -package container // import "github.com/docker/docker/api/types/container" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// ContainerWaitOKBodyError container waiting error, if any -// swagger:model ContainerWaitOKBodyError -type ContainerWaitOKBodyError struct { - - // Details of an error - Message string `json:"Message,omitempty"` -} - -// ContainerWaitOKBody OK response to ContainerWait operation -// swagger:model ContainerWaitOKBody -type ContainerWaitOKBody struct { - - // error - // Required: true - Error *ContainerWaitOKBodyError `json:"Error"` - - // Exit code of the container - // Required: true - StatusCode int64 `json:"StatusCode"` -} diff --git a/vendor/github.com/docker/docker/api/types/container/host_config.go b/vendor/github.com/docker/docker/api/types/container/host_config.go deleted file mode 100644 index c3de3d976..000000000 --- a/vendor/github.com/docker/docker/api/types/container/host_config.go +++ /dev/null @@ -1,424 +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" - "github.com/docker/go-units" -) - -// Isolation represents the isolation technology of a container. The supported -// values are platform specific -type Isolation string - -// 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 { - return strings.ToLower(string(i)) == "default" || string(i) == "" -} - -// IsHyperV indicates the use of a Hyper-V partition for isolation -func (i Isolation) IsHyperV() bool { - return strings.ToLower(string(i)) == "hyperv" -} - -// IsProcess indicates the use of process isolation -func (i Isolation) IsProcess() bool { - return strings.ToLower(string(i)) == "process" -} - -const ( - // IsolationEmpty is unspecified (same behavior as default) - IsolationEmpty = Isolation("") - // IsolationDefault is the default isolation mode on current daemon - IsolationDefault = Isolation("default") - // IsolationProcess is process isolation mode - IsolationProcess = Isolation("process") - // IsolationHyperV is HyperV isolation mode - IsolationHyperV = Isolation("hyperv") -) - -// IpcMode represents the container ipc stack. -type IpcMode string - -// IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared. -func (n IpcMode) IsPrivate() bool { - return n == "private" -} - -// IsHost indicates whether the container shares the host's ipc namespace. -func (n IpcMode) IsHost() bool { - return n == "host" -} - -// IsShareable indicates whether the container's ipc namespace can be shared with another container. -func (n IpcMode) IsShareable() bool { - return n == "shareable" -} - -// IsContainer indicates whether the container uses another container's ipc namespace. -func (n IpcMode) IsContainer() bool { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// IsNone indicates whether container IpcMode is set to "none". -func (n IpcMode) IsNone() bool { - return n == "none" -} - -// 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 { - 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() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 && parts[0] == "container" { - return parts[1] - } - return "" -} - -// 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 { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// ConnectedContainer is the id of the container which network this container is connected to. -func (n NetworkMode) ConnectedContainer() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -//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 { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// 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 { - parts := strings.SplitN(string(c), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the cgroup spec is valid. -func (c CgroupSpec) Valid() bool { - return c.IsContainer() || c == "" -} - -// Container returns the name of the container whose cgroup will be used. -func (c CgroupSpec) Container() string { - parts := strings.SplitN(string(c), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// 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 { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - default: - return false - } - return true -} - -// 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 { - parts := strings.SplitN(string(n), ":", 2) - return len(parts) > 1 && parts[0] == "container" -} - -// Valid indicates whether the pid namespace is valid. -func (n PidMode) Valid() bool { - parts := strings.Split(string(n), ":") - switch mode := parts[0]; mode { - case "", "host": - case "container": - if len(parts) != 2 || parts[1] == "" { - return false - } - default: - return false - } - return true -} - -// Container returns the name of the container whose pid namespace is going to be used. -func (n PidMode) Container() string { - parts := strings.SplitN(string(n), ":", 2) - if len(parts) > 1 { - return parts[1] - } - return "" -} - -// 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 = "" - 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 int64 // Kernel memory limit (in bytes) - KernelMemoryTCP int64 // 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 - - // 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 - Capabilities []string `json:"Capabilities"` // List of kernel capabilities to be available for container (this overrides the default set) - 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 - ConsoleSize [2]uint // Initial console size (height,width) - 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"` -} 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 cf6fdf440..000000000 --- a/vendor/github.com/docker/docker/api/types/container/hostconfig_unix.go +++ /dev/null @@ -1,41 +0,0 @@ -// +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/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/events/events.go b/vendor/github.com/docker/docker/api/types/events/events.go deleted file mode 100644 index 027c6edb7..000000000 --- a/vendor/github.com/docker/docker/api/types/events/events.go +++ /dev/null @@ -1,52 +0,0 @@ -package events // import "github.com/docker/docker/api/types/events" - -const ( - // ContainerEventType is the event type that containers generate - ContainerEventType = "container" - // DaemonEventType is the event type that daemon generate - DaemonEventType = "daemon" - // ImageEventType is the event type that images generate - ImageEventType = "image" - // NetworkEventType is the event type that networks generate - NetworkEventType = "network" - // PluginEventType is the event type that plugins generate - PluginEventType = "plugin" - // VolumeEventType is the event type that volumes generate - VolumeEventType = "volume" - // ServiceEventType is the event type that services generate - ServiceEventType = "service" - // NodeEventType is the event type that nodes generate - NodeEventType = "node" - // SecretEventType is the event type that secrets generate - SecretEventType = "secret" - // ConfigEventType is the event type that configs generate - ConfigEventType = "config" -) - -// Actor describes something that generates events, -// like a container, or a network, or a volume. -// It has a defined name and a set or 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"` - ID string `json:"id,omitempty"` - From string `json:"from,omitempty"` - - Type string - 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/parse.go b/vendor/github.com/docker/docker/api/types/filters/parse.go deleted file mode 100644 index 1f75403f7..000000000 --- a/vendor/github.com/docker/docker/api/types/filters/parse.go +++ /dev/null @@ -1,315 +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 -} - -// 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: Use ToJSON -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, err - } - - args.fields = deprecatedArgs(deprecated) - return args, nil -} - -// UnmarshalJSON populates the Args from JSON encode bytes -func (args Args) UnmarshalJSON(raw []byte) error { - if len(raw) == 0 { - return nil - } - 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 { - testKV := strings.SplitN(value, "=", 2) - - v, ok := sources[testKV[0]] - if !ok { - return false - } - if len(testKV) == 2 && testKV[1] != 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 -} - -// 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 -} - -type invalidFilter string - -func (e invalidFilter) Error() string { - return "Invalid filter '" + string(e) + "'" -} - -func (invalidFilter) InvalidParameter() {} - -// 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) - } - } - 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 4d9bf1c62..000000000 --- a/vendor/github.com/docker/docker/api/types/graph_driver_data.go +++ /dev/null @@ -1,17 +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 a container's graph driver. -// swagger:model GraphDriverData -type GraphDriverData struct { - - // data - // Required: true - Data map[string]string `json:"Data"` - - // name - // 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 b5a7a0c49..000000000 --- a/vendor/github.com/docker/docker/api/types/image/image_history.go +++ /dev/null @@ -1,37 +0,0 @@ -package image // import "github.com/docker/docker/api/types/image" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// 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_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 e145b3dcf..000000000 --- a/vendor/github.com/docker/docker/api/types/image_summary.go +++ /dev/null @@ -1,49 +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 { - - // containers - // Required: true - Containers int64 `json:"Containers"` - - // created - // Required: true - Created int64 `json:"Created"` - - // Id - // Required: true - ID string `json:"Id"` - - // labels - // Required: true - Labels map[string]string `json:"Labels"` - - // parent Id - // Required: true - ParentID string `json:"ParentId"` - - // repo digests - // Required: true - RepoDigests []string `json:"RepoDigests"` - - // repo tags - // Required: true - RepoTags []string `json:"RepoTags"` - - // shared size - // Required: true - SharedSize int64 `json:"SharedSize"` - - // size - // Required: true - Size int64 `json:"Size"` - - // virtual size - // Required: true - VirtualSize int64 `json:"VirtualSize"` -} 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 ab4446b38..000000000 --- a/vendor/github.com/docker/docker/api/types/mount/mount.go +++ /dev/null @@ -1,131 +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" -) - -// 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"` -} - -// 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"` -} - -// 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 docker/docker/pkg/mount/flags.go: - // - // 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. -} 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 71e97338f..000000000 --- a/vendor/github.com/docker/docker/api/types/network/network.go +++ /dev/null @@ -1,127 +0,0 @@ -package network // import "github.com/docker/docker/api/types/network" -import ( - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/errdefs" -) - -// 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 errdefs.InvalidParameter(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/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 8789ad3b3..000000000 --- a/vendor/github.com/docker/docker/api/types/registry/registry.go +++ /dev/null @@ -1,119 +0,0 @@ -package registry // import "github.com/docker/docker/api/types/registry" - -import ( - "encoding/json" - "net" - - "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 v1.Descriptor - // Platforms contains the list of platforms supported by the image, - // obtained by parsing the manifest - Platforms []v1.Platform -} diff --git a/vendor/github.com/docker/docker/api/types/seccomp.go b/vendor/github.com/docker/docker/api/types/seccomp.go deleted file mode 100644 index 2259c6be1..000000000 --- a/vendor/github.com/docker/docker/api/types/seccomp.go +++ /dev/null @@ -1,94 +0,0 @@ -package types // import "github.com/docker/docker/api/types" - -// Seccomp represents the config for a seccomp profile for syscall restriction. -type Seccomp struct { - DefaultAction Action `json:"defaultAction"` - // Architectures is kept to maintain backward compatibility with the old - // seccomp profile. - Architectures []Arch `json:"architectures,omitempty"` - ArchMap []Architecture `json:"archMap,omitempty"` - Syscalls []*Syscall `json:"syscalls"` -} - -// Architecture is used to represent a specific architecture -// and its sub-architectures -type Architecture struct { - Arch Arch `json:"architecture"` - SubArches []Arch `json:"subArchitectures"` -} - -// Arch used for architectures -type Arch string - -// Additional architectures permitted to be used for system calls -// By default only the native architecture of the kernel is permitted -const ( - ArchX86 Arch = "SCMP_ARCH_X86" - ArchX86_64 Arch = "SCMP_ARCH_X86_64" - ArchX32 Arch = "SCMP_ARCH_X32" - ArchARM Arch = "SCMP_ARCH_ARM" - ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" - ArchMIPS Arch = "SCMP_ARCH_MIPS" - ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" - ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" - ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" - ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" - ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" - ArchPPC Arch = "SCMP_ARCH_PPC" - ArchPPC64 Arch = "SCMP_ARCH_PPC64" - ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" - ArchS390 Arch = "SCMP_ARCH_S390" - ArchS390X Arch = "SCMP_ARCH_S390X" -) - -// Action taken upon Seccomp rule match -type Action string - -// Define actions for Seccomp rules -const ( - ActKill Action = "SCMP_ACT_KILL" - ActTrap Action = "SCMP_ACT_TRAP" - ActErrno Action = "SCMP_ACT_ERRNO" - ActTrace Action = "SCMP_ACT_TRACE" - ActAllow Action = "SCMP_ACT_ALLOW" -) - -// Operator used to match syscall arguments in Seccomp -type Operator string - -// Define operators for syscall arguments in Seccomp -const ( - OpNotEqual Operator = "SCMP_CMP_NE" - OpLessThan Operator = "SCMP_CMP_LT" - OpLessEqual Operator = "SCMP_CMP_LE" - OpEqualTo Operator = "SCMP_CMP_EQ" - OpGreaterEqual Operator = "SCMP_CMP_GE" - OpGreaterThan Operator = "SCMP_CMP_GT" - OpMaskedEqual Operator = "SCMP_CMP_MASKED_EQ" -) - -// Arg used for matching specific syscall arguments in Seccomp -type Arg struct { - Index uint `json:"index"` - Value uint64 `json:"value"` - ValueTwo uint64 `json:"valueTwo"` - Op Operator `json:"op"` -} - -// Filter is used to conditionally apply Seccomp rules -type Filter struct { - Caps []string `json:"caps,omitempty"` - Arches []string `json:"arches,omitempty"` - MinKernel string `json:"minKernel,omitempty"` -} - -// Syscall is used to match a group of syscalls in Seccomp -type Syscall struct { - Name string `json:"name,omitempty"` - Names []string `json:"names,omitempty"` - Action Action `json:"action"` - Args []*Arg `json:"args"` - Comment string `json:"comment"` - Includes Filter `json:"includes"` - Excludes Filter `json:"excludes"` -} 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 ef020f458..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/common.go +++ /dev/null @@ -1,40 +0,0 @@ -package swarm // import "github.com/docker/docker/api/types/swarm" - -import "time" - -// Version represents the internal object version. -type Version struct { - Index uint64 `json:",omitempty"` -} - -// 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 48190c176..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/container.go +++ /dev/null @@ -1,76 +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" -) - -// 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"` -} 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 1e30f5fa1..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/node.go +++ /dev/null @@ -1,115 +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"` -} - -// 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"` -} - -// 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" -) 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 1fdc9b043..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/runtime/plugin.pb.go +++ /dev/null @@ -1,712 +0,0 @@ -// Code generated by protoc-gen-gogo. -// source: plugin.proto -// DO NOT EDIT! - -/* - 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"` -} - -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 -} - -// 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++ - } - 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 encodeFixed64Plugin(dAtA []byte, offset int, v uint64) int { - dAtA[offset] = uint8(v) - dAtA[offset+1] = uint8(v >> 8) - dAtA[offset+2] = uint8(v >> 16) - dAtA[offset+3] = uint8(v >> 24) - dAtA[offset+4] = uint8(v >> 32) - dAtA[offset+5] = uint8(v >> 40) - dAtA[offset+6] = uint8(v >> 48) - dAtA[offset+7] = uint8(v >> 56) - return offset + 8 -} -func encodeFixed32Plugin(dAtA []byte, offset int, v uint32) int { - dAtA[offset] = uint8(v) - dAtA[offset+1] = uint8(v >> 8) - dAtA[offset+2] = uint8(v >> 16) - dAtA[offset+3] = uint8(v >> 24) - return offset + 4 -} -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 - } - 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) - 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{ - // 196 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0xe2, 0xe2, 0x29, 0xc8, 0x29, 0x4d, - 0xcf, 0xcc, 0xd3, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x57, 0x6a, 0x63, 0xe4, 0xe2, 0x0a, 0x00, 0x0b, - 0x04, 0x17, 0xa4, 0x26, 0x0b, 0x09, 0x71, 0xb1, 0xe4, 0x25, 0xe6, 0xa6, 0x4a, 0x30, 0x2a, 0x30, - 0x6a, 0x70, 0x06, 0x81, 0xd9, 0x42, 0x62, 0x5c, 0x6c, 0x45, 0xa9, 0xb9, 0xf9, 0x25, 0xa9, 0x12, - 0x4c, 0x60, 0x51, 0x28, 0x4f, 0xc8, 0x80, 0x8b, 0xab, 0xa0, 0x28, 0xb3, 0x2c, 0x33, 0x27, 0x35, - 0x3d, 0xb5, 0x58, 0x82, 0x59, 0x81, 0x59, 0x83, 0xdb, 0x48, 0x40, 0x0f, 0x62, 0x58, 0x00, 0x4c, - 0x22, 0x08, 0x49, 0x8d, 0x90, 0x14, 0x17, 0x47, 0x4a, 0x66, 0x71, 0x62, 0x52, 0x4e, 0x6a, 0x8a, - 0x04, 0x8b, 0x02, 0xa3, 0x06, 0x47, 0x10, 0x9c, 0xaf, 0x14, 0xcb, 0xc5, 0x8f, 0xa6, 0x15, 0xab, - 0x63, 0x14, 0xb8, 0xb8, 0x53, 0x52, 0x8b, 0x93, 0x8b, 0x32, 0x0b, 0x4a, 0x32, 0xf3, 0xf3, 0xa0, - 0x2e, 0x42, 0x16, 0x12, 0x12, 0xe1, 0x62, 0x2d, 0x4b, 0xcc, 0x29, 0x4d, 0x05, 0xbb, 0x88, 0x33, - 0x08, 0xc2, 0x71, 0xe2, 0x39, 0xf1, 0x48, 0x8e, 0xf1, 0xc2, 0x23, 0x39, 0xc6, 0x07, 0x8f, 0xe4, - 0x18, 0x93, 0xd8, 0xc0, 0x9e, 0x37, 0x06, 0x04, 0x00, 0x00, 0xff, 0xff, 0xb8, 0x84, 0xad, 0x79, - 0x0c, 0x01, 0x00, 0x00, -} 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 abf192e75..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/service.go +++ /dev/null @@ -1,124 +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"` -} - -// 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"` -} - -// 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{} - -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 -} 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 b25f99964..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/swarm.go +++ /dev/null @@ -1,227 +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"` -} - -// 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 d5a57df5d..000000000 --- a/vendor/github.com/docker/docker/api/types/swarm/task.go +++ /dev/null @@ -1,192 +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"` -} - -// 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). -type Resources struct { - NanoCPUs int64 `json:",omitempty"` - MemoryBytes int64 `json:",omitempty"` - GenericResources []GenericResource `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 *Resources `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"` -} diff --git a/vendor/github.com/docker/docker/api/types/time/duration_convert.go b/vendor/github.com/docker/docker/api/types/time/duration_convert.go deleted file mode 100644 index 84b6f0732..000000000 --- a/vendor/github.com/docker/docker/api/types/time/duration_convert.go +++ /dev/null @@ -1,12 +0,0 @@ -package time // import "github.com/docker/docker/api/types/time" - -import ( - "strconv" - "time" -) - -// DurationToSecondsString converts the specified duration to the number -// seconds it represents, formatted as a string. -func DurationToSecondsString(duration time.Duration) string { - return strconv.FormatFloat(duration.Seconds(), 'f', 0, 64) -} 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 ea3495efe..000000000 --- a/vendor/github.com/docker/docker/api/types/time/timestamp.go +++ /dev/null @@ -1,129 +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 or shorter than 9 digits it is -// converted to nanoseconds. The expectation is that the seconds and -// seconds will be used to create a time variable. For example: -// seconds, nanoseconds, err := ParseTimestamp("1136073600.000000001",0) -// if err == nil since := time.Unix(seconds, nanoseconds) -// returns seconds as def(aultSeconds) if value == "" -func ParseTimestamps(value string, def int64) (int64, int64, error) { - if value == "" { - return def, 0, nil - } - return parseTimestamp(value) -} - -func parseTimestamp(value string) (int64, int64, error) { - sa := strings.SplitN(value, ".", 2) - s, err := strconv.ParseInt(sa[0], 10, 64) - if err != nil { - return s, 0, err - } - if len(sa) != 2 { - return s, 0, nil - } - n, err := strconv.ParseInt(sa[1], 10, 64) - if err != nil { - return s, n, err - } - // should already be in nanoseconds but just in case convert n to nanoseconds - n = int64(float64(n) * math.Pow(float64(10), float64(9-len(sa[1])))) - return s, n, 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 a39ffcb7b..000000000 --- a/vendor/github.com/docker/docker/api/types/types.go +++ /dev/null @@ -1,615 +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/go-connections/nat" -) - -// RootFS returns Image's RootFS description including the layer IDs. -type RootFS struct { - Type string - Layers []string `json:",omitempty"` - BaseLayer string `json:",omitempty"` -} - -// ImageInspect contains response of Engine API: -// GET "/images/{name:.*}/json" -type ImageInspect struct { - ID string `json:"Id"` - RepoTags []string - RepoDigests []string - Parent string - Comment string - Created string - Container string - ContainerConfig *container.Config - DockerVersion string - Author string - Config *container.Config - Architecture string - Os string - OsVersion string `json:",omitempty"` - Size int64 - VirtualSize int64 - GraphDriver GraphDriverData - RootFS RootFS - Metadata ImageMetadata -} - -// ImageMetadata contains engine-local data about the image -type ImageMetadata struct { - 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 -} - -// 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 - Plugins PluginsInfo - MemoryLimit bool - SwapLimit bool - KernelMemory bool - KernelMemoryTCP bool - 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 - NEventsListener int - KernelVersion string - OperatingSystem 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 - ClusterStore string - ClusterAdvertise 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"` - Warnings []string -} - -// KeyValue holds a key/value pair -type KeyValue struct { - Key, Value string -} - -// 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{} - split := strings.Split(opt, ",") - for _, s := range split { - kv := strings.SplitN(s, "=", 2) - if len(kv) != 2 { - return nil, fmt.Errorf("invalid security option %q", s) - } - if kv[0] == "" || kv[1] == "" { - return nil, errors.New("invalid empty security option") - } - if kv[0] == "name" { - secopt.Name = kv[1] - continue - } - secopt.Options = append(secopt.Options, KeyValue{Key: kv[0], Value: kv[1]}) - } - 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 -} - -// 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 available in Docker Swarm -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"` - 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 mount.Type `json:",omitempty"` - Name string `json:",omitempty"` - Source string - Destination string - Driver string `json:",omitempty"` - Mode string - RW bool - 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 { - Path string `json:"path"` - Args []string `json:"runtimeArgs,omitempty"` -} - -// DiskUsage contains response of Engine API: -// GET "/system/df" -type DiskUsage struct { - LayersSize int64 - Images []*ImageSummary - Containers []*Container - Volumes []*Volume - BuildCache []*BuildCache - BuilderSize int64 // deprecated -} - -// 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 string - Parent string - Type string - Description string - InUse bool - Shared bool - Size int64 - CreatedAt time.Time - 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/compare.go b/vendor/github.com/docker/docker/api/types/versions/compare.go deleted file mode 100644 index 8ccb0aa92..000000000 --- a/vendor/github.com/docker/docker/api/types/versions/compare.go +++ /dev/null @@ -1,62 +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 { - var ( - currTab = strings.Split(v1, ".") - otherTab = strings.Split(v2, ".") - ) - - max := len(currTab) - if len(otherTab) > max { - max = len(otherTab) - } - for i := 0; i < max; 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.go b/vendor/github.com/docker/docker/api/types/volume.go deleted file mode 100644 index b5ee96a50..000000000 --- a/vendor/github.com/docker/docker/api/types/volume.go +++ /dev/null @@ -1,69 +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 - -// Volume volume -// swagger:model Volume -type Volume struct { - - // 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 *VolumeUsageData `json:"UsageData,omitempty"` -} - -// VolumeUsageData Usage details about the volume. This information is used by the -// `GET /system/df` endpoint, and omitted in other endpoints. -// -// swagger:model VolumeUsageData -type VolumeUsageData 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_create.go b/vendor/github.com/docker/docker/api/types/volume/volume_create.go deleted file mode 100644 index 0c3772d3a..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume_create.go +++ /dev/null @@ -1,29 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -// VolumeCreateBody Volume configuration -// swagger:model VolumeCreateBody -type VolumeCreateBody struct { - - // Name of the volume driver to use. - // Required: true - Driver string `json:"Driver"` - - // A mapping of driver options and values. These options are passed directly to the driver and are driver specific. - // Required: true - DriverOpts map[string]string `json:"DriverOpts"` - - // User-defined key/value metadata. - // Required: true - Labels map[string]string `json:"Labels"` - - // The new volume's name. If not specified, Docker generates a name. - // Required: true - Name string `json:"Name"` -} diff --git a/vendor/github.com/docker/docker/api/types/volume/volume_list.go b/vendor/github.com/docker/docker/api/types/volume/volume_list.go deleted file mode 100644 index 45c3c1c9a..000000000 --- a/vendor/github.com/docker/docker/api/types/volume/volume_list.go +++ /dev/null @@ -1,23 +0,0 @@ -package volume // import "github.com/docker/docker/api/types/volume" - -// ---------------------------------------------------------------------------- -// DO NOT EDIT THIS FILE -// This file was generated by `swagger generate operation` -// -// See hack/generate-swagger-api.sh -// ---------------------------------------------------------------------------- - -import "github.com/docker/docker/api/types" - -// VolumeListOKBody Volume list response -// swagger:model VolumeListOKBody -type VolumeListOKBody struct { - - // List of volumes - // Required: true - Volumes []*types.Volume `json:"Volumes"` - - // Warnings that occurred when fetching the list of volumes - // Required: true - Warnings []string `json:"Warnings"` -} diff --git a/vendor/github.com/docker/docker/builder/dockerignore/dockerignore.go b/vendor/github.com/docker/docker/builder/dockerignore/dockerignore.go deleted file mode 100644 index 57f224afc..000000000 --- a/vendor/github.com/docker/docker/builder/dockerignore/dockerignore.go +++ /dev/null @@ -1,64 +0,0 @@ -package dockerignore // import "github.com/docker/docker/builder/dockerignore" - -import ( - "bufio" - "bytes" - "fmt" - "io" - "path/filepath" - "strings" -) - -// ReadAll reads a .dockerignore file and returns the list of file patterns -// to ignore. Note this will trim whitespace from each line as well -// as use GO's "clean" func to get the shortest/cleanest path for each. -func ReadAll(reader io.Reader) ([]string, error) { - if reader == nil { - return nil, nil - } - - scanner := bufio.NewScanner(reader) - var excludes []string - currentLine := 0 - - utf8bom := []byte{0xEF, 0xBB, 0xBF} - for scanner.Scan() { - scannedBytes := scanner.Bytes() - // We trim UTF8 BOM - if currentLine == 0 { - scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom) - } - pattern := string(scannedBytes) - currentLine++ - // Lines starting with # (comments) are ignored before processing - if strings.HasPrefix(pattern, "#") { - continue - } - pattern = strings.TrimSpace(pattern) - if pattern == "" { - continue - } - // normalize absolute paths to paths relative to the context - // (taking care of '!' prefix) - invert := pattern[0] == '!' - if invert { - pattern = strings.TrimSpace(pattern[1:]) - } - if len(pattern) > 0 { - pattern = filepath.Clean(pattern) - pattern = filepath.ToSlash(pattern) - if len(pattern) > 1 && pattern[0] == '/' { - pattern = pattern[1:] - } - } - if invert { - pattern = "!" + pattern - } - - excludes = append(excludes, pattern) - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("Error reading .dockerignore: %v", err) - } - return excludes, nil -} 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 6213963db..000000000 --- a/vendor/github.com/docker/docker/builder/remotecontext/git/gitutils.go +++ /dev/null @@ -1,209 +0,0 @@ -package git // import "github.com/docker/docker/builder/remotecontext/git" - -import ( - "io/ioutil" - "net/http" - "net/url" - "os" - "os/exec" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/symlink" - "github.com/docker/docker/pkg/urlutil" - "github.com/pkg/errors" -) - -type gitRepo struct { - remote string - ref string - subdir string -} - -// Clone clones a repository into a newly created directory which -// will be under "docker-build-git" -func Clone(remoteURL string) (string, error) { - repo, err := parseRemoteURL(remoteURL) - - if err != nil { - return "", err - } - - return cloneGitRepo(repo) -} - -func cloneGitRepo(repo gitRepo) (checkoutDir string, err error) { - fetch := fetchArgs(repo.remote, repo.ref) - - root, err := ioutil.TempDir("", "docker-build-git") - if err != nil { - return "", err - } - - defer func() { - if err != nil { - os.RemoveAll(root) - } - }() - - if out, err := 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 := 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 := gitWithinDir(root, fetch...); err != nil { - return "", errors.Wrapf(err, "error fetching: %s", output) - } - - checkoutDir, err = checkoutGit(root, repo.ref, repo.subdir) - 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 - } - - var fragment string - if strings.HasPrefix(remoteURL, "git@") { - // git@.. is not an URL, so cannot be parsed as URL - parts := strings.SplitN(remoteURL, "#", 2) - - repo.remote = parts[0] - if len(parts) == 2 { - fragment = parts[1] - } - 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) { - refAndDir := strings.SplitN(fragment, ":", 2) - ref = "master" - if len(refAndDir[0]) != 0 { - ref = refAndDir[0] - } - if len(refAndDir) > 1 && len(refAndDir[1]) != 0 { - subdir = refAndDir[1] - } - return -} - -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 urlutil.IsURL(remoteURL) { - // 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) - if err != nil || res.StatusCode != http.StatusOK { - res, err = http.Get(serviceURL) - 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 checkoutGit(root, ref, subdir 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 := gitWithinDir(root, "checkout", ref); err != nil { - // If checking out by branch name fails check out the last fetched ref - if _, err2 := gitWithinDir(root, "checkout", "FETCH_HEAD"); err2 != nil { - return "", errors.Wrapf(err, "error checking out %s: %s", ref, output) - } - } - - if subdir != "" { - newCtx, err := symlink.FollowSymlinkInScope(filepath.Join(root, subdir), root) - if err != nil { - return "", errors.Wrapf(err, "error setting git context, %q not within git root", 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 gitWithinDir(dir string, args ...string) ([]byte, error) { - a := []string{"--work-tree", dir, "--git-dir", filepath.Join(dir, ".git")} - return git(append(a, args...)...) -} - -func git(args ...string) ([]byte, error) { - return exec.Command("git", args...).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 { - return urlutil.IsURL(str) || strings.HasPrefix(str, "git://") || strings.HasPrefix(str, "git@") -} 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 3aae43e3d..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 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 397d67cdc..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" - "fmt" - "net/url" - - "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", fmt.Sprintf("%d", opts.KeepStorage)) - filters, err := filters.ToJSON(opts.Filters) - if err != nil { - return nil, errors.Wrap(err, "prune could not marshal filters option") - } - query.Set("filters", filters) - - 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, fmt.Errorf("Error retrieving disk usage: %v", err) - } - - 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 66d46dd16..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, wrapResponseError(err, resp, "container", container) - } - - 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 b63d4d6d4..000000000 --- a/vendor/github.com/docker/docker/client/client.go +++ /dev/null @@ -1,309 +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/reference/api/ - -Usage - -You use the library by creating a client object and calling methods on it. The -client can be created either from environment variables with NewEnvClient, or -configured manually with NewClient. - -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" - "fmt" - "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" -) - -// 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 default values. It takes functors -// to modify values when creating it, like `NewClientWithOpts(WithVersion(…))` -// 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. -func NewClientWithOpts(ops ...Opt) (*Client, error) { - client, err := defaultHTTPClient(DefaultDockerHost) - if err != nil { - return nil, err - } - c := &Client{ - host: DefaultDockerHost, - version: api.DefaultVersion, - client: client, - proto: defaultProto, - addr: defaultAddr, - } - - for _, op := range ops { - if err := op(c); err != nil { - return nil, err - } - } - - if _, ok := c.client.Transport.(http.RoundTripper); !ok { - return nil, fmt.Errorf("unable to verify TLS configuration, invalid transport %v", c.client.Transport) - } - 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(host string) (*http.Client, error) { - url, err := ParseHostURL(host) - if err != nil { - return nil, err - } - transport := new(http.Transport) - sockets.ConfigureTransport(transport, url.Scheme, url.Host) - 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. Any errors are silently ignored. If a manual override is in place, -// either through the `DOCKER_API_VERSION` environment variable, or if the client -// was initialized with a fixed version (`opts.WithVersion(xx)`), no negotiation -// will be performed. -func (cli *Client) NegotiateAPIVersion(ctx context.Context) { - if !cli.manualOverride { - ping, _ := cli.Ping(ctx) - cli.negotiateAPIVersionPing(ping) - } -} - -// NegotiateAPIVersionPing updates the client version to match the Ping.APIVersion -// if the ping version is less than the default version. If a manual override is -// in place, either through the `DOCKER_API_VERSION` environment variable, or if -// the client was initialized with a fixed version (`opts.WithVersion(xx)`), no -// negotiation is performed. -func (cli *Client) NegotiateAPIVersionPing(p types.Ping) { - if !cli.manualOverride { - cli.negotiateAPIVersionPing(p) - } -} - -// negotiateAPIVersionPing queries the API and updates the version to match the -// API version. Any errors are silently ignored. -func (cli *Client) negotiateAPIVersionPing(p types.Ping) { - // try the latest version before versioning headers existed - if p.APIVersion == "" { - p.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(p.APIVersion, cli.version) { - cli.version = p.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 { - return &*cli.client -} - -// ParseHostURL parses a url string, validates the string is a host url, and -// returns the parsed URL -func ParseHostURL(host string) (*url.URL, error) { - protoAddrParts := strings.SplitN(host, "://", 2) - if len(protoAddrParts) == 1 { - return nil, fmt.Errorf("unable to parse docker host `%s`", host) - } - - var basePath string - proto, addr := protoAddrParts[0], protoAddrParts[1] - 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 -} - -// CustomHTTPHeaders returns the custom http headers stored by the client. -func (cli *Client) CustomHTTPHeaders() map[string]string { - m := make(map[string]string) - for k, v := range cli.customHTTPHeaders { - m[k] = v - } - return m -} - -// SetCustomHTTPHeaders that will be set on every HTTP request made by the client. -// Deprecated: use WithHTTPHeaders when creating the client. -func (cli *Client) SetCustomHTTPHeaders(headers map[string]string) { - cli.customHTTPHeaders = headers -} - -// Dialer returns a dialer for a raw stream connection, with 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 54cdfc29a..000000000 --- a/vendor/github.com/docker/docker/client/client_deprecated.go +++ /dev/null @@ -1,23 +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 -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(FromEnv) -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 3d24470ba..000000000 --- a/vendor/github.com/docker/docker/client/client_unix.go +++ /dev/null @@ -1,9 +0,0 @@ -// +build linux freebsd openbsd darwin - -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "unix:///var/run/docker.sock" - -const defaultProto = "unix" -const defaultAddr = "/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 c649e5441..000000000 --- a/vendor/github.com/docker/docker/client/client_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package client // import "github.com/docker/docker/client" - -// DefaultDockerHost defines os specific default if DOCKER_HOST is unset -const DefaultDockerHost = "npipe:////./pipe/docker_engine" - -const defaultProto = "npipe" -const defaultAddr = "//./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 ee7d411df..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 7d0ce3e11..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/ioutil" - - "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, wrapResponseError(err, resp, "config", id) - } - - body, err := ioutil.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 a708fcaec..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 wrapResponseError(err, resp, "config", id) -} 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 39e59cf85..000000000 --- a/vendor/github.com/docker/docker/client/config_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" -) - -// 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", strconv.FormatUint(version.Index, 10)) - 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 88ba1ef63..000000000 --- a/vendor/github.com/docker/docker/client/container_attach.go +++ /dev/null @@ -1,57 +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 2966e88c8..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 into 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 bb278bf7f..000000000 --- a/vendor/github.com/docker/docker/client/container_copy.go +++ /dev/null @@ -1,103 +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{}, wrapResponseError(err, response, "container:path", containerID+":"+path) - } - 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 wrapResponseError(err, response, "container:path", containerID+":"+dstPath) - } - - // TODO this code converts non-error status-codes (e.g., "204 No Content") into an error; verify if this is the desired behavior - if response.statusCode != http.StatusOK { - return fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - 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{}, wrapResponseError(err, response, "container:path", containerID+":"+srcPath) - } - - // TODO this code converts non-error status-codes (e.g., "204 No Content") into an error; verify if this is the desired behavior - if response.statusCode != http.StatusOK { - return nil, types.ContainerPathStat{}, fmt.Errorf("unexpected status code from daemon: %d", response.statusCode) - } - - // 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 5b795e0c1..000000000 --- a/vendor/github.com/docker/docker/client/container_create.go +++ /dev/null @@ -1,52 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/versions" -) - -type configWrapper struct { - *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig -} - -// ContainerCreate creates a new container based in 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, containerName string) (container.ContainerCreateCreatedBody, error) { - var response container.ContainerCreateCreatedBody - - if err := cli.NewVersionError("1.25", "stop timeout"); config != nil && config.StopTimeout != nil && err != nil { - return response, err - } - - // When using API 1.24 and under, the client is responsible for removing the container - if hostConfig != nil && versions.LessThan(cli.ClientVersion(), "1.25") { - hostConfig.AutoRemove = false - } - - query := url.Values{} - 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 -} 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 29dac8491..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.ContainerChangeResponseItem, error) { - var changes []container.ContainerChangeResponseItem - - 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 e3ee755b7..000000000 --- a/vendor/github.com/docker/docker/client/container_exec.go +++ /dev/null @@ -1,54 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - - "github.com/docker/docker/api/types" -) - -// 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 - } - - 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 { - 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) { - 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 c496bcffe..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/ioutil" - "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{}, wrapResponseError(err, serverResp, "container", containerID) - } - - 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, wrapResponseError(err, serverResp, "container", containerID) - } - - body, err := ioutil.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 4d6f1d23d..000000000 --- a/vendor/github.com/docker/docker/client/container_kill.go +++ /dev/null @@ -1,16 +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{} - 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 1e7a63a9c..000000000 --- a/vendor/github.com/docker/docker/client/container_list.go +++ /dev/null @@ -1,56 +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 != -1 { - 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 { - 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 5b6541f03..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, wrapResponseError(err, resp, "container", container) - } - 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 df81461b8..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 wrapResponseError(err, resp, "container", containerID) -} 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 41e421969..000000000 --- a/vendor/github.com/docker/docker/client/container_restart.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" -) - -// ContainerRestart stops and starts a container again. -// It makes the daemon to 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, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - 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 6ef44c774..000000000 --- a/vendor/github.com/docker/docker/client/container_stats.go +++ /dev/null @@ -1,26 +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 -} 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 629d7ab64..000000000 --- a/vendor/github.com/docker/docker/client/container_stop.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "time" - - timetypes "github.com/docker/docker/api/types/time" -) - -// 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, timeout *time.Duration) error { - query := url.Values{} - if timeout != nil { - query.Set("t", timetypes.DurationToSecondsString(*timeout)) - } - 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 6917cf9fb..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 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 6ab8c1da9..000000000 --- a/vendor/github.com/docker/docker/client/container_wait.go +++ /dev/null @@ -1,83 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "net/url" - - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/versions" -) - -// 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.ContainerWaitOKBody, <-chan error) { - if versions.LessThan(cli.ClientVersion(), "1.30") { - return cli.legacyContainerWait(ctx, containerID) - } - - resultC := make(chan container.ContainerWaitOKBody) - errC := make(chan error, 1) - - query := url.Values{} - 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) - var res container.ContainerWaitOKBody - if err := json.NewDecoder(resp.body).Decode(&res); err != nil { - 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.ContainerWaitOKBody, <-chan error) { - resultC := make(chan container.ContainerWaitOKBody) - 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.ContainerWaitOKBody - 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 354cd3693..000000000 --- a/vendor/github.com/docker/docker/client/disk_usage.go +++ /dev/null @@ -1,26 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - - "github.com/docker/docker/api/types" -) - -// DiskUsage requests the current data usage from the daemon -func (cli *Client) DiskUsage(ctx context.Context) (types.DiskUsage, error) { - var du types.DiskUsage - - serverResp, err := cli.get(ctx, "/system/df", nil, nil) - defer ensureReaderClosed(serverResp) - if err != nil { - return du, err - } - - if err := json.NewDecoder(serverResp.body).Decode(&du); err != nil { - return du, 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 f4e3794cb..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" - - registrytypes "github.com/docker/docker/api/types/registry" -) - -// DistributionInspect returns the image digest with full Manifest -func (cli *Client) DistributionInspect(ctx context.Context, image, encodedRegistryAuth string) (registrytypes.DistributionInspect, error) { - // Contact the registry to retrieve digest and platform information - var distributionInspect registrytypes.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{ - "X-Registry-Auth": {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/errors.go b/vendor/github.com/docker/docker/client/errors.go deleted file mode 100644 index 001c10288..000000000 --- a/vendor/github.com/docker/docker/client/errors.go +++ /dev/null @@ -1,138 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "fmt" - "net/http" - - "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 { - _, ok := errors.Cause(err).(errConnectionFailed) - return ok -} - -// 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 _, ok := err.(notFound); ok { - return ok - } - return errdefs.IsNotFound(err) -} - -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) -} - -func wrapResponseError(err error, resp serverResponse, object, id string) error { - switch { - case err == nil: - return nil - case resp.statusCode == http.StatusNotFound: - return objectNotFoundError{object: object, id: id} - case resp.statusCode == http.StatusNotImplemented: - return errdefs.NotImplemented(err) - default: - return err - } -} - -// unauthorizedError represents an authorization error in a remote registry. -type unauthorizedError struct { - cause error -} - -// Error returns a string representation of an unauthorizedError -func (u unauthorizedError) Error() string { - return u.cause.Error() -} - -// IsErrUnauthorized returns true if the error is caused -// when a remote registry authentication fails -func IsErrUnauthorized(err error) bool { - if _, ok := err.(unauthorizedError); ok { - return ok - } - return errdefs.IsUnauthorized(err) -} - -type pluginPermissionDenied struct { - name string -} - -func (e pluginPermissionDenied) Error() string { - return "Permission denied while installing plugin " + e.name -} - -// IsErrPluginPermissionDenied returns true if the error is caused -// when a user denies a plugin's permissions -func IsErrPluginPermissionDenied(err error) bool { - _, ok := err.(pluginPermissionDenied) - return ok -} - -type notImplementedError struct { - message string -} - -func (e notImplementedError) Error() string { - return e.message -} - -func (e notImplementedError) NotImplemented() bool { - return true -} - -// IsErrNotImplemented returns true if the error is a NotImplemented error. -// This is returned by the API when a requested feature has not been -// implemented. -func IsErrNotImplemented(err error) bool { - if _, ok := err.(notImplementedError); ok { - return ok - } - return errdefs.IsNotImplemented(err) -} - -// 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 6e5653895..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 { - 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 e9c9a752f..000000000 --- a/vendor/github.com/docker/docker/client/hijack.go +++ /dev/null @@ -1,143 +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/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 - } - - apiPath := cli.getAPIPath(ctx, path, query) - req, err := http.NewRequest("POST", apiPath, bodyEncoded) - if err != nil { - return types.HijackedResponse{}, err - } - req = cli.addHeaders(req, headers) - - conn, err := cli.setupHijackConn(ctx, req, "tcp") - if err != nil { - return types.HijackedResponse{}, err - } - - return types.HijackedResponse{Conn: conn, Reader: bufio.NewReader(conn)}, 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("POST", url, nil) - if err != nil { - return nil, err - } - req = cli.addHeaders(req, meta) - - return cli.setupHijackConn(ctx, req, proto) -} - -// 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, error) { - req.Host = cli.addr - 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) - 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 iff 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) - } - - return c, 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 8fcf99503..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 request to the daemon to build images. -// The Body in the response implement 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 239380474..000000000 --- a/vendor/github.com/docker/docker/client/image_create.go +++ /dev/null @@ -1,37 +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" -) - -// ImageCreate creates a new image based in 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{"X-Registry-Auth": {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 c2972ea95..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 in 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 1eb8dce02..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/ioutil" - - "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, wrapResponseError(err, serverResp, "image", imageID) - } - - body, err := ioutil.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 4fa8c006b..000000000 --- a/vendor/github.com/docker/docker/client/image_list.go +++ /dev/null @@ -1,45 +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 { - filterJSON, err := filters.ToParamWithVersion(cli.version, optionFilters) - if err != nil { - return images, err - } - query.Set("filters", filterJSON) - } - if options.All { - query.Set("all", "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 49d412ee3..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/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") - } - - tag := "" - name := reference.FamiliarName(ref) - - if nameTaggedRef, isNamedTagged := ref.(reference.NamedTagged); isNamedTagged { - tag = nameTaggedRef.Tag() - } - - query := url.Values{} - query.Set("tag", 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{"X-Registry-Auth": {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 84a41af0f..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, wrapResponseError(err, resp, "image", imageID) - } - - 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 82955a747..000000000 --- a/vendor/github.com/docker/docker/client/image_search.go +++ /dev/null @@ -1,51 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "encoding/json" - "fmt" - "net/url" - - "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 to 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) - query.Set("limit", fmt.Sprintf("%d", 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{"X-Registry-Auth": {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 cde64be4b..000000000 --- a/vendor/github.com/docker/docker/client/interface.go +++ /dev/null @@ -1,199 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" - "net" - "net/http" - "time" - - "github.com/docker/docker/api/types" - containertypes "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" - networktypes "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/api/types/swarm" - volumetypes "github.com/docker/docker/api/types/volume" -) - -// 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 *containertypes.Config, hostConfig *containertypes.HostConfig, networkingConfig *networktypes.NetworkingConfig, containerName string) (containertypes.ContainerCreateCreatedBody, error) - ContainerDiff(ctx context.Context, container string) ([]containertypes.ContainerChangeResponseItem, 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, timeout *time.Duration) error - ContainerStatPath(ctx context.Context, container, path string) (types.ContainerPathStat, error) - ContainerStats(ctx context.Context, container string, stream bool) (types.ContainerStats, error) - ContainerStart(ctx context.Context, container string, options types.ContainerStartOptions) error - ContainerStop(ctx context.Context, container string, timeout *time.Duration) error - ContainerTop(ctx context.Context, container string, arguments []string) (containertypes.ContainerTopOKBody, error) - ContainerUnpause(ctx context.Context, container string) error - ContainerUpdate(ctx context.Context, container string, updateConfig containertypes.UpdateConfig) (containertypes.ContainerUpdateOKBody, error) - ContainerWait(ctx context.Context, container string, condition containertypes.WaitCondition) (<-chan containertypes.ContainerWaitOKBody, <-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 *networktypes.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 types.AuthConfig) (registry.AuthenticateOKBody, error) - DiskUsage(ctx context.Context) (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 volumetypes.VolumeCreateBody) (types.Volume, error) - VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) - VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) - VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumeListOKBody, error) - VolumeRemove(ctx context.Context, volumeID string, force bool) error - VolumesPrune(ctx context.Context, pruneFilter filters.Args) (types.VolumesPruneReport, 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 f05852063..000000000 --- a/vendor/github.com/docker/docker/client/login.go +++ /dev/null @@ -1,25 +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" -) - -// 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 types.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 89a05b302..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/ioutil" - "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, wrapResponseError(err, resp, "network", networkID) - } - - body, err := ioutil.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 7130c1364..000000000 --- a/vendor/github.com/docker/docker/client/network_list.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" - "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 { - 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 e71b16d86..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 wrapResponseError(err, resp, "network", networkID) -} 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 d296c9fdd..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/ioutil" - - "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, wrapResponseError(err, serverResp, "node", nodeID) - } - - body, err := ioutil.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 03ab87809..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 wrapResponseError(err, resp, "node", nodeID) -} 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 de32a617f..000000000 --- a/vendor/github.com/docker/docker/client/node_update.go +++ /dev/null @@ -1,18 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/url" - "strconv" - - "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", strconv.FormatUint(version.Index, 10)) - 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 6f77f0955..000000000 --- a/vendor/github.com/docker/docker/client/options.go +++ /dev/null @@ -1,172 +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. -// -// Supported environment variables: -// DOCKER_HOST to set the url to the docker server. -// DOCKER_API_VERSION to set the version of the API to reach, leave empty for latest. -// DOCKER_CERT_PATH to load the TLS certificates from. -// DOCKER_TLS_VERIFY to enable or disable TLS verification, off by default. -func FromEnv(c *Client) error { - if dockerCertPath := os.Getenv("DOCKER_CERT_PATH"); dockerCertPath != "" { - options := tlsconfig.Options{ - CAFile: filepath.Join(dockerCertPath, "ca.pem"), - CertFile: filepath.Join(dockerCertPath, "cert.pem"), - KeyFile: filepath.Join(dockerCertPath, "key.pem"), - InsecureSkipVerify: os.Getenv("DOCKER_TLS_VERIFY") == "", - } - tlsc, err := tlsconfig.Client(options) - if err != nil { - return err - } - - c.client = &http.Client{ - Transport: &http.Transport{TLSClientConfig: tlsc}, - CheckRedirect: CheckRedirect, - } - } - - if host := os.Getenv("DOCKER_HOST"); host != "" { - if err := WithHost(host)(c); err != nil { - return err - } - } - - if version := os.Getenv("DOCKER_API_VERSION"); version != "" { - if err := WithVersion(version)(c); err != nil { - return err - } - } - return nil -} - -// WithDialer applies the dialer.DialContext to the client transport. This can be -// used to set the Timeout and KeepAlive settings of the client. -// Deprecated: use WithDialContext -func WithDialer(dialer *net.Dialer) Opt { - return WithDialContext(dialer.DialContext) -} - -// 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) - } -} - -// 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) - } -} - -// 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 - } -} - -// 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 90f39ec14..000000000 --- a/vendor/github.com/docker/docker/client/ping.go +++ /dev/null @@ -1,66 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "net/http" - "path" - - "github.com/docker/docker/api/types" - "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("HEAD", 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("GET", 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) - } - 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 81b89732b..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/ioutil" - - "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, wrapResponseError(err, resp, "plugin", name) - } - - body, err := ioutil.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 012afe61c..000000000 --- a/vendor/github.com/docker/docker/client/plugin_install.go +++ /dev/null @@ -1,113 +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/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{"X-Registry-Auth": {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{"X-Registry-Auth": {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, pluginPermissionDenied{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 8285cecd6..000000000 --- a/vendor/github.com/docker/docker/client/plugin_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" -) - -// 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 { - 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, wrapResponseError(err, resp, "plugin", "") - } - - 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 d20bfe844..000000000 --- a/vendor/github.com/docker/docker/client/plugin_push.go +++ /dev/null @@ -1,16 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "io" -) - -// 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{"X-Registry-Auth": {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 51ca1040d..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 wrapResponseError(err, resp, "plugin", name) -} 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 115cea945..000000000 --- a/vendor/github.com/docker/docker/client/plugin_upgrade.go +++ /dev/null @@ -1,39 +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/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{"X-Registry-Auth": {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 3078335e2..000000000 --- a/vendor/github.com/docker/docker/client/request.go +++ /dev/null @@ -1,273 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "bytes" - "context" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "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, "HEAD", 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, "GET", 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, "POST", 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, "POST", path, query, body, headers) -} - -// put sends an http request to the docker API using the method PUT. -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, "PUT", 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, "PUT", 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, "DELETE", 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 == "POST" || method == "PUT") - 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) - - if cli.proto == "unix" || cli.proto == "npipe" { - // For local communications, it doesn't matter what the host is. We just - // need a valid and meaningful host name. (See #189) - req.Host = "docker" - } - - req.URL.Host = cli.addr - req.URL.Scheme = cli.scheme - - 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) - if err != nil { - return resp, errdefs.FromStatusCode(err, resp.statusCode) - } - 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. Please check your TLS client certification settings") - } - - // Don't decorate context sentinel errors; users may be comparing to - // them directly. - switch err { - case context.Canceled, 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, "Got 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 !err.Temporary() { - 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`) { - err = errors.New(err.Error() + " In the default daemon configuration on Windows, the docker client must be run elevated to connect. This error may also 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 = ioutil.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") && k == "User-Agent" { - continue - } - req.Header.Set(k, v) - } - - if headers != nil { - for k, v := range headers { - req.Header[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(ioutil.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 fd5b91413..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 d093916c9..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/ioutil" - - "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, wrapResponseError(err, resp, "secret", id) - } - - body, err := ioutil.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 c16f55580..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 wrapResponseError(err, resp, "secret", id) -} 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 164256bbc..000000000 --- a/vendor/github.com/docker/docker/client/secret_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" -) - -// 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", strconv.FormatUint(version.Index, 10)) - 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 620fc6cff..000000000 --- a/vendor/github.com/docker/docker/client/service_create.go +++ /dev/null @@ -1,166 +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/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 distErr error - - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []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 types.ServiceCreateResponse{}, err - } - - // ensure that the image is tagged - var imgPlatforms []swarm.Platform - if service.TaskTemplate.ContainerSpec != nil { - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - var img string - img, imgPlatforms, distErr = imageDigestAndPlatforms(ctx, cli, service.TaskTemplate.ContainerSpec.Image, options.EncodedRegistryAuth) - if img != "" { - service.TaskTemplate.ContainerSpec.Image = img - } - } - } - - // ensure that the image is tagged - if service.TaskTemplate.PluginSpec != nil { - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - var img string - img, imgPlatforms, distErr = imageDigestAndPlatforms(ctx, cli, service.TaskTemplate.PluginSpec.Remote, options.EncodedRegistryAuth) - if img != "" { - service.TaskTemplate.PluginSpec.Remote = img - } - } - } - - if service.TaskTemplate.Placement == nil && len(imgPlatforms) > 0 { - service.TaskTemplate.Placement = &swarm.Placement{} - } - if len(imgPlatforms) > 0 { - service.TaskTemplate.Placement.Platforms = imgPlatforms - } - - var response types.ServiceCreateResponse - 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 distErr != nil { - response.Warnings = append(response.Warnings, digestWarning(service.TaskTemplate.ContainerSpec.Image)) - } - - return response, err -} - -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 -// an empty string if there are no updates. -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 "" -} - -// 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 2801483b8..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/ioutil" - "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, wrapResponseError(err, serverResp, "service", serviceID) - } - - body, err := ioutil.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 64d35e715..000000000 --- a/vendor/github.com/docker/docker/client/service_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" -) - -// 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) - } - - 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 953a2adf5..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 wrapResponseError(err, resp, "service", serviceID) -} 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 cd0f59e21..000000000 --- a/vendor/github.com/docker/docker/client/service_update.go +++ /dev/null @@ -1,94 +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/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{} - distErr error - ) - - headers := map[string][]string{ - "version": {cli.version}, - } - - if options.EncodedRegistryAuth != "" { - headers["X-Registry-Auth"] = []string{options.EncodedRegistryAuth} - } - - if options.RegistryAuthFrom != "" { - query.Set("registryAuthFrom", options.RegistryAuthFrom) - } - - if options.Rollback != "" { - query.Set("rollback", options.Rollback) - } - - query.Set("version", strconv.FormatUint(version.Index, 10)) - - if err := validateServiceSpec(service); err != nil { - return types.ServiceUpdateResponse{}, err - } - - var imgPlatforms []swarm.Platform - // ensure that the image is tagged - if service.TaskTemplate.ContainerSpec != nil { - if taggedImg := imageWithTagString(service.TaskTemplate.ContainerSpec.Image); taggedImg != "" { - service.TaskTemplate.ContainerSpec.Image = taggedImg - } - if options.QueryRegistry { - var img string - img, imgPlatforms, distErr = imageDigestAndPlatforms(ctx, cli, service.TaskTemplate.ContainerSpec.Image, options.EncodedRegistryAuth) - if img != "" { - service.TaskTemplate.ContainerSpec.Image = img - } - } - } - - // ensure that the image is tagged - if service.TaskTemplate.PluginSpec != nil { - if taggedImg := imageWithTagString(service.TaskTemplate.PluginSpec.Remote); taggedImg != "" { - service.TaskTemplate.PluginSpec.Remote = taggedImg - } - if options.QueryRegistry { - var img string - img, imgPlatforms, distErr = imageDigestAndPlatforms(ctx, cli, service.TaskTemplate.PluginSpec.Remote, options.EncodedRegistryAuth) - if img != "" { - service.TaskTemplate.PluginSpec.Remote = img - } - } - } - - if service.TaskTemplate.Placement == nil && len(imgPlatforms) > 0 { - service.TaskTemplate.Placement = &swarm.Placement{} - } - if len(imgPlatforms) > 0 { - service.TaskTemplate.Placement.Platforms = imgPlatforms - } - - var response types.ServiceUpdateResponse - 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 distErr != nil { - response.Warnings = append(response.Warnings, digestWarning(service.TaskTemplate.ContainerSpec.Image)) - } - - 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 56a5bea76..000000000 --- a/vendor/github.com/docker/docker/client/swarm_update.go +++ /dev/null @@ -1,22 +0,0 @@ -package client // import "github.com/docker/docker/client" - -import ( - "context" - "fmt" - "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", strconv.FormatUint(version.Index, 10)) - query.Set("rotateWorkerToken", fmt.Sprintf("%v", flags.RotateWorkerToken)) - query.Set("rotateManagerToken", fmt.Sprintf("%v", flags.RotateManagerToken)) - query.Set("rotateManagerUnlockKey", fmt.Sprintf("%v", 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 44d40ba5a..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/ioutil" - - "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, wrapResponseError(err, serverResp, "task", taskID) - } - - body, err := ioutil.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 92761b3c6..000000000 --- a/vendor/github.com/docker/docker/client/volume_create.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" - volumetypes "github.com/docker/docker/api/types/volume" -) - -// VolumeCreate creates a volume in the docker host. -func (cli *Client) VolumeCreate(ctx context.Context, options volumetypes.VolumeCreateBody) (types.Volume, error) { - var volume types.Volume - resp, err := cli.post(ctx, "/volumes/create", nil, options, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volume, err - } - err = json.NewDecoder(resp.body).Decode(&volume) - return volume, 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 e20b2c67c..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/ioutil" - - "github.com/docker/docker/api/types" -) - -// VolumeInspect returns the information about a specific volume in the docker host. -func (cli *Client) VolumeInspect(ctx context.Context, volumeID string) (types.Volume, error) { - volume, _, err := cli.VolumeInspectWithRaw(ctx, volumeID) - return volume, 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) (types.Volume, []byte, error) { - if volumeID == "" { - return types.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID} - } - - var volume types.Volume - resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil) - defer ensureReaderClosed(resp) - if err != nil { - return volume, nil, wrapResponseError(err, resp, "volume", volumeID) - } - - body, err := ioutil.ReadAll(resp.body) - if err != nil { - return volume, nil, err - } - rdr := bytes.NewReader(body) - err = json.NewDecoder(rdr).Decode(&volume) - return volume, 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 2380d5638..000000000 --- a/vendor/github.com/docker/docker/client/volume_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/filters" - volumetypes "github.com/docker/docker/api/types/volume" -) - -// VolumeList returns the volumes configured in the docker host. -func (cli *Client) VolumeList(ctx context.Context, filter filters.Args) (volumetypes.VolumeListOKBody, error) { - var volumes volumetypes.VolumeListOKBody - query := url.Values{} - - if filter.Len() > 0 { - filterJSON, err := filters.ToParamWithVersion(cli.version, filter) - 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 79decdafa..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 wrapResponseError(err, resp, "volume", volumeID) -} diff --git a/vendor/github.com/docker/docker/contrib/syntax/vim/LICENSE b/vendor/github.com/docker/docker/contrib/syntax/vim/LICENSE deleted file mode 100644 index e67cdabd2..000000000 --- a/vendor/github.com/docker/docker/contrib/syntax/vim/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 Honza Pokorny -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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/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 c9916e013..000000000 --- a/vendor/github.com/docker/docker/errdefs/helpers.go +++ /dev/null @@ -1,227 +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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 -} - -// 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 ac9bf6d33..000000000 --- a/vendor/github.com/docker/docker/errdefs/http_helpers.go +++ /dev/null @@ -1,172 +0,0 @@ -package errdefs // import "github.com/docker/docker/errdefs" - -import ( - "fmt" - "net/http" - - "github.com/docker/distribution/registry/api/errcode" - "github.com/sirupsen/logrus" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// GetHTTPErrorStatusCode retrieves status code from error message. -func GetHTTPErrorStatusCode(err error) int { - if err == nil { - logrus.WithFields(logrus.Fields{"error": err}).Error("unexpected HTTP error handling") - return http.StatusInternalServerError - } - - var statusCode int - - // Stop right there - // Are you sure you should be adding a new error class here? Do one of the existing ones work? - - // Note that the below functions are already checking the error causal chain for matches. - switch { - case IsNotFound(err): - statusCode = http.StatusNotFound - case IsInvalidParameter(err): - statusCode = http.StatusBadRequest - case IsConflict(err): - statusCode = http.StatusConflict - case IsUnauthorized(err): - statusCode = http.StatusUnauthorized - case IsUnavailable(err): - statusCode = http.StatusServiceUnavailable - case IsForbidden(err): - statusCode = http.StatusForbidden - case IsNotModified(err): - statusCode = http.StatusNotModified - case IsNotImplemented(err): - statusCode = http.StatusNotImplemented - case IsSystem(err) || IsUnknown(err) || IsDataLoss(err) || IsDeadline(err) || IsCancelled(err): - statusCode = http.StatusInternalServerError - default: - statusCode = statusCodeFromGRPCError(err) - if statusCode != http.StatusInternalServerError { - return statusCode - } - statusCode = statusCodeFromDistributionError(err) - if statusCode != http.StatusInternalServerError { - return statusCode - } - if e, ok := err.(causer); ok { - return GetHTTPErrorStatusCode(e.Cause()) - } - - logrus.WithFields(logrus.Fields{ - "module": "api", - "error_type": fmt.Sprintf("%T", err), - }).Debugf("FIXME: Got an API for which error does not match any expected type!!!: %+v", err) - } - - if statusCode == 0 { - statusCode = http.StatusInternalServerError - } - - return statusCode -} - -// FromStatusCode creates an errdef error, based on the provided HTTP status-code -func FromStatusCode(err error, statusCode int) error { - if err == nil { - return err - } - 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: - logrus.WithFields(logrus.Fields{ - "module": "api", - "status_code": fmt.Sprintf("%d", statusCode), - }).Debugf("FIXME: Got an status-code for which error does not match any expected type!!!: %d", statusCode) - - 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 -} - -// statusCodeFromGRPCError returns status code according to gRPC error -func statusCodeFromGRPCError(err error) int { - switch status.Code(err) { - case codes.InvalidArgument: // code 3 - return http.StatusBadRequest - case codes.NotFound: // code 5 - return http.StatusNotFound - case codes.AlreadyExists: // code 6 - return http.StatusConflict - case codes.PermissionDenied: // code 7 - return http.StatusForbidden - case codes.FailedPrecondition: // code 9 - return http.StatusBadRequest - case codes.Unauthenticated: // code 16 - return http.StatusUnauthorized - case codes.OutOfRange: // code 11 - return http.StatusBadRequest - case codes.Unimplemented: // code 12 - return http.StatusNotImplemented - case codes.Unavailable: // code 14 - return http.StatusServiceUnavailable - default: - if e, ok := err.(causer); ok { - return statusCodeFromGRPCError(e.Cause()) - } - // codes.Canceled(1) - // codes.Unknown(2) - // codes.DeadlineExceeded(4) - // codes.ResourceExhausted(8) - // codes.Aborted(10) - // codes.Internal(13) - // codes.DataLoss(15) - return http.StatusInternalServerError - } -} - -// statusCodeFromDistributionError returns status code according to registry errcode -// code is loosely based on errcode.ServeJSON() in docker/distribution -func statusCodeFromDistributionError(err error) int { - switch errs := err.(type) { - case errcode.Errors: - if len(errs) < 1 { - return http.StatusInternalServerError - } - if _, ok := errs[0].(errcode.ErrorCoder); ok { - return statusCodeFromDistributionError(errs[0]) - } - case errcode.ErrorCoder: - return errs.ErrorCode().Descriptor().HTTPStatusCode - default: - if e, ok := err.(causer); ok { - return statusCodeFromDistributionError(e.Cause()) - } - } - return http.StatusInternalServerError -} 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 bb623fa85..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive.go +++ /dev/null @@ -1,1284 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bufio" - "bytes" - "compress/bzip2" - "compress/gzip" - "context" - "fmt" - "io" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strconv" - "strings" - "syscall" - "time" - - "github.com/docker/docker/pkg/fileutils" - "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/sirupsen/logrus" -) - -var unpigzPath string - -func init() { - if path, err := exec.LookPath("unpigz"); err != nil { - logrus.Debug("unpigz binary not found in PATH, falling back to go gzip library") - } else { - logrus.Debugf("Using unpigz binary found at path %s", path) - unpigzPath = path - } -} - -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 - UIDMaps []idtools.IDMap - GIDMaps []idtools.IDMap - 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, IDMapping: &idtools.IdentityMapping{}} -} - -// 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 -) - -const ( - // AUFSWhiteoutFormat is the default format for whiteouts - AUFSWhiteoutFormat WhiteoutFormat = iota - // OverlayWhiteoutFormat formats whiteout according to the overlay - // standard. - OverlayWhiteoutFormat -) - -const ( - modeISDIR = 040000 // Directory - modeISFIFO = 010000 // FIFO - modeISREG = 0100000 // Regular file - modeISLNK = 0120000 // Symbolic link - modeISBLK = 060000 // Block special file - modeISCHR = 020000 // Character special file - modeISSOCK = 0140000 // Socket -) - -// 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 -} - -// DetectCompression detects the compression algorithm of the source. -func DetectCompression(source []byte) Compression { - for compression, m := range map[Compression][]byte{ - Bzip2: {0x42, 0x5A, 0x68}, - Gzip: {0x1F, 0x8B, 0x08}, - Xz: {0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00}, - } { - if len(source) < len(m) { - logrus.Debug("Len too short") - continue - } - if bytes.Equal(m, source[:len(m)]) { - 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 unpigzPath == "" { - return gzip.NewReader(buf) - } - - disablePigzEnv := os.Getenv("MOBY_DISABLE_PIGZ") - if disablePigzEnv != "" { - if disablePigz, err := strconv.ParseBool(disablePigzEnv); err != nil { - return nil, err - } else if disablePigz { - return gzip.NewReader(buf) - } - } - - 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 - 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 - } - - 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" - } - return "" -} - -// FileInfoHeader creates a populated Header from fi. -// Compared to archive pkg this function fills in more information. -// Also, regardless of Go version, this function fills file type bits (e.g. hdr.Mode |= modeISDIR), -// which have been deleted since Go 1.9 archive/tar. -func FileInfoHeader(name string, fi os.FileInfo, link string) (*tar.Header, error) { - hdr, err := tar.FileInfoHeader(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 = fillGo18FileTypeBits(int64(chmodTarEntry(os.FileMode(hdr.Mode))), fi) - hdr.Name = canonicalTarName(name, fi.IsDir()) - if err := setHeaderForSpecialDevice(hdr, name, fi.Sys()); err != nil { - return nil, err - } - return hdr, nil -} - -// fillGo18FileTypeBits fills type bits which have been removed on Go 1.9 archive/tar -// https://github.com/golang/go/commit/66b5a2f -func fillGo18FileTypeBits(mode int64, fi os.FileInfo) int64 { - fm := fi.Mode() - switch { - case fm.IsRegular(): - mode |= modeISREG - case fi.IsDir(): - mode |= modeISDIR - case fm&os.ModeSymlink != 0: - mode |= modeISLNK - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { - mode |= modeISCHR - } else { - mode |= modeISBLK - } - case fm&os.ModeNamedPipe != 0: - mode |= modeISFIFO - case fm&os.ModeSocket != 0: - mode |= modeISSOCK - } - return mode -} - -// ReadSecurityXattrToTarHeader reads security.capability xattr from filesystem -// to a tar header -func ReadSecurityXattrToTarHeader(path string, hdr *tar.Header) error { - capability, _ := system.Lgetxattr(path, "security.capability") - if capability != nil { - hdr.Xattrs = make(map[string]string) - hdr.Xattrs["security.capability"] = string(capability) - } - 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, - } -} - -// 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 = CanonicalTarNameForPath(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 system.OpenSequential to ensure we use sequential file - // access on Windows to avoid depleting the standby list. - // On Linux, this equates to a regular os.Open. - file, err := system.OpenSequential(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, tar.TypeRegA: - // Source is regular file. We use system.OpenFileSequential to use sequential - // file access to avoid depleting the standby list on Windows. - // On Linux, this equates to a regular os.OpenFile - file, err := system.OpenFileSequential(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: - 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) - - // 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 { - return err - } - } - - 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) { - - // Fix the source path to work with long path names. This is a no-op - // on platforms other than Windows. - srcPath = fixVolumePathPrefix(srcPath) - - pm, err := fileutils.NewPatternMatcher(options.ExcludePatterns) - if err != nil { - return nil, err - } - - pipeReader, pipeWriter := io.Pipe() - - compressWriter, err := CompressStream(pipeWriter, options.Compression) - if err != nil { - return nil, err - } - - go func() { - ta := newTarAppender( - idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps), - compressWriter, - options.ChownOpts, - ) - ta.WhiteoutConverter = getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - - 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 := compressWriter.Close(); err != nil { - logrus.Errorf("Can't close compress writer: %s", err) - } - if err := 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(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(options.IncludeFiles) > 0 { - logrus.Warn("Tar: Can't archive a file with includes") - } - - dir, base := SplitPathDirEntry(srcPath) - srcPath = dir - options.IncludeFiles = []string{base} - } - - if len(options.IncludeFiles) == 0 { - options.IncludeFiles = []string{"."} - } - - seen := make(map[string]bool) - - for _, include := range options.IncludeFiles { - rebaseName := options.RebaseNames[include] - - walkRoot := getWalkRoot(srcPath, include) - filepath.Walk(walkRoot, func(filePath string, f os.FileInfo, err error) error { - if err != nil { - logrus.Errorf("Tar: Can't stat file %s to tar: %s", srcPath, err) - return nil - } - - relFilePath, err := filepath.Rel(srcPath, filePath) - if err != nil || (!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 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 { - skip, err = pm.Matches(relFilePath) - if err != nil { - logrus.Errorf("Error matching %s: %v", relFilePath, err) - return err - } - } - - 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 !pm.Exclusions() { - return filepath.SkipDir - } - - dirSlash := relFilePath + string(filepath.Separator) - - for _, pat := range 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 - }) - } - }() - - return pipeReader, 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 - idMapping := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) - rootIDs := idMapping.RootPair() - whiteoutConverter := getWhiteoutConverter(options.WhiteoutFormat, options.InUserNS) - - // 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 - } - - // 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 - } - } - - // After calling filepath.Clean(hdr.Name) above, hdr.Name will now be in - // the filepath format for the OS on which the daemon is running. Hence - // the check for a slash-suffix MUST be done in an OS-agnostic way. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = idtools.MkdirAllAndChownNew(parentPath, 0777, rootIDs) - if err != nil { - return err - } - } - } - - 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(idMapping, 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 { - path := filepath.Join(dest, hdr.Name) - - if err := system.Chtimes(path, hdr.AccessTime, hdr.ModTime); 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 { - logrus.Debugf("TarUntar(%s %s)", src, dst) - archive, err := TarWithOptions(src, &TarOptions{Compression: Uncompressed}) - if err != nil { - return err - } - defer archive.Close() - options := &TarOptions{ - UIDMaps: archiver.IDMapping.UIDs(), - GIDMaps: archiver.IDMapping.GIDs(), - } - 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{ - UIDMaps: archiver.IDMapping.UIDs(), - GIDMaps: archiver.IDMapping.GIDs(), - } - 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 - logrus.Debugf("Creating dest directory: %s", dst) - if err := idtools.MkdirAllAndChownNew(dst, 0755, rootIDs); err != nil { - return err - } - logrus.Debugf("Calling TarUntar(%s, %s)", src, dst) - 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) { - logrus.Debugf("CopyFileWithTar(%s, %s)", src, dst) - 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 := tar.FileInfoHeader(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 - } - - // 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() - } - }() - - return pipeR, 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 := ioutil.TempFile(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 0601f7b0d..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_linux.go +++ /dev/null @@ -1,261 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "fmt" - "io/ioutil" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/containerd/continuity/fs" - "github.com/docker/docker/pkg/system" - "github.com/pkg/errors" - "golang.org/x/sys/unix" -) - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) tarWhiteoutConverter { - if format == OverlayWhiteoutFormat { - return overlayWhiteoutConverter{inUserNS: inUserNS} - } - return nil -} - -type overlayWhiteoutConverter struct { - inUserNS bool -} - -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, - } - } - } - - 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 { - if c.inUserNS { - if err = replaceDirWithOverlayOpaque(dir); err != nil { - return false, errors.Wrapf(err, "replaceDirWithOverlayOpaque(%q) failed", dir) - } - } else { - 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 { - if c.inUserNS { - // Ubuntu and a few distros support overlayfs in userns. - // - // Although we can't call mknod directly in userns (at least on bionic kernel 4.15), - // we can still create 0,0 char device using mknodChar0Overlay(). - // - // NOTE: we don't need this hack for the containerd snapshotter+unpack model. - if err := mknodChar0Overlay(originalPath); err != nil { - return false, errors.Wrapf(err, "failed to mknodChar0UserNS(%q)", originalPath) - } - } else { - 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 -} - -// mknodChar0Overlay creates 0,0 char device by mounting overlayfs and unlinking. -// This function can be used for creating 0,0 char device in userns on Ubuntu. -// -// Steps: -// * Mkdir lower,upper,merged,work -// * Create lower/dummy -// * Mount overlayfs -// * Unlink merged/dummy -// * Unmount overlayfs -// * Make sure a 0,0 char device is created as upper/dummy -// * Rename upper/dummy to cleansedOriginalPath -func mknodChar0Overlay(cleansedOriginalPath string) error { - dir := filepath.Dir(cleansedOriginalPath) - tmp, err := ioutil.TempDir(dir, "mc0o") - if err != nil { - return errors.Wrapf(err, "failed to create a tmp directory under %s", dir) - } - defer os.RemoveAll(tmp) - lower := filepath.Join(tmp, "l") - upper := filepath.Join(tmp, "u") - work := filepath.Join(tmp, "w") - merged := filepath.Join(tmp, "m") - for _, s := range []string{lower, upper, work, merged} { - if err := os.MkdirAll(s, 0700); err != nil { - return errors.Wrapf(err, "failed to mkdir %s", s) - } - } - dummyBase := "d" - lowerDummy := filepath.Join(lower, dummyBase) - if err := ioutil.WriteFile(lowerDummy, []byte{}, 0600); err != nil { - return errors.Wrapf(err, "failed to create a dummy lower file %s", lowerDummy) - } - mOpts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lower, upper, work) - // docker/pkg/mount.Mount() requires procfs to be mounted. So we use syscall.Mount() directly instead. - if err := syscall.Mount("overlay", merged, "overlay", uintptr(0), mOpts); err != nil { - return errors.Wrapf(err, "failed to mount overlay (%s) on %s", mOpts, merged) - } - mergedDummy := filepath.Join(merged, dummyBase) - if err := os.Remove(mergedDummy); err != nil { - syscall.Unmount(merged, 0) - return errors.Wrapf(err, "failed to unlink %s", mergedDummy) - } - if err := syscall.Unmount(merged, 0); err != nil { - return errors.Wrapf(err, "failed to unmount %s", merged) - } - upperDummy := filepath.Join(upper, dummyBase) - if err := isChar0(upperDummy); err != nil { - return err - } - if err := os.Rename(upperDummy, cleansedOriginalPath); err != nil { - return errors.Wrapf(err, "failed to rename %s to %s", upperDummy, cleansedOriginalPath) - } - return nil -} - -func isChar0(path string) error { - osStat, err := os.Stat(path) - if err != nil { - return errors.Wrapf(err, "failed to stat %s", path) - } - st, ok := osStat.Sys().(*syscall.Stat_t) - if !ok { - return errors.Errorf("got unsupported stat for %s", path) - } - if os.FileMode(st.Mode)&syscall.S_IFMT != syscall.S_IFCHR { - return errors.Errorf("%s is not a character device, got mode=%d", path, st.Mode) - } - if st.Rdev != 0 { - return errors.Errorf("%s is not a 0,0 character device, got Rdev=%d", path, st.Rdev) - } - return nil -} - -// replaceDirWithOverlayOpaque replaces path with a new directory with trusted.overlay.opaque -// xattr. The contents of the directory are preserved. -func replaceDirWithOverlayOpaque(path string) error { - if path == "/" { - return errors.New("replaceDirWithOverlayOpaque: path must not be \"/\"") - } - dir := filepath.Dir(path) - tmp, err := ioutil.TempDir(dir, "rdwoo") - if err != nil { - return errors.Wrapf(err, "failed to create a tmp directory under %s", dir) - } - defer os.RemoveAll(tmp) - // newPath is a new empty directory crafted with trusted.overlay.opaque xattr. - // we copy the content of path into newPath, remove path, and rename newPath to path. - newPath, err := createDirWithOverlayOpaque(tmp) - if err != nil { - return errors.Wrapf(err, "createDirWithOverlayOpaque(%q) failed", tmp) - } - if err := fs.CopyDir(newPath, path); err != nil { - return errors.Wrapf(err, "CopyDir(%q, %q) failed", newPath, path) - } - if err := os.RemoveAll(path); err != nil { - return err - } - return os.Rename(newPath, path) -} - -// createDirWithOverlayOpaque creates a directory with trusted.overlay.opaque xattr, -// without calling setxattr, so as to allow creating opaque dir in userns on Ubuntu. -func createDirWithOverlayOpaque(tmp string) (string, error) { - lower := filepath.Join(tmp, "l") - upper := filepath.Join(tmp, "u") - work := filepath.Join(tmp, "w") - merged := filepath.Join(tmp, "m") - for _, s := range []string{lower, upper, work, merged} { - if err := os.MkdirAll(s, 0700); err != nil { - return "", errors.Wrapf(err, "failed to mkdir %s", s) - } - } - dummyBase := "d" - lowerDummy := filepath.Join(lower, dummyBase) - if err := os.MkdirAll(lowerDummy, 0700); err != nil { - return "", errors.Wrapf(err, "failed to create a dummy lower directory %s", lowerDummy) - } - mOpts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", lower, upper, work) - // docker/pkg/mount.Mount() requires procfs to be mounted. So we use syscall.Mount() directly instead. - if err := syscall.Mount("overlay", merged, "overlay", uintptr(0), mOpts); err != nil { - return "", errors.Wrapf(err, "failed to mount overlay (%s) on %s", mOpts, merged) - } - mergedDummy := filepath.Join(merged, dummyBase) - if err := os.Remove(mergedDummy); err != nil { - syscall.Unmount(merged, 0) - return "", errors.Wrapf(err, "failed to rmdir %s", mergedDummy) - } - // upperDummy becomes a 0,0-char device file here - if err := os.Mkdir(mergedDummy, 0700); err != nil { - syscall.Unmount(merged, 0) - return "", errors.Wrapf(err, "failed to mkdir %s", mergedDummy) - } - // upperDummy becomes a directory with trusted.overlay.opaque xattr - // (but can't be verified in userns) - if err := syscall.Unmount(merged, 0); err != nil { - return "", errors.Wrapf(err, "failed to unmount %s", merged) - } - upperDummy := filepath.Join(upper, dummyBase) - return upperDummy, 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 65a73354c..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_other.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !linux - -package archive // import "github.com/docker/docker/pkg/archive" - -func getWhiteoutConverter(format WhiteoutFormat, inUserNS bool) tarWhiteoutConverter { - return 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 d62633603..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_unix.go +++ /dev/null @@ -1,115 +0,0 @@ -// +build !windows - -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "os" - "path/filepath" - "strings" - "syscall" - - "github.com/docker/docker/pkg/idtools" - "github.com/docker/docker/pkg/system" - rsystem "github.com/opencontainers/runc/libcontainer/system" - "golang.org/x/sys/unix" -) - -// 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 -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return p // already unix-style -} - -// 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 -} - -func setHeaderForSpecialDevice(hdr *tar.Header, name string, stat interface{}) (err error) { - s, ok := stat.(*syscall.Stat_t) - - if ok { - // Currently go does not fill in the major/minors - 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 -} - -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 { - if rsystem.RunningInUserNS() { - // cannot create a device if running in user namespace - return nil - } - - 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 - } - - return system.Mknod(path, mode, int(system.Mkdev(hdr.Devmajor, hdr.Devminor))) -} - -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 ae6b89fd7..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/archive_windows.go +++ /dev/null @@ -1,67 +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) -} - -// CanonicalTarNameForPath returns platform-specific filepath -// to canonical posix-style path for tar archival. p is relative -// path. -func CanonicalTarNameForPath(p string) string { - return filepath.ToSlash(p) -} - -// 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 { - //perm &= 0755 // this 0-ed out tar flags (like link, regular file, directory marker etc.) - permPart := perm & os.ModePerm - noPermPart := perm &^ os.ModePerm - // Add the x bit: make everything +x from windows - permPart |= 0111 - permPart &= 0755 - - return noPermPart | permPart -} - -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 aedb91b03..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes.go +++ /dev/null @@ -1,445 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "io/ioutil" - "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 := ioutil.TempDir("", "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, uidMaps, gidMaps []idtools.IDMap) (io.ReadCloser, error) { - reader, writer := io.Pipe() - go func() { - ta := newTarAppender(idtools.NewIDMappingsFromMaps(uidMaps, gidMaps), 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 ba744741c..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_other.go +++ /dev/null @@ -1,97 +0,0 @@ -// +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.Walk(sourceDir, func(path string, f os.FileInfo, 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 06217b716..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/changes_unix.go +++ /dev/null @@ -1,43 +0,0 @@ -// +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 57fddac07..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy.go +++ /dev/null @@ -1,480 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "errors" - "io" - "io/ioutil" - "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 the separator, then another is not added. -func PreserveTrailingDotOrSeparator(cleanedPath string, originalPath string, sep byte) string { - // Ensure paths are in platform semantics - cleanedPath = strings.Replace(cleanedPath, "/", string(sep), -1) - originalPath = strings.Replace(originalPath, "/", string(sep), -1) - - if !specifiesCurrentDir(cleanedPath) && specifiesCurrentDir(originalPath) { - if !hasTrailingPathSeparator(cleanedPath, sep) { - // 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(sep) - } - cleanedPath += "." - } - - if !hasTrailingPathSeparator(cleanedPath, sep) && hasTrailingPathSeparator(originalPath, sep) { - cleanedPath += string(sep) - } - - 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, sep byte) bool { - return hasTrailingPathSeparator(path, sep) || specifiesCurrentDir(path) -} - -// hasTrailingPathSeparator returns whether the given -// path ends with the system's path separator character. -func hasTrailingPathSeparator(path string, sep byte) bool { - return len(path) > 0 && path[len(path)-1] == sep -} - -// 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, ioutil.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, os.PathSeparator): - // 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 - } - - if _, err = io.Copy(rebasedTar, srcTar); err != nil { - w.CloseWithError(err) - return - } - } - }() - - return rebased -} - -// TODO @gupta-ak. These might have to be changed in the future to be -// continuity driver aware as well to support LCOW. - -// 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, os.PathSeparator) - dstPath = PreserveTrailingDotOrSeparator(filepath.Clean(dstPath), dstPath, os.PathSeparator) - - 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, os.PathSeparator) && - 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, os.PathSeparator) && - !hasTrailingPathSeparator(resolvedPath, os.PathSeparator) { - 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 3958364f5..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/copy_unix.go +++ /dev/null @@ -1,11 +0,0 @@ -// +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 146e21fe1..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/diff.go +++ /dev/null @@ -1,260 +0,0 @@ -package archive // import "github.com/docker/docker/pkg/archive" - -import ( - "archive/tar" - "fmt" - "io" - "io/ioutil" - "os" - "path/filepath" - "runtime" - "strings" - - "github.com/docker/docker/pkg/idtools" - "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{} - } - idMapping := idtools.NewIDMappingsFromMaps(options.UIDMaps, options.GIDMaps) - - 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 - } - } - - // Note as these operations are platform specific, so must the slash be. - if !strings.HasSuffix(hdr.Name, string(os.PathSeparator)) { - // Not the root directory, ensure that the parent directory exists. - // This happened in some tests where an image had a tarfile without any - // parent directories. - parent := filepath.Dir(hdr.Name) - parentPath := filepath.Join(dest, parent) - - if _, err := os.Lstat(parentPath); err != nil && os.IsNotExist(err) { - err = system.MkdirAll(parentPath, 0600, "") - 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 = ioutil.TempDir("", "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 - } - } - 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.Walk(dir, func(path string, info os.FileInfo, 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 { - err := os.RemoveAll(path) - return err - } - 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(idMapping, srcHdr); err != nil { - return 0, err - } - - if err := createTarFile(path, dest, srcHdr, srcData, true, 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 { - 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) -} - -// 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 - if runtime.GOOS != "windows" { - oldmask, err := system.Umask(0) - if err != nil { - return 0, err - } - defer system.Umask(oldmask) - } - - 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/example_changes.go b/vendor/github.com/docker/docker/pkg/archive/example_changes.go deleted file mode 100644 index 495db809e..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/example_changes.go +++ /dev/null @@ -1,97 +0,0 @@ -// +build ignore - -// Simple tool to create an archive stream from an old and new directory -// -// By default it will stream the comparison of two temporary directories with junk files -package main - -import ( - "flag" - "fmt" - "io" - "io/ioutil" - "os" - "path" - - "github.com/docker/docker/pkg/archive" - "github.com/sirupsen/logrus" -) - -var ( - flDebug = flag.Bool("D", false, "debugging output") - flNewDir = flag.String("newdir", "", "") - flOldDir = flag.String("olddir", "", "") - log = logrus.New() -) - -func main() { - flag.Usage = func() { - fmt.Println("Produce a tar from comparing two directory paths. By default a demo tar is created of around 200 files (including hardlinks)") - fmt.Printf("%s [OPTIONS]\n", os.Args[0]) - flag.PrintDefaults() - } - flag.Parse() - log.Out = os.Stderr - if (len(os.Getenv("DEBUG")) > 0) || *flDebug { - logrus.SetLevel(logrus.DebugLevel) - } - var newDir, oldDir string - - if len(*flNewDir) == 0 { - var err error - newDir, err = ioutil.TempDir("", "docker-test-newDir") - if err != nil { - log.Fatal(err) - } - defer os.RemoveAll(newDir) - if _, err := prepareUntarSourceDirectory(100, newDir, true); err != nil { - log.Fatal(err) - } - } else { - newDir = *flNewDir - } - - if len(*flOldDir) == 0 { - oldDir, err := ioutil.TempDir("", "docker-test-oldDir") - if err != nil { - log.Fatal(err) - } - defer os.RemoveAll(oldDir) - } else { - oldDir = *flOldDir - } - - changes, err := archive.ChangesDirs(newDir, oldDir) - if err != nil { - log.Fatal(err) - } - - a, err := archive.ExportChanges(newDir, changes) - if err != nil { - log.Fatal(err) - } - defer a.Close() - - i, err := io.Copy(os.Stdout, a) - if err != nil && err != io.EOF { - log.Fatal(err) - } - fmt.Fprintf(os.Stderr, "wrote archive of %d bytes", i) -} - -func prepareUntarSourceDirectory(numberOfFiles int, targetPath string, makeLinks bool) (int, error) { - fileData := []byte("fooo") - for n := 0; n < numberOfFiles; n++ { - fileName := fmt.Sprintf("file-%d", n) - if err := ioutil.WriteFile(path.Join(targetPath, fileName), fileData, 0700); err != nil { - return 0, err - } - if makeLinks { - if err := os.Link(path.Join(targetPath, fileName), path.Join(targetPath, fileName+"-link")); err != nil { - return 0, err - } - } - } - totalSize := numberOfFiles * len(fileData) - return totalSize, 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 f58bf227f..000000000 --- a/vendor/github.com/docker/docker/pkg/archive/time_unsupported.go +++ /dev/null @@ -1,16 +0,0 @@ -// +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 85435694c..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/fileutils/fileutils.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils.go deleted file mode 100644 index 34f1c726f..000000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils.go +++ /dev/null @@ -1,298 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "errors" - "fmt" - "io" - "os" - "path/filepath" - "regexp" - "strings" - "text/scanner" - - "github.com/sirupsen/logrus" -) - -// PatternMatcher allows checking paths against a list of patterns -type PatternMatcher struct { - patterns []*Pattern - exclusions bool -} - -// NewPatternMatcher creates a new matcher object for specific patterns that can -// be used later to match against patterns against paths -func NewPatternMatcher(patterns []string) (*PatternMatcher, error) { - pm := &PatternMatcher{ - patterns: make([]*Pattern, 0, len(patterns)), - } - for _, p := range patterns { - // Eliminate leading and trailing whitespace. - p = strings.TrimSpace(p) - if p == "" { - continue - } - p = filepath.Clean(p) - newp := &Pattern{} - if p[0] == '!' { - if len(p) == 1 { - return nil, errors.New("illegal exclusion pattern: \"!\"") - } - newp.exclusion = true - p = p[1:] - pm.exclusions = true - } - // Do some syntax checking on the pattern. - // filepath's Match() has some really weird rules that are inconsistent - // so instead of trying to dup their logic, just call Match() for its - // error state and if there is an error in the pattern return it. - // If this becomes an issue we can remove this since its really only - // needed in the error (syntax) case - which isn't really critical. - if _, err := filepath.Match(p, "."); err != nil { - return nil, err - } - newp.cleanedPattern = p - newp.dirs = strings.Split(p, string(os.PathSeparator)) - pm.patterns = append(pm.patterns, newp) - } - return pm, nil -} - -// Matches matches path against all the patterns. Matches is not safe to be -// called concurrently -func (pm *PatternMatcher) Matches(file string) (bool, error) { - matched := false - file = filepath.FromSlash(file) - parentPath := filepath.Dir(file) - parentPathDirs := strings.Split(parentPath, string(os.PathSeparator)) - - for _, pattern := range pm.patterns { - negative := false - - if pattern.exclusion { - negative = true - } - - match, err := pattern.match(file) - if err != nil { - return false, err - } - - if !match && parentPath != "." { - // Check to see if the pattern matches one of our parent dirs. - if len(pattern.dirs) <= len(parentPathDirs) { - match, _ = pattern.match(strings.Join(parentPathDirs[:len(pattern.dirs)], string(os.PathSeparator))) - } - } - - if match { - matched = !negative - } - } - - if matched { - logrus.Debugf("Skipping excluded path: %s", file) - } - - return matched, nil -} - -// Exclusions returns true if any of the patterns define exclusions -func (pm *PatternMatcher) Exclusions() bool { - return pm.exclusions -} - -// Patterns returns array of active patterns -func (pm *PatternMatcher) Patterns() []*Pattern { - return pm.patterns -} - -// Pattern defines a single regexp used to filter file paths. -type Pattern struct { - cleanedPattern string - dirs []string - regexp *regexp.Regexp - exclusion bool -} - -func (p *Pattern) String() string { - return p.cleanedPattern -} - -// Exclusion returns true if this pattern defines exclusion -func (p *Pattern) Exclusion() bool { - return p.exclusion -} - -func (p *Pattern) match(path string) (bool, error) { - - if p.regexp == nil { - if err := p.compile(); err != nil { - return false, filepath.ErrBadPattern - } - } - - b := p.regexp.MatchString(path) - - return b, nil -} - -func (p *Pattern) compile() error { - regStr := "^" - pattern := p.cleanedPattern - // Go through the pattern and convert it to a regexp. - // We use a scanner so we can support utf-8 chars. - var scan scanner.Scanner - scan.Init(strings.NewReader(pattern)) - - sl := string(os.PathSeparator) - escSL := sl - if sl == `\` { - escSL += `\` - } - - for scan.Peek() != scanner.EOF { - ch := scan.Next() - - if ch == '*' { - if scan.Peek() == '*' { - // is some flavor of "**" - scan.Next() - - // Treat **/ as ** so eat the "/" - if string(scan.Peek()) == sl { - scan.Next() - } - - if scan.Peek() == scanner.EOF { - // is "**EOF" - to align with .gitignore just accept all - regStr += ".*" - } else { - // is "**" - // Note that this allows for any # of /'s (even 0) because - // the .* will eat everything, even /'s - regStr += "(.*" + escSL + ")?" - } - } else { - // is "*" so map it to anything but "/" - regStr += "[^" + escSL + "]*" - } - } else if ch == '?' { - // "?" is any char except "/" - regStr += "[^" + escSL + "]" - } else if ch == '.' || ch == '$' { - // Escape some regexp special chars that have no meaning - // in golang's filepath.Match - regStr += `\` + string(ch) - } else if ch == '\\' { - // escape next char. Note that a trailing \ in the pattern - // will be left alone (but need to escape it) - if sl == `\` { - // On windows map "\" to "\\", meaning an escaped backslash, - // and then just continue because filepath.Match on - // Windows doesn't allow escaping at all - regStr += escSL - continue - } - if scan.Peek() != scanner.EOF { - regStr += `\` + string(scan.Next()) - } else { - regStr += `\` - } - } else { - regStr += string(ch) - } - } - - regStr += "$" - - re, err := regexp.Compile(regStr) - if err != nil { - return err - } - - p.regexp = re - return nil -} - -// Matches returns true if file matches any of the patterns -// and isn't excluded by any of the subsequent patterns. -func Matches(file string, patterns []string) (bool, error) { - pm, err := NewPatternMatcher(patterns) - if err != nil { - return false, err - } - file = filepath.Clean(file) - - if file == "." { - // Don't let them exclude everything, kind of silly. - return false, nil - } - - return pm.Matches(file) -} - -// CopyFile copies from src to dst until either EOF is reached -// on src or an error occurs. It verifies src exists and removes -// the dst if it exists. -func CopyFile(src, dst string) (int64, error) { - cleanSrc := filepath.Clean(src) - cleanDst := filepath.Clean(dst) - if cleanSrc == cleanDst { - return 0, nil - } - sf, err := os.Open(cleanSrc) - if err != nil { - return 0, err - } - defer sf.Close() - if err := os.Remove(cleanDst); err != nil && !os.IsNotExist(err) { - return 0, err - } - df, err := os.Create(cleanDst) - if err != nil { - return 0, err - } - defer df.Close() - return io.Copy(df, sf) -} - -// ReadSymlinkedDirectory returns the target directory of a symlink. -// The target of the symbolic link may not be a file. -func ReadSymlinkedDirectory(path string) (string, error) { - var realPath string - var err error - if realPath, err = filepath.Abs(path); err != nil { - return "", fmt.Errorf("unable to get absolute path for %s: %s", path, err) - } - if realPath, err = filepath.EvalSymlinks(realPath); err != nil { - return "", fmt.Errorf("failed to canonicalise path for %s: %s", path, err) - } - realPathInfo, err := os.Stat(realPath) - if err != nil { - return "", fmt.Errorf("failed to stat target '%s' of '%s': %s", realPath, path, err) - } - if !realPathInfo.Mode().IsDir() { - return "", fmt.Errorf("canonical path points to a file '%s'", realPath) - } - return realPath, nil -} - -// CreateIfNotExists creates a file or a directory only if it does not already exist. -func CreateIfNotExists(path string, isDir bool) error { - if _, err := os.Stat(path); err != nil { - if os.IsNotExist(err) { - if isDir { - return os.MkdirAll(path, 0755) - } - if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { - return err - } - f, err := os.OpenFile(path, os.O_CREATE, 0755) - if err != nil { - return err - } - f.Close() - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go deleted file mode 100644 index e40cc271b..000000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_darwin.go +++ /dev/null @@ -1,27 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "os" - "os/exec" - "strconv" - "strings" -) - -// GetTotalUsedFds returns the number of used File Descriptors by -// executing `lsof -p PID` -func GetTotalUsedFds() int { - pid := os.Getpid() - - cmd := exec.Command("lsof", "-p", strconv.Itoa(pid)) - - output, err := cmd.CombinedOutput() - if err != nil { - return -1 - } - - outputStr := strings.TrimSpace(string(output)) - - fds := strings.Split(outputStr, "\n") - - return len(fds) - 1 -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go deleted file mode 100644 index 565396f1c..000000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build linux freebsd - -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -import ( - "fmt" - "io/ioutil" - "os" - - "github.com/sirupsen/logrus" -) - -// GetTotalUsedFds Returns the number of used File Descriptors by -// reading it via /proc filesystem. -func GetTotalUsedFds() int { - if fds, err := ioutil.ReadDir(fmt.Sprintf("/proc/%d/fd", os.Getpid())); err != nil { - logrus.Errorf("Error opening /proc/%d/fd: %s", os.Getpid(), err) - } else { - return len(fds) - } - return -1 -} diff --git a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go b/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go deleted file mode 100644 index 3f1ebb656..000000000 --- a/vendor/github.com/docker/docker/pkg/fileutils/fileutils_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package fileutils // import "github.com/docker/docker/pkg/fileutils" - -// GetTotalUsedFds Returns the number of used File Descriptors. Not supported -// on Windows. -func GetTotalUsedFds() int { - return -1 -} 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 47ecd0c09..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_linux.go +++ /dev/null @@ -1,109 +0,0 @@ -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/idtools" -) - -// GetStatic returns the home directory for the current user without calling -// os/user.Current(). This is useful for static-linked binary on glibc-based -// system, because a call to os/user.Current() in a static binary leads to -// segfault due to a glibc issue that won't be fixed in a short term. -// (#29344, golang/go#13470, https://sourceware.org/bugzilla/show_bug.cgi?id=19341) -func GetStatic() (string, error) { - uid := os.Getuid() - usr, err := idtools.LookupUID(uid) - if err != nil { - return "", err - } - return usr.Home, nil -} - -// 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. -// -// 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 := os.Getenv("HOME") - 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. -// -// 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 := os.Getenv("HOME") - if home == "" { - return "", errors.New("could not get either XDG_CONFIG_HOME or HOME") - } - return filepath.Join(home, ".config"), 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 f0a363ded..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_others.go +++ /dev/null @@ -1,33 +0,0 @@ -// +build !linux - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "errors" -) - -// GetStatic is not needed for non-linux systems. -// (Precisely, it is needed only for glibc-based linux systems.) -func GetStatic() (string, error) { - return "", errors.New("homedir.GetStatic() is not supported on this system") -} - -// 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") -} 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 d85e12448..000000000 --- a/vendor/github.com/docker/docker/pkg/homedir/homedir_unix.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build !windows - -package homedir // import "github.com/docker/docker/pkg/homedir" - -import ( - "os" - - "github.com/opencontainers/runc/libcontainer/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. -func Get() string { - home := os.Getenv(Key()) - if home == "" { - if u, err := user.CurrentUser(); err == nil { - return u.Home - } - } - 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 b3af7a422..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools.go +++ /dev/null @@ -1,264 +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 to the requested uid/gid pair. -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. -// 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 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 -} - -// IdentityMapping contains a mappings of UIDs and GIDs -type IdentityMapping struct { - uids []IDMap - gids []IDMap -} - -// NewIdentityMapping takes a requested user and group name and -// using the data from /etc/sub{uid,gid} ranges, creates the -// proper uid and gid remapping ranges for that user/group pair -func NewIdentityMapping(username, groupname string) (*IdentityMapping, error) { - subuidRanges, err := parseSubuid(username) - if err != nil { - return nil, err - } - subgidRanges, err := parseSubgid(groupname) - if err != nil { - return nil, err - } - if len(subuidRanges) == 0 { - return nil, fmt.Errorf("No subuid ranges found for user %q", username) - } - if len(subgidRanges) == 0 { - return nil, fmt.Errorf("No subgid ranges found for group %q", groupname) - } - - return &IdentityMapping{ - uids: createIDMap(subuidRanges), - gids: createIDMap(subgidRanges), - }, nil -} - -// NewIDMappingsFromMaps creates a new mapping from two slices -// Deprecated: this is a temporary shim while transitioning to IDMapping -func NewIDMappingsFromMaps(uids []IDMap, gids []IDMap) *IdentityMapping { - return &IdentityMapping{uids: uids, gids: gids} -} - -// 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.uids, i.gids) - 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.uids) - if err != nil { - return target, err - } - } - - if pair.GID != target.GID { - target.GID, err = toHost(pair.GID, i.gids) - } - 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.uids) - if err != nil { - return -1, -1, err - } - gid, err := toContainer(pair.GID, i.gids) - return uid, gid, err -} - -// Empty returns true if there are no id mappings -func (i *IdentityMapping) Empty() bool { - return len(i.uids) == 0 && len(i.gids) == 0 -} - -// UIDs return the UID mapping -// TODO: remove this once everything has been refactored to use pairs -func (i *IdentityMapping) UIDs() []IDMap { - return i.uids -} - -// GIDs return the UID mapping -// TODO: remove this once everything has been refactored to use pairs -func (i *IdentityMapping) GIDs() []IDMap { - return i.gids -} - -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() { - if err := s.Err(); err != nil { - return rangeList, err - } - - 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, nil -} 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 fb239743a..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_unix.go +++ /dev/null @@ -1,231 +0,0 @@ -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "bytes" - "fmt" - "io" - "os" - "path/filepath" - "strings" - "sync" - "syscall" - - "github.com/docker/docker/pkg/system" - "github.com/opencontainers/runc/libcontainer/user" -) - -var ( - entOnce sync.Once - getentCmd string -) - -func mkdirAs(path string, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - // 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 - - stat, err := system.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 lazyChown(path, owner.UID, owner.GID, stat) - } - - 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 := system.MkdirAll(path, mode, ""); err != nil { - return err - } - } else { - if err := os.Mkdir(path, mode); err != nil && !os.IsExist(err) { - 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 := lazyChown(pathComponent, owner.UID, owner.GID, nil); err != nil { - return err - } - } - return nil -} - -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -func CanAccess(path string, pair Identity) bool { - statInfo, err := system.Stat(path) - if err != nil { - return false - } - fileMode := os.FileMode(statInfo.Mode()) - permBits := fileMode.Perm() - return accessible(statInfo.UID() == uint32(pair.UID), - statInfo.GID() == uint32(pair.GID), permBits) -} - -func accessible(isOwner, isGroup bool, perms os.FileMode) bool { - if isOwner && (perms&0100 == 0100) { - return true - } - if isGroup && (perms&0010 == 0010) { - return true - } - if perms&0001 == 0001 { - return true - } - return false -} - -// 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(username string) (user.User, error) { - // first try a local system files lookup using existing capabilities - usr, err := user.LookupUser(username) - if err == nil { - return usr, nil - } - // local files lookup failed; attempt to call `getent` to query configured passwd dbs - usr, err = getentUser(fmt.Sprintf("%s %s", "passwd", username)) - 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(fmt.Sprintf("%s %d", "passwd", uid)) -} - -func getentUser(args string) (user.User, error) { - reader, err := callGetent(args) - 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", strings.Split(args, " ")[1]) - } - 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(groupname string) (user.Group, error) { - // first try a local system files lookup using existing capabilities - group, err := user.LookupGroup(groupname) - if err == nil { - return group, nil - } - // local files lookup failed; attempt to call `getent` to query configured group dbs - return getentGroup(fmt.Sprintf("%s %s", "group", groupname)) -} - -// 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(fmt.Sprintf("%s %d", "group", gid)) -} - -func getentGroup(args string) (user.Group, error) { - reader, err := callGetent(args) - 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", strings.Split(args, " ")[1]) - } - return groups[0], nil -} - -func callGetent(args string) (io.Reader, error) { - entOnce.Do(func() { getentCmd, _ = resolveBinary("getent") }) - // if no `getent` command on host, can't do anything else - if getentCmd == "" { - return nil, fmt.Errorf("") - } - out, err := execCmd(getentCmd, args) - if err != nil { - exitCode, errC := system.GetExitCode(err) - if errC != nil { - return nil, err - } - switch exitCode { - case 1: - return nil, fmt.Errorf("getent reported invalid parameters/database unknown") - case 2: - terms := strings.Split(args, " ") - return nil, fmt.Errorf("getent unable to find entry %q in %s database", terms[1], terms[0]) - case 3: - return nil, fmt.Errorf("getent database doesn't support enumeration") - default: - return nil, err - } - - } - return bytes.NewReader(out), nil -} - -// lazyChown performs a chown 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. -func lazyChown(p string, uid, gid int, stat *system.StatT) error { - if stat == nil { - var err error - stat, err = system.Stat(p) - if err != nil { - return err - } - } - if stat.UID() == uint32(uid) && stat.GID() == uint32(gid) { - return nil - } - return os.Chown(p, uid, gid) -} 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 4ae38a1b1..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/idtools_windows.go +++ /dev/null @@ -1,25 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "os" - - "github.com/docker/docker/pkg/system" -) - -// 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, mode os.FileMode, owner Identity, mkAll, chownExisting bool) error { - if err := system.MkdirAll(path, mode, ""); err != nil { - return err - } - return nil -} - -// CanAccess takes a valid (existing) directory and a uid, gid pair and determines -// if that uid, gid pair has access (execute bit) to the directory -// Windows does not require/support this function, so always return true -func CanAccess(path string, identity Identity) bool { - return true -} 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 6272c5a40..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_linux.go +++ /dev/null @@ -1,164 +0,0 @@ -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "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 - - cmdTemplates = map[string]string{ - "adduser": "--system --shell /bin/false --no-create-home --disabled-login --disabled-password --group %s", - "useradd": "-r -s /bin/false %s", - "usermod": "-%s %d-%d %s", - } - - idOutRegexp = regexp.MustCompile(`uid=([0-9]+).*gid=([0-9]+)`) - // default length for a UID/GID subordinate range - defaultRangeLen = 65536 - defaultRangeStart = 100000 - userMod = "usermod" -) - -// 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 := execCmd("id", name) - 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(userName 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" - } - }) - if userCommand == "" { - return fmt.Errorf("Cannot add user; no useradd/adduser binary found") - } - args := fmt.Sprintf(cmdTemplates[userCommand], userName) - out, err := execCmd(userCommand, args) - if 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) - } - out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "v", startID, startID+defaultRangeLen-1, name)) - 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) - } - out, err := execCmd(userMod, fmt.Sprintf(cmdTemplates[userMod], "w", startID, startID+defaultRangeLen-1, name)) - 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 e7c4d6311..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/usergroupadd_unsupported.go +++ /dev/null @@ -1,12 +0,0 @@ -// +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 903ac4501..000000000 --- a/vendor/github.com/docker/docker/pkg/idtools/utils_unix.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package idtools // import "github.com/docker/docker/pkg/idtools" - -import ( - "fmt" - "os/exec" - "path/filepath" - "strings" -) - -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) -} - -func execCmd(cmd, args string) ([]byte, error) { - execCmd := exec.Command(cmd, strings.Split(args, " ")...) - return execCmd.CombinedOutput() -} 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 d4bbf3c9d..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/bytespipe.go +++ /dev/null @@ -1,186 +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. -} - -// 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() - - written := 0 -loop0: - for { - if bp.closeErr != nil { - bp.mu.Unlock() - 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() - bp.mu.Unlock() - 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 { - 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() - bp.mu.Unlock() - 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() - if bp.bufLen == 0 { - if bp.closeErr != nil { - bp.mu.Unlock() - return 0, bp.closeErr - } - bp.wait.Wait() - if bp.bufLen == 0 && bp.closeErr != nil { - err := bp.closeErr - bp.mu.Unlock() - return 0, err - } - } - - 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() - bp.mu.Unlock() - 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 534d66ac2..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/fswriters.go +++ /dev/null @@ -1,162 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io" - "io/ioutil" - "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 := ioutil.TempFile(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 := ioutil.TempDir(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 1f657bd3d..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/readers.go +++ /dev/null @@ -1,157 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "context" - "crypto/sha256" - "encoding/hex" - "io" -) - -// 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 -} - -// Close calls back the passed closer function -func (r *ReadCloserWrapper) Close() error { - 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, - } -} - -// HashData returns the sha256 sum of src. -func HashData(src io.Reader) (string, error) { - h := sha256.New() - if _, err := io.Copy(h, src); err != nil { - return "", err - } - return "sha256:" + hex.EncodeToString(h.Sum(nil)), nil -} - -// 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 -} - -// 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 { - p.closeWithError(io.EOF) - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go deleted file mode 100644 index dc894f913..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import "io/ioutil" - -// TempDir on Unix systems is equivalent to ioutil.TempDir. -func TempDir(dir, prefix string) (string, error) { - return ioutil.TempDir(dir, prefix) -} diff --git a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go b/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go deleted file mode 100644 index ecaba2e36..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/temp_windows.go +++ /dev/null @@ -1,16 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import ( - "io/ioutil" - - "github.com/docker/docker/pkg/longpath" -) - -// TempDir is the equivalent of ioutil.TempDir, except that the result is in Windows longpath format. -func TempDir(dir, prefix string) (string, error) { - tempDir, err := ioutil.TempDir(dir, prefix) - if err != nil { - return "", err - } - return longpath.AddPrefix(tempDir), nil -} 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 61c679497..000000000 --- a/vendor/github.com/docker/docker/pkg/ioutils/writers.go +++ /dev/null @@ -1,66 +0,0 @@ -package ioutils // import "github.com/docker/docker/pkg/ioutils" - -import "io" - -// 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 -} - -func (r *writeCloserWrapper) Close() error { - 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 a68b566ce..000000000 --- a/vendor/github.com/docker/docker/pkg/jsonmessage/jsonmessage.go +++ /dev/null @@ -1,283 +0,0 @@ -package jsonmessage // import "github.com/docker/docker/pkg/jsonmessage" - -import ( - "encoding/json" - "fmt" - "io" - "strings" - "time" - - "github.com/docker/docker/pkg/term" - "github.com/docker/go-units" - "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 -// 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. terminalFd is the fd of the current terminal, -// Start is the initial value for the operation. Current is the current status and -// value of the progress made towards Total. Total is the end value describing when -// we made 100% progress for an operation. -type JSONProgress struct { - terminalFd uintptr - Current int64 `json:"current,omitempty"` - Total int64 `json:"total,omitempty"` - Start int64 `json:"start,omitempty"` - // If true, don't show xB/yB - HideCounts bool `json:"hidecounts,omitempty"` - Units string `json:"units,omitempty"` - nowFunc func() time.Time - 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 "": - current := units.HumanSize(float64(p.Current)) - return fmt.Sprintf("%8v", 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 -} - -// shim for testing -func (p *JSONProgress) now() time.Time { - if p.nowFunc == nil { - p.nowFunc = func() time.Time { - return time.Now().UTC() - } - } - return p.nowFunc() -} - -// shim for testing -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 displays the JSONMessage to `out`. If `isTerminal` is true, it will erase the -// entire current line when displaying the progressbar. -func (jm *JSONMessage) Display(out io.Writer, isTerminal bool) error { - if jm.Error != nil { - if jm.Error.Code == 401 { - return fmt.Errorf("authentication is required") - } - return jm.Error - } - var endl string - if isTerminal && jm.Stream == "" && jm.Progress != nil { - clearLine(out) - endl = "\r" - fmt.Fprintf(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 displays a json message stream from `in` to `out`, `isTerminal` -// describes if `out` is a terminal. If this is the case, it will print `\n` at the end of -// each line and move the cursor while displaying. -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 -} - -type stream interface { - io.Writer - FD() uintptr - IsTerminal() bool -} - -// DisplayJSONMessagesToStream prints json messages to the output stream -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 4177affba..000000000 --- a/vendor/github.com/docker/docker/pkg/longpath/longpath.go +++ /dev/null @@ -1,26 +0,0 @@ -// longpath introduces some constants and helper functions for handling long paths -// in Windows, which 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 ( - "strings" -) - -// Prefix is the longpath prefix for Windows file paths. -const Prefix = `\\?\` - -// AddPrefix will add 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 -} diff --git a/vendor/github.com/docker/docker/pkg/mount/flags.go b/vendor/github.com/docker/docker/pkg/mount/flags.go deleted file mode 100644 index ffd473311..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/flags.go +++ /dev/null @@ -1,137 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "fmt" - "strings" -) - -var flags = map[string]struct { - clear bool - flag int -}{ - "defaults": {false, 0}, - "ro": {false, RDONLY}, - "rw": {true, RDONLY}, - "suid": {true, NOSUID}, - "nosuid": {false, NOSUID}, - "dev": {true, NODEV}, - "nodev": {false, NODEV}, - "exec": {true, NOEXEC}, - "noexec": {false, NOEXEC}, - "sync": {false, SYNCHRONOUS}, - "async": {true, SYNCHRONOUS}, - "dirsync": {false, DIRSYNC}, - "remount": {false, REMOUNT}, - "mand": {false, MANDLOCK}, - "nomand": {true, MANDLOCK}, - "atime": {true, NOATIME}, - "noatime": {false, NOATIME}, - "diratime": {true, NODIRATIME}, - "nodiratime": {false, NODIRATIME}, - "bind": {false, BIND}, - "rbind": {false, RBIND}, - "unbindable": {false, UNBINDABLE}, - "runbindable": {false, RUNBINDABLE}, - "private": {false, PRIVATE}, - "rprivate": {false, RPRIVATE}, - "shared": {false, SHARED}, - "rshared": {false, RSHARED}, - "slave": {false, SLAVE}, - "rslave": {false, RSLAVE}, - "relatime": {false, RELATIME}, - "norelatime": {true, RELATIME}, - "strictatime": {false, STRICTATIME}, - "nostrictatime": {true, STRICTATIME}, -} - -var validFlags = map[string]bool{ - "": true, - "size": true, - "mode": true, - "uid": true, - "gid": true, - "nr_inodes": true, - "nr_blocks": true, - "mpol": true, -} - -var propagationFlags = map[string]bool{ - "bind": true, - "rbind": true, - "unbindable": true, - "runbindable": true, - "private": true, - "rprivate": true, - "shared": true, - "rshared": true, - "slave": true, - "rslave": true, -} - -// MergeTmpfsOptions merge mount options to make sure there is no duplicate. -func MergeTmpfsOptions(options []string) ([]string, error) { - // We use collisions maps to remove duplicates. - // For flag, the key is the flag value (the key for propagation flag is -1) - // For data=value, the key is the data - flagCollisions := map[int]bool{} - dataCollisions := map[string]bool{} - - var newOptions []string - // We process in reverse order - for i := len(options) - 1; i >= 0; i-- { - option := options[i] - if option == "defaults" { - continue - } - if f, ok := flags[option]; ok && f.flag != 0 { - // There is only one propagation mode - key := f.flag - if propagationFlags[option] { - key = -1 - } - // Check to see if there is collision for flag - if !flagCollisions[key] { - // We prepend the option and add to collision map - newOptions = append([]string{option}, newOptions...) - flagCollisions[key] = true - } - continue - } - opt := strings.SplitN(option, "=", 2) - if len(opt) != 2 || !validFlags[opt[0]] { - return nil, fmt.Errorf("Invalid tmpfs option %q", opt) - } - if !dataCollisions[opt[0]] { - // We prepend the option and add to collision map - newOptions = append([]string{option}, newOptions...) - dataCollisions[opt[0]] = true - } - } - - return newOptions, nil -} - -// Parse fstab type mount options into mount() flags -// and device specific data -func parseOptions(options string) (int, string) { - var ( - flag int - data []string - ) - - for _, o := range strings.Split(options, ",") { - // If the option does not exist in the flags table or the flag - // is not supported on the platform, - // then it is a data value for a specific fs type - if f, exists := flags[o]; exists && f.flag != 0 { - if f.clear { - flag &= ^f.flag - } else { - flag |= f.flag - } - } else { - data = append(data, o) - } - } - return flag, strings.Join(data, ",") -} diff --git a/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go b/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go deleted file mode 100644 index ef35ef905..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/flags_freebsd.go +++ /dev/null @@ -1,49 +0,0 @@ -// +build freebsd,cgo - -package mount // import "github.com/docker/docker/pkg/mount" - -/* -#include -*/ -import "C" - -const ( - // RDONLY will mount the filesystem as read-only. - RDONLY = C.MNT_RDONLY - - // NOSUID will not allow set-user-identifier or set-group-identifier bits to - // take effect. - NOSUID = C.MNT_NOSUID - - // NOEXEC will not allow execution of any binaries on the mounted file system. - NOEXEC = C.MNT_NOEXEC - - // SYNCHRONOUS will allow any I/O to the file system to be done synchronously. - SYNCHRONOUS = C.MNT_SYNCHRONOUS - - // NOATIME will not update the file access time when reading from a file. - NOATIME = C.MNT_NOATIME -) - -// These flags are unsupported. -const ( - BIND = 0 - DIRSYNC = 0 - MANDLOCK = 0 - NODEV = 0 - NODIRATIME = 0 - UNBINDABLE = 0 - RUNBINDABLE = 0 - PRIVATE = 0 - RPRIVATE = 0 - SHARED = 0 - RSHARED = 0 - SLAVE = 0 - RSLAVE = 0 - RBIND = 0 - RELATIVE = 0 - RELATIME = 0 - REMOUNT = 0 - STRICTATIME = 0 - mntDetach = 0 -) diff --git a/vendor/github.com/docker/docker/pkg/mount/flags_linux.go b/vendor/github.com/docker/docker/pkg/mount/flags_linux.go deleted file mode 100644 index a1b199a31..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/flags_linux.go +++ /dev/null @@ -1,87 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "golang.org/x/sys/unix" -) - -const ( - // RDONLY will mount the file system read-only. - RDONLY = unix.MS_RDONLY - - // NOSUID will not allow set-user-identifier or set-group-identifier bits to - // take effect. - NOSUID = unix.MS_NOSUID - - // NODEV will not interpret character or block special devices on the file - // system. - NODEV = unix.MS_NODEV - - // NOEXEC will not allow execution of any binaries on the mounted file system. - NOEXEC = unix.MS_NOEXEC - - // SYNCHRONOUS will allow I/O to the file system to be done synchronously. - SYNCHRONOUS = unix.MS_SYNCHRONOUS - - // DIRSYNC will force all directory updates within the file system to be done - // synchronously. This affects the following system calls: create, link, - // unlink, symlink, mkdir, rmdir, mknod and rename. - DIRSYNC = unix.MS_DIRSYNC - - // REMOUNT will attempt to remount an already-mounted file system. This is - // commonly used to change the mount flags for a file system, especially to - // make a readonly file system writeable. It does not change device or mount - // point. - REMOUNT = unix.MS_REMOUNT - - // MANDLOCK will force mandatory locks on a filesystem. - MANDLOCK = unix.MS_MANDLOCK - - // NOATIME will not update the file access time when reading from a file. - NOATIME = unix.MS_NOATIME - - // NODIRATIME will not update the directory access time. - NODIRATIME = unix.MS_NODIRATIME - - // BIND remounts a subtree somewhere else. - BIND = unix.MS_BIND - - // RBIND remounts a subtree and all possible submounts somewhere else. - RBIND = unix.MS_BIND | unix.MS_REC - - // UNBINDABLE creates a mount which cannot be cloned through a bind operation. - UNBINDABLE = unix.MS_UNBINDABLE - - // RUNBINDABLE marks the entire mount tree as UNBINDABLE. - RUNBINDABLE = unix.MS_UNBINDABLE | unix.MS_REC - - // PRIVATE creates a mount which carries no propagation abilities. - PRIVATE = unix.MS_PRIVATE - - // RPRIVATE marks the entire mount tree as PRIVATE. - RPRIVATE = unix.MS_PRIVATE | unix.MS_REC - - // SLAVE creates a mount which receives propagation from its master, but not - // vice versa. - SLAVE = unix.MS_SLAVE - - // RSLAVE marks the entire mount tree as SLAVE. - RSLAVE = unix.MS_SLAVE | unix.MS_REC - - // SHARED creates a mount which provides the ability to create mirrors of - // that mount such that mounts and unmounts within any of the mirrors - // propagate to the other mirrors. - SHARED = unix.MS_SHARED - - // RSHARED marks the entire mount tree as SHARED. - RSHARED = unix.MS_SHARED | unix.MS_REC - - // RELATIME updates inode access times relative to modify or change time. - RELATIME = unix.MS_RELATIME - - // STRICTATIME allows to explicitly request full atime updates. This makes - // it possible for the kernel to default to relatime or noatime but still - // allow userspace to override it. - STRICTATIME = unix.MS_STRICTATIME - - mntDetach = unix.MNT_DETACH -) diff --git a/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go b/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go deleted file mode 100644 index cc6c47590..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/flags_unsupported.go +++ /dev/null @@ -1,31 +0,0 @@ -// +build !linux,!freebsd freebsd,!cgo - -package mount // import "github.com/docker/docker/pkg/mount" - -// These flags are unsupported. -const ( - BIND = 0 - DIRSYNC = 0 - MANDLOCK = 0 - NOATIME = 0 - NODEV = 0 - NODIRATIME = 0 - NOEXEC = 0 - NOSUID = 0 - UNBINDABLE = 0 - RUNBINDABLE = 0 - PRIVATE = 0 - RPRIVATE = 0 - SHARED = 0 - RSHARED = 0 - SLAVE = 0 - RSLAVE = 0 - RBIND = 0 - RELATIME = 0 - RELATIVE = 0 - REMOUNT = 0 - STRICTATIME = 0 - SYNCHRONOUS = 0 - RDONLY = 0 - mntDetach = 0 -) diff --git a/vendor/github.com/docker/docker/pkg/mount/mount.go b/vendor/github.com/docker/docker/pkg/mount/mount.go deleted file mode 100644 index 4afd63c42..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mount.go +++ /dev/null @@ -1,159 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "sort" - "strconv" - "strings" - - "github.com/sirupsen/logrus" -) - -// mountError records an error from mount or unmount operation -type mountError struct { - op string - source, target string - flags uintptr - data string - err error -} - -func (e *mountError) Error() string { - out := e.op + " " - - if e.source != "" { - out += e.source + ":" + e.target - } else { - out += e.target - } - - if e.flags != uintptr(0) { - out += ", flags: 0x" + strconv.FormatUint(uint64(e.flags), 16) - } - if e.data != "" { - out += ", data: " + e.data - } - - out += ": " + e.err.Error() - return out -} - -// Cause returns the underlying cause of the error -func (e *mountError) Cause() error { - return e.err -} - -// FilterFunc is a type defining a callback function -// to filter out unwanted entries. It takes a pointer -// to an Info struct (not fully populated, currently -// only Mountpoint is filled in), and returns two booleans: -// - skip: true if the entry should be skipped -// - stop: true if parsing should be stopped after the entry -type FilterFunc func(*Info) (skip, stop bool) - -// PrefixFilter discards all entries whose mount points -// do not start with a prefix specified -func PrefixFilter(prefix string) FilterFunc { - return func(m *Info) (bool, bool) { - skip := !strings.HasPrefix(m.Mountpoint, prefix) - return skip, false - } -} - -// SingleEntryFilter looks for a specific entry -func SingleEntryFilter(mp string) FilterFunc { - return func(m *Info) (bool, bool) { - if m.Mountpoint == mp { - return false, true // don't skip, stop now - } - return true, false // skip, keep going - } -} - -// ParentsFilter returns all entries whose mount points -// can be parents of a path specified, discarding others. -// For example, given `/var/lib/docker/something`, entries -// like `/var/lib/docker`, `/var` and `/` are returned. -func ParentsFilter(path string) FilterFunc { - return func(m *Info) (bool, bool) { - skip := !strings.HasPrefix(path, m.Mountpoint) - return skip, false - } -} - -// GetMounts retrieves a list of mounts for the current running process, -// with an optional filter applied (use nil for no filter). -func GetMounts(f FilterFunc) ([]*Info, error) { - return parseMountTable(f) -} - -// Mounted determines if a specified mountpoint has been mounted. -// On Linux it looks at /proc/self/mountinfo. -func Mounted(mountpoint string) (bool, error) { - entries, err := GetMounts(SingleEntryFilter(mountpoint)) - if err != nil { - return false, err - } - - return len(entries) > 0, nil -} - -// Mount will mount filesystem according to the specified configuration, on the -// condition that the target path is *not* already mounted. Options must be -// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See -// flags.go for supported option flags. -func Mount(device, target, mType, options string) error { - flag, _ := parseOptions(options) - if flag&REMOUNT != REMOUNT { - if mounted, err := Mounted(target); err != nil || mounted { - return err - } - } - return ForceMount(device, target, mType, options) -} - -// ForceMount will mount a filesystem according to the specified configuration, -// *regardless* if the target path is not already mounted. Options must be -// specified like the mount or fstab unix commands: "opt1=val1,opt2=val2". See -// flags.go for supported option flags. -func ForceMount(device, target, mType, options string) error { - flag, data := parseOptions(options) - return mount(device, target, mType, uintptr(flag), data) -} - -// Unmount lazily unmounts a filesystem on supported platforms, otherwise -// does a normal unmount. -func Unmount(target string) error { - return unmount(target, mntDetach) -} - -// RecursiveUnmount unmounts the target and all mounts underneath, starting with -// the deepsest mount first. -func RecursiveUnmount(target string) error { - mounts, err := parseMountTable(PrefixFilter(target)) - if err != nil { - return err - } - - // Make the deepest mount be first - sort.Slice(mounts, func(i, j int) bool { - return len(mounts[i].Mountpoint) > len(mounts[j].Mountpoint) - }) - - for i, m := range mounts { - logrus.Debugf("Trying to unmount %s", m.Mountpoint) - err = unmount(m.Mountpoint, mntDetach) - if err != nil { - if i == len(mounts)-1 { // last mount - if mounted, e := Mounted(m.Mountpoint); e != nil || mounted { - return err - } - } else { - // This is some submount, we can ignore this error for now, the final unmount will fail if this is a real problem - logrus.WithError(err).Warnf("Failed to unmount submount %s", m.Mountpoint) - } - } - - logrus.Debugf("Unmounted %s", m.Mountpoint) - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go b/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go deleted file mode 100644 index 09ad36060..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mounter_freebsd.go +++ /dev/null @@ -1,59 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -/* -#include -#include -#include -#include -#include -#include -*/ -import "C" - -import ( - "strings" - "syscall" - "unsafe" -) - -func allocateIOVecs(options []string) []C.struct_iovec { - out := make([]C.struct_iovec, len(options)) - for i, option := range options { - out[i].iov_base = unsafe.Pointer(C.CString(option)) - out[i].iov_len = C.size_t(len(option) + 1) - } - return out -} - -func mount(device, target, mType string, flag uintptr, data string) error { - isNullFS := false - - xs := strings.Split(data, ",") - for _, x := range xs { - if x == "bind" { - isNullFS = true - } - } - - options := []string{"fspath", target} - if isNullFS { - options = append(options, "fstype", "nullfs", "target", device) - } else { - options = append(options, "fstype", mType, "from", device) - } - rawOptions := allocateIOVecs(options) - for _, rawOption := range rawOptions { - defer C.free(rawOption.iov_base) - } - - if errno := C.nmount(&rawOptions[0], C.uint(len(options)), C.int(flag)); errno != 0 { - return &mountError{ - op: "mount", - source: device, - target: target, - flags: flag, - err: syscall.Errno(errno), - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go b/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go deleted file mode 100644 index a0a1ad236..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mounter_linux.go +++ /dev/null @@ -1,73 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "golang.org/x/sys/unix" -) - -const ( - // ptypes is the set propagation types. - ptypes = unix.MS_SHARED | unix.MS_PRIVATE | unix.MS_SLAVE | unix.MS_UNBINDABLE - - // pflags is the full set valid flags for a change propagation call. - pflags = ptypes | unix.MS_REC | unix.MS_SILENT - - // broflags is the combination of bind and read only - broflags = unix.MS_BIND | unix.MS_RDONLY -) - -// isremount returns true if either device name or flags identify a remount request, false otherwise. -func isremount(device string, flags uintptr) bool { - switch { - // We treat device "" and "none" as a remount request to provide compatibility with - // requests that don't explicitly set MS_REMOUNT such as those manipulating bind mounts. - case flags&unix.MS_REMOUNT != 0, device == "", device == "none": - return true - default: - return false - } -} - -func mount(device, target, mType string, flags uintptr, data string) error { - oflags := flags &^ ptypes - if !isremount(device, flags) || data != "" { - // Initial call applying all non-propagation flags for mount - // or remount with changed data - if err := unix.Mount(device, target, mType, oflags, data); err != nil { - return &mountError{ - op: "mount", - source: device, - target: target, - flags: oflags, - data: data, - err: err, - } - } - } - - if flags&ptypes != 0 { - // Change the propagation type. - if err := unix.Mount("", target, "", flags&pflags, ""); err != nil { - return &mountError{ - op: "remount", - target: target, - flags: flags & pflags, - err: err, - } - } - } - - if oflags&broflags == broflags { - // Remount the bind to apply read only. - if err := unix.Mount("", target, "", oflags|unix.MS_REMOUNT, ""); err != nil { - return &mountError{ - op: "remount-ro", - target: target, - flags: oflags | unix.MS_REMOUNT, - err: err, - } - - } - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go b/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go deleted file mode 100644 index c3e5aec27..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mounter_unsupported.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !linux,!freebsd freebsd,!cgo - -package mount // import "github.com/docker/docker/pkg/mount" - -func mount(device, target, mType string, flag uintptr, data string) error { - panic("Not implemented") -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo.go deleted file mode 100644 index ecd03fc02..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo.go +++ /dev/null @@ -1,40 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -// Info reveals information about a particular mounted filesystem. This -// struct is populated from the content in the /proc//mountinfo file. -type Info struct { - // ID is a unique identifier of the mount (may be reused after umount). - ID int - - // Parent indicates the ID of the mount parent (or of self for the top of the - // mount tree). - Parent int - - // Major indicates one half of the device ID which identifies the device class. - Major int - - // Minor indicates one half of the device ID which identifies a specific - // instance of device. - Minor int - - // Root of the mount within the filesystem. - Root string - - // Mountpoint indicates the mount point relative to the process's root. - Mountpoint string - - // Opts represents mount-specific options. - Opts string - - // Optional represents optional fields. - Optional string - - // Fstype indicates the type of filesystem, such as EXT3. - Fstype string - - // Source indicates filesystem specific information or "none". - Source string - - // VfsOpts represents per super block options. - VfsOpts string -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go deleted file mode 100644 index 36c89dc1a..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo_freebsd.go +++ /dev/null @@ -1,55 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -/* -#include -#include -#include -*/ -import "C" - -import ( - "fmt" - "reflect" - "unsafe" -) - -// Parse /proc/self/mountinfo because comparing Dev and ino does not work from -// bind mounts. -func parseMountTable(filter FilterFunc) ([]*Info, error) { - var rawEntries *C.struct_statfs - - count := int(C.getmntinfo(&rawEntries, C.MNT_WAIT)) - if count == 0 { - return nil, fmt.Errorf("Failed to call getmntinfo") - } - - var entries []C.struct_statfs - header := (*reflect.SliceHeader)(unsafe.Pointer(&entries)) - header.Cap = count - header.Len = count - header.Data = uintptr(unsafe.Pointer(rawEntries)) - - var out []*Info - for _, entry := range entries { - var mountinfo Info - var skip, stop bool - mountinfo.Mountpoint = C.GoString(&entry.f_mntonname[0]) - - if filter != nil { - // filter out entries we're not interested in - skip, stop = filter(p) - if skip { - continue - } - } - - mountinfo.Source = C.GoString(&entry.f_mntfromname[0]) - mountinfo.Fstype = C.GoString(&entry.f_fstypename[0]) - - out = append(out, &mountinfo) - if stop { - break - } - } - return out, nil -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go deleted file mode 100644 index fe6e3ddba..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo_linux.go +++ /dev/null @@ -1,144 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "bufio" - "fmt" - "io" - "os" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -func parseInfoFile(r io.Reader, filter FilterFunc) ([]*Info, error) { - s := bufio.NewScanner(r) - out := []*Info{} - var err error - for s.Scan() { - if err = s.Err(); err != nil { - return nil, err - } - /* - See http://man7.org/linux/man-pages/man5/proc.5.html - - 36 35 98:0 /mnt1 /mnt2 rw,noatime master:1 - ext3 /dev/root rw,errors=continue - (1)(2)(3) (4) (5) (6) (7) (8) (9) (10) (11) - - (1) mount ID: unique identifier of the mount (may be reused after umount) - (2) parent ID: ID of parent (or of self for the top of the mount tree) - (3) major:minor: value of st_dev for files on filesystem - (4) root: root of the mount within the filesystem - (5) mount point: mount point relative to the process's root - (6) mount options: per mount options - (7) optional fields: zero or more fields of the form "tag[:value]" - (8) separator: marks the end of the optional fields - (9) filesystem type: name of filesystem of the form "type[.subtype]" - (10) mount source: filesystem specific information or "none" - (11) super options: per super block options - */ - - text := s.Text() - fields := strings.Split(text, " ") - numFields := len(fields) - if numFields < 10 { - // should be at least 10 fields - return nil, fmt.Errorf("Parsing '%s' failed: not enough fields (%d)", text, numFields) - } - - p := &Info{} - // ignore any numbers parsing errors, as there should not be any - p.ID, _ = strconv.Atoi(fields[0]) - p.Parent, _ = strconv.Atoi(fields[1]) - mm := strings.Split(fields[2], ":") - if len(mm) != 2 { - return nil, fmt.Errorf("Parsing '%s' failed: unexpected minor:major pair %s", text, mm) - } - p.Major, _ = strconv.Atoi(mm[0]) - p.Minor, _ = strconv.Atoi(mm[1]) - - p.Root, err = strconv.Unquote(`"` + fields[3] + `"`) - if err != nil { - return nil, errors.Wrapf(err, "Parsing '%s' failed: unable to unquote root field", fields[3]) - } - - p.Mountpoint, err = strconv.Unquote(`"` + fields[4] + `"`) - if err != nil { - return nil, errors.Wrapf(err, "Parsing '%s' failed: unable to unquote mount point field", fields[4]) - } - p.Opts = fields[5] - - var skip, stop bool - if filter != nil { - // filter out entries we're not interested in - skip, stop = filter(p) - if skip { - continue - } - } - - // one or more optional fields, when a separator (-) - i := 6 - for ; i < numFields && fields[i] != "-"; i++ { - switch i { - case 6: - p.Optional = fields[6] - default: - /* NOTE there might be more optional fields before the such as - fields[7]...fields[N] (where N < sepIndex), although - as of Linux kernel 4.15 the only known ones are - mount propagation flags in fields[6]. The correct - behavior is to ignore any unknown optional fields. - */ - break - } - } - if i == numFields { - return nil, fmt.Errorf("Parsing '%s' failed: missing separator ('-')", text) - } - - // There should be 3 fields after the separator... - if i+4 > numFields { - return nil, fmt.Errorf("Parsing '%s' failed: not enough fields after a separator", text) - } - // ... but in Linux <= 3.9 mounting a cifs with spaces in a share name - // (like "//serv/My Documents") _may_ end up having a space in the last field - // of mountinfo (like "unc=//serv/My Documents"). Since kernel 3.10-rc1, cifs - // option unc= is ignored, so a space should not appear. In here we ignore - // those "extra" fields caused by extra spaces. - p.Fstype = fields[i+1] - p.Source = fields[i+2] - p.VfsOpts = fields[i+3] - - out = append(out, p) - if stop { - break - } - } - return out, nil -} - -// Parse /proc/self/mountinfo because comparing Dev and ino does not work from -// bind mounts -func parseMountTable(filter FilterFunc) ([]*Info, error) { - f, err := os.Open("/proc/self/mountinfo") - if err != nil { - return nil, err - } - defer f.Close() - - return parseInfoFile(f, filter) -} - -// PidMountInfo collects the mounts for a specific process ID. If the process -// ID is unknown, it is better to use `GetMounts` which will inspect -// "/proc/self/mountinfo" instead. -func PidMountInfo(pid int) ([]*Info, error) { - f, err := os.Open(fmt.Sprintf("/proc/%d/mountinfo", pid)) - if err != nil { - return nil, err - } - defer f.Close() - - return parseInfoFile(f, nil) -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go deleted file mode 100644 index fd16d3ed6..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo_unsupported.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !windows,!linux,!freebsd freebsd,!cgo - -package mount // import "github.com/docker/docker/pkg/mount" - -import ( - "fmt" - "runtime" -) - -func parseMountTable(f FilterFunc) ([]*Info, error) { - return nil, fmt.Errorf("mount.parseMountTable is not implemented on %s/%s", runtime.GOOS, runtime.GOARCH) -} diff --git a/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go b/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go deleted file mode 100644 index 27e0f6976..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/mountinfo_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -func parseMountTable(f FilterFunc) ([]*Info, error) { - // Do NOT return an error! - return nil, nil -} diff --git a/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go b/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go deleted file mode 100644 index 8a100f0bc..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/sharedsubtree_linux.go +++ /dev/null @@ -1,71 +0,0 @@ -package mount // import "github.com/docker/docker/pkg/mount" - -// MakeShared ensures a mounted filesystem has the SHARED mount option enabled. -// See the supported options in flags.go for further reference. -func MakeShared(mountPoint string) error { - return ensureMountedAs(mountPoint, "shared") -} - -// MakeRShared ensures a mounted filesystem has the RSHARED mount option enabled. -// See the supported options in flags.go for further reference. -func MakeRShared(mountPoint string) error { - return ensureMountedAs(mountPoint, "rshared") -} - -// MakePrivate ensures a mounted filesystem has the PRIVATE mount option enabled. -// See the supported options in flags.go for further reference. -func MakePrivate(mountPoint string) error { - return ensureMountedAs(mountPoint, "private") -} - -// MakeRPrivate ensures a mounted filesystem has the RPRIVATE mount option -// enabled. See the supported options in flags.go for further reference. -func MakeRPrivate(mountPoint string) error { - return ensureMountedAs(mountPoint, "rprivate") -} - -// MakeSlave ensures a mounted filesystem has the SLAVE mount option enabled. -// See the supported options in flags.go for further reference. -func MakeSlave(mountPoint string) error { - return ensureMountedAs(mountPoint, "slave") -} - -// MakeRSlave ensures a mounted filesystem has the RSLAVE mount option enabled. -// See the supported options in flags.go for further reference. -func MakeRSlave(mountPoint string) error { - return ensureMountedAs(mountPoint, "rslave") -} - -// MakeUnbindable ensures a mounted filesystem has the UNBINDABLE mount option -// enabled. See the supported options in flags.go for further reference. -func MakeUnbindable(mountPoint string) error { - return ensureMountedAs(mountPoint, "unbindable") -} - -// MakeRUnbindable ensures a mounted filesystem has the RUNBINDABLE mount -// option enabled. See the supported options in flags.go for further reference. -func MakeRUnbindable(mountPoint string) error { - return ensureMountedAs(mountPoint, "runbindable") -} - -// MakeMount ensures that the file or directory given is a mount point, -// bind mounting it to itself it case it is not. -func MakeMount(mnt string) error { - mounted, err := Mounted(mnt) - if err != nil { - return err - } - if mounted { - return nil - } - - return Mount(mnt, mnt, "none", "bind") -} - -func ensureMountedAs(mountPoint, options string) error { - if err := MakeMount(mountPoint); err != nil { - return err - } - - return ForceMount("", mountPoint, "none", options) -} diff --git a/vendor/github.com/docker/docker/pkg/mount/unmount_unix.go b/vendor/github.com/docker/docker/pkg/mount/unmount_unix.go deleted file mode 100644 index 4be427685..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/unmount_unix.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !windows - -package mount // import "github.com/docker/docker/pkg/mount" - -import "golang.org/x/sys/unix" - -func unmount(target string, flags int) error { - err := unix.Unmount(target, flags) - if err == nil || err == unix.EINVAL { - // Ignore "not mounted" error here. Note the same error - // can be returned if flags are invalid, so this code - // assumes that the flags value is always correct. - return nil - } - - return &mountError{ - op: "umount", - target: target, - flags: uintptr(flags), - err: err, - } -} diff --git a/vendor/github.com/docker/docker/pkg/mount/unmount_unsupported.go b/vendor/github.com/docker/docker/pkg/mount/unmount_unsupported.go deleted file mode 100644 index a88ad3577..000000000 --- a/vendor/github.com/docker/docker/pkg/mount/unmount_unsupported.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build windows - -package mount // import "github.com/docker/docker/pkg/mount" - -func unmount(target string, flag int) error { - panic("Not implemented") -} 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 05eac680e..000000000 --- a/vendor/github.com/docker/docker/pkg/namesgenerator/names-generator.go +++ /dev/null @@ -1,853 +0,0 @@ -package namesgenerator // import "github.com/docker/docker/pkg/namesgenerator" - -import ( - "fmt" - "math/rand" -) - -var ( - left = [...]string{ - "admiring", - "adoring", - "affectionate", - "agitated", - "amazing", - "angry", - "awesome", - "beautiful", - "blissful", - "bold", - "boring", - "brave", - "busy", - "charming", - "clever", - "cocky", - "cool", - "compassionate", - "competent", - "condescending", - "confident", - "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", - "interesting", - "intelligent", - "jolly", - "jovial", - "keen", - "kind", - "laughing", - "loving", - "lucid", - "magical", - "mystifying", - "modest", - "musing", - "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{ - // 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", - - // 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", - - // 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 perfectd the "oscillation overthruster", a device that allows one to pass through solid matter. - https://en.wikipedia.org/wiki/The_Adventures_of_Buckaroo_Banzai_Across_the_8th_Dimension - "banzai", - - // John Bardeen co-invented the transistor - https://en.wikipedia.org/wiki/John_Bardeen - "bardeen", - - // 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", - - // 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", - - // 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", - - // Bram Cohen - American computer programmer and author of the BitTorrent peer-to-peer protocol. https://en.wikipedia.org/wiki/Bram_Cohen - "cohen", - - // David Lee Chaum - American computer scientist and cryptographer. Known for his seminal contributions in the field of anonymous communication. https://en.wikipedia.org/wiki/David_Chaum - "chaum", - - // Joan Clarke - Bletchley Park code breaker during the Second World War who pioneered techniques that remained top secret for decades. Also an accomplished numismatist https://en.wikipedia.org/wiki/Joan_Clarke - "clarke", - - // 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", - - // 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", - - // Marie Curie discovered radioactivity. https://en.wikipedia.org/wiki/Marie_Curie. - "curie", - - // 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", - - // Martin Edward Hellman - American cryptologist, best known for his invention of public-key cryptography in co-operation with Whitfield Diffie and Ralph Merkle. https://en.wikipedia.org/wiki/Martin_Hellman - "hellman", - - // Werner Heisenberg was a founding father of quantum mechanics. https://en.wikipedia.org/wiki/Werner_Heisenberg - "heisenberg", - - // Grete Hermann was a German philosopher noted for her philosophical work on the foundations of quantum mechanics. https://en.wikipedia.org/wiki/Grete_Hermann - "hermann", - - // Caroline Lucretia Herschel - German astronomer and discoverer of several comets. https://en.wikipedia.org/wiki/Caroline_Herschel - "herschel", - - // Heinrich Rudolf Hertz - German physicist who first conclusively proved the existence of the electromagnetic waves. https://en.wikipedia.org/wiki/Heinrich_Hertz - "hertz", - - // Jaroslav Heyrovský was the inventor of the polarographic method, father of the electroanalytical method, and recipient of the Nobel Prize in 1959. His main field of work was polarography. https://en.wikipedia.org/wiki/Jaroslav_Heyrovsk%C3%BD - "heyrovsky", - - // Dorothy Hodgkin was a British biochemist, credited with the development of protein crystallography. She was awarded the Nobel Prize in Chemistry in 1964. https://en.wikipedia.org/wiki/Dorothy_Hodgkin - "hodgkin", - - // Douglas R. Hofstadter is an American professor of cognitive science and author of the Pulitzer Prize and American Book Award-winning work Goedel, Escher, Bach: An Eternal Golden Braid in 1979. A mind-bending work which coined Hofstadter's Law: "It always takes longer than you expect, even when you take into account Hofstadter's Law." https://en.wikipedia.org/wiki/Douglas_Hofstadter - "hofstadter", - - // Erna Schneider Hoover revolutionized modern communication by inventing a computerized telephone switching method. https://en.wikipedia.org/wiki/Erna_Schneider_Hoover - "hoover", - - // 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", - - // 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 silicone 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", - - // 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", - - // 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", - - // 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", - - // Marvin Minsky - Pioneer in Artificial Intelligence, co-founder of the MIT's AI Lab, won the Turing Award in 1969. https://en.wikipedia.org/wiki/Marvin_Minsky - "minsky", - - // Maryam Mirzakhani - an Iranian mathematician and the first woman to win the Fields Medal. https://en.wikipedia.org/wiki/Maryam_Mirzakhani - "mirzakhani", - - // Gordon Earle Moore - American engineer, Silicon Valley founding father, author of Moore's law. https://en.wikipedia.org/wiki/Gordon_Moore - "moore", - - // Samuel Morse - contributed to the invention of a single-wire telegraph system based on European telegraphs and was a co-developer of the Morse code - https://en.wikipedia.org/wiki/Samuel_Morse - "morse", - - // Ian Murdock - founder of the Debian project - https://en.wikipedia.org/wiki/Ian_Murdock - "murdock", - - // May-Britt Moser - Nobel prize winner neuroscientist who contributed to the discovery of grid cells in the brain. https://en.wikipedia.org/wiki/May-Britt_Moser - "moser", - - // John Napier of Merchiston - Scottish landowner known as an astronomer, mathematician and physicist. Best known for his discovery of logarithms. https://en.wikipedia.org/wiki/John_Napier - "napier", - - // John Forbes Nash, Jr. - American mathematician who made fundamental contributions to game theory, differential geometry, and the study of partial differential equations. https://en.wikipedia.org/wiki/John_Forbes_Nash_Jr. - "nash", - - // John von Neumann - todays computer architectures are based on the von Neumann architecture. https://en.wikipedia.org/wiki/Von_Neumann_architecture - "neumann", - - // Isaac Newton invented classic mechanics and modern optics. https://en.wikipedia.org/wiki/Isaac_Newton - "newton", - - // 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 silicone 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", - - // 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", - - // 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", - - // Dennis Ritchie - co-creator of UNIX and the C programming language. - https://en.wikipedia.org/wiki/Dennis_Ritchie - "ritchie", - - // Ida Rhodes - American pioneer in computer programming, designed the first computer used for Social Security. https://en.wikipedia.org/wiki/Ida_Rhodes - "rhodes", - - // Julia Hall Bowman Robinson - American mathematician renowned for her contributions to the fields of computability theory and computational complexity theory. https://en.wikipedia.org/wiki/Julia_Robinson - "robinson", - - // Wilhelm Conrad Röntgen - German physicist who was awarded the first Nobel Prize in Physics in 1901 for the discovery of X-rays (Röntgen rays). https://en.wikipedia.org/wiki/Wilhelm_R%C3%B6ntgen - "roentgen", - - // Rosalind Franklin - British biophysicist and X-ray crystallographer whose research was critical to the understanding of DNA - https://en.wikipedia.org/wiki/Rosalind_Franklin - "rosalind", - - // Vera Rubin - American astronomer who pioneered work on galaxy rotation rates. https://en.wikipedia.org/wiki/Vera_Rubin - "rubin", - - // Meghnad Saha - Indian astrophysicist best known for his development of the Saha equation, used to describe chemical and physical conditions in stars - https://en.wikipedia.org/wiki/Meghnad_Saha - "saha", - - // Jean E. Sammet developed FORMAC, the first widely used computer language for symbolic manipulation of mathematical formulas. https://en.wikipedia.org/wiki/Jean_E._Sammet - "sammet", - - // Mildred Sanderson - American mathematician best known for Sanderson's theorem concerning modular invariants. https://en.wikipedia.org/wiki/Mildred_Sanderson - "sanderson", - - // Satoshi Nakamoto is the name used by the unknown person or group of people who developed bitcoin, authored the bitcoin white paper, and created and deployed bitcoin's original reference implementation. https://en.wikipedia.org/wiki/Satoshi_Nakamoto - "satoshi", - - // Adi Shamir - Israeli cryptographer whose numerous inventions and contributions to cryptography include the Ferge Fiat Shamir identification scheme, the Rivest Shamir Adleman (RSA) public-key cryptosystem, the Shamir's secret sharing scheme, the breaking of the Merkle-Hellman cryptosystem, the TWINKLE and TWIRL factoring devices and the discovery of differential cryptanalysis (with Eli Biham). https://en.wikipedia.org/wiki/Adi_Shamir - "shamir", - - // Claude Shannon - The father of information theory and founder of digital circuit design theory. (https://en.wikipedia.org/wiki/Claude_Shannon) - "shannon", - - // Carol Shaw - Originally an Atari employee, Carol Shaw is said to be the first female video game designer. https://en.wikipedia.org/wiki/Carol_Shaw_(video_game_designer) - "shaw", - - // 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", - - // Richard Matthew Stallman - the founder of the Free Software movement, the GNU project, the Free Software Foundation, and the League for Programming Freedom. He also invented the concept of copyleft to protect the ideals of this movement, and enshrined this concept in the widely-used GPL (General Public License) for software. https://en.wikiquote.org/wiki/Richard_Stallman - "stallman", - - // 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", - - // Valentina Tereshkova is a Russian engineer, cosmonaut and politician. She was the first woman to fly to space in 1963. In 2013, at the age of 76, she offered to go on a one-way mission to Mars. https://en.wikipedia.org/wiki/Valentina_Tereshkova - "tereshkova", - - // Nikola Tesla invented the AC electric system and every gadget ever used by a James Bond villain. https://en.wikipedia.org/wiki/Nikola_Tesla - "tesla", - - // Marie Tharp - American geologist and oceanic cartographer who co-created the first scientific map of the Atlantic Ocean floor. Her work led to the acceptance of the theories of plate tectonics and continental drift. https://en.wikipedia.org/wiki/Marie_Tharp - "tharp", - - // Ken Thompson - co-creator of UNIX and the C programming language - https://en.wikipedia.org/wiki/Ken_Thompson - "thompson", - - // Linus Torvalds invented Linux and Git. https://en.wikipedia.org/wiki/Linus_Torvalds - "torvalds", - - // Youyou Tu - Chinese pharmaceutical chemist and educator known for discovering artemisinin and dihydroartemisinin, used to treat malaria, which has saved millions of lives. Joint winner of the 2015 Nobel Prize in Physiology or Medicine. https://en.wikipedia.org/wiki/Tu_Youyou - "tu", - - // Alan Turing was a founding father of computer science. https://en.wikipedia.org/wiki/Alan_Turing. - "turing", - - // 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", - - // 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", - - // 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", - - // 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 := fmt.Sprintf("%s_%s", left[rand.Intn(len(left))], right[rand.Intn(len(right))]) - if name == "boring_wozniak" /* Steve Wozniak is not boring */ { - goto begin - } - - if retry > 0 { - name = fmt.Sprintf("%s%d", name, rand.Intn(10)) - } - return name -} diff --git a/vendor/github.com/docker/docker/pkg/pools/pools.go b/vendor/github.com/docker/docker/pkg/pools/pools.go deleted file mode 100644 index 46339c282..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{} { return make([]byte, size) }, - }, - } -} - -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/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 7ca07dc64..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 5fe071d62..000000000 --- a/vendor/github.com/docker/docker/pkg/stringid/stringid.go +++ /dev/null @@ -1,63 +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" - "fmt" - "regexp" - "strconv" - "strings" -) - -const shortLen = 12 - -var ( - validShortID = regexp.MustCompile("^[a-f0-9]{12}$") - validHex = regexp.MustCompile(`^[a-f0-9]{64}$`) -) - -// IsShortID determines if an arbitrary string *looks like* a short ID. -func IsShortID(id string) bool { - 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 image ID. -func ValidateID(id string) error { - if ok := validHex.MatchString(id); !ok { - return fmt.Errorf("image ID %q is invalid", id) - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE deleted file mode 100644 index 5d80670bc..000000000 --- a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.APACHE +++ /dev/null @@ -1,191 +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 - - Copyright 2014-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 - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/pkg/symlink/LICENSE.BSD b/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD deleted file mode 100644 index 2ee8768d3..000000000 --- a/vendor/github.com/docker/docker/pkg/symlink/LICENSE.BSD +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2014-2018 The Docker & 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/docker/pkg/symlink/fs.go b/vendor/github.com/docker/docker/pkg/symlink/fs.go deleted file mode 100644 index 7b894cde7..000000000 --- a/vendor/github.com/docker/docker/pkg/symlink/fs.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE.BSD file. - -// This code is a modified version of path/filepath/symlink.go from the Go standard library. - -package symlink // import "github.com/docker/docker/pkg/symlink" - -import ( - "bytes" - "errors" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/system" -) - -// FollowSymlinkInScope is a wrapper around evalSymlinksInScope that returns an -// absolute path. This function handles paths in a platform-agnostic manner. -func FollowSymlinkInScope(path, root string) (string, error) { - path, err := filepath.Abs(filepath.FromSlash(path)) - if err != nil { - return "", err - } - root, err = filepath.Abs(filepath.FromSlash(root)) - if err != nil { - return "", err - } - return evalSymlinksInScope(path, root) -} - -// evalSymlinksInScope will evaluate symlinks in `path` within a scope `root` and return -// a result guaranteed to be contained within the scope `root`, at the time of the call. -// Symlinks in `root` are not evaluated and left as-is. -// Errors encountered while attempting to evaluate symlinks in path will be returned. -// Non-existing paths are valid and do not constitute an error. -// `path` has to contain `root` as a prefix, or else an error will be returned. -// Trying to break out from `root` does not constitute an error. -// -// Example: -// If /foo/bar -> /outside, -// FollowSymlinkInScope("/foo/bar", "/foo") == "/foo/outside" instead of "/outside" -// -// IMPORTANT: it is the caller's responsibility to call evalSymlinksInScope *after* relevant symlinks -// are created and not to create subsequently, additional symlinks that could potentially make a -// previously-safe path, unsafe. Example: if /foo/bar does not exist, evalSymlinksInScope("/foo/bar", "/foo") -// would return "/foo/bar". If one makes /foo/bar a symlink to /baz subsequently, then "/foo/bar" should -// no longer be considered safely contained in "/foo". -func evalSymlinksInScope(path, root string) (string, error) { - root = filepath.Clean(root) - if path == root { - return path, nil - } - if !strings.HasPrefix(path, root) { - return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) - } - const maxIter = 255 - originalPath := path - // given root of "/a" and path of "/a/b/../../c" we want path to be "/b/../../c" - path = path[len(root):] - if root == string(filepath.Separator) { - path = string(filepath.Separator) + path - } - if !strings.HasPrefix(path, string(filepath.Separator)) { - return "", errors.New("evalSymlinksInScope: " + path + " is not in " + root) - } - path = filepath.Clean(path) - // consume path by taking each frontmost path element, - // expanding it if it's a symlink, and appending it to b - var b bytes.Buffer - // b here will always be considered to be the "current absolute path inside - // root" when we append paths to it, we also append a slash and use - // filepath.Clean after the loop to trim the trailing slash - for n := 0; path != ""; n++ { - if n > maxIter { - return "", errors.New("evalSymlinksInScope: too many links in " + originalPath) - } - - // find next path component, p - i := strings.IndexRune(path, filepath.Separator) - var p string - if i == -1 { - p, path = path, "" - } else { - p, path = path[:i], path[i+1:] - } - - if p == "" { - continue - } - - // this takes a b.String() like "b/../" and a p like "c" and turns it - // into "/b/../c" which then gets filepath.Cleaned into "/c" and then - // root gets prepended and we Clean again (to remove any trailing slash - // if the first Clean gave us just "/") - cleanP := filepath.Clean(string(filepath.Separator) + b.String() + p) - if isDriveOrRoot(cleanP) { - // never Lstat "/" itself, or drive letters on Windows - b.Reset() - continue - } - fullP := filepath.Clean(root + cleanP) - - fi, err := os.Lstat(fullP) - if os.IsNotExist(err) { - // if p does not exist, accept it - b.WriteString(p) - b.WriteRune(filepath.Separator) - continue - } - if err != nil { - return "", err - } - if fi.Mode()&os.ModeSymlink == 0 { - b.WriteString(p) - b.WriteRune(filepath.Separator) - continue - } - - // it's a symlink, put it at the front of path - dest, err := os.Readlink(fullP) - if err != nil { - return "", err - } - if system.IsAbs(dest) { - b.Reset() - } - path = dest + string(filepath.Separator) + path - } - - // see note above on "fullP := ..." for why this is double-cleaned and - // what's happening here - return filepath.Clean(root + filepath.Clean(string(filepath.Separator)+b.String())), nil -} - -// EvalSymlinks returns the path name after the evaluation of any symbolic -// links. -// If path is relative the result will be relative to the current directory, -// unless one of the components is an absolute symbolic link. -// This version has been updated to support long paths prepended with `\\?\`. -func EvalSymlinks(path string) (string, error) { - return evalSymlinks(path) -} diff --git a/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go b/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go deleted file mode 100644 index c6dafcb0b..000000000 --- a/vendor/github.com/docker/docker/pkg/symlink/fs_unix.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !windows - -package symlink // import "github.com/docker/docker/pkg/symlink" - -import ( - "path/filepath" -) - -func evalSymlinks(path string) (string, error) { - return filepath.EvalSymlinks(path) -} - -func isDriveOrRoot(p string) bool { - return p == string(filepath.Separator) -} diff --git a/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go b/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go deleted file mode 100644 index 754761717..000000000 --- a/vendor/github.com/docker/docker/pkg/symlink/fs_windows.go +++ /dev/null @@ -1,169 +0,0 @@ -package symlink // import "github.com/docker/docker/pkg/symlink" - -import ( - "bytes" - "errors" - "os" - "path/filepath" - "strings" - - "github.com/docker/docker/pkg/longpath" - "golang.org/x/sys/windows" -) - -func toShort(path string) (string, error) { - p, err := windows.UTF16FromString(path) - if err != nil { - return "", err - } - b := p // GetShortPathName says we can reuse buffer - n, err := windows.GetShortPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - if n > uint32(len(b)) { - b = make([]uint16, n) - if _, err = windows.GetShortPathName(&p[0], &b[0], uint32(len(b))); err != nil { - return "", err - } - } - return windows.UTF16ToString(b), nil -} - -func toLong(path string) (string, error) { - p, err := windows.UTF16FromString(path) - if err != nil { - return "", err - } - b := p // GetLongPathName says we can reuse buffer - n, err := windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - if n > uint32(len(b)) { - b = make([]uint16, n) - n, err = windows.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - } - b = b[:n] - return windows.UTF16ToString(b), nil -} - -func evalSymlinks(path string) (string, error) { - path, err := walkSymlinks(path) - if err != nil { - return "", err - } - - p, err := toShort(path) - if err != nil { - return "", err - } - p, err = toLong(p) - if err != nil { - return "", err - } - // windows.GetLongPathName does not change the case of the drive letter, - // but the result of EvalSymlinks must be unique, so we have - // EvalSymlinks(`c:\a`) == EvalSymlinks(`C:\a`). - // Make drive letter upper case. - if len(p) >= 2 && p[1] == ':' && 'a' <= p[0] && p[0] <= 'z' { - p = string(p[0]+'A'-'a') + p[1:] - } else if len(p) >= 6 && p[5] == ':' && 'a' <= p[4] && p[4] <= 'z' { - p = p[:3] + string(p[4]+'A'-'a') + p[5:] - } - return filepath.Clean(p), nil -} - -const utf8RuneSelf = 0x80 - -func walkSymlinks(path string) (string, error) { - const maxIter = 255 - originalPath := path - // consume path by taking each frontmost path element, - // expanding it if it's a symlink, and appending it to b - var b bytes.Buffer - for n := 0; path != ""; n++ { - if n > maxIter { - return "", errors.New("EvalSymlinks: too many links in " + originalPath) - } - - // A path beginning with `\\?\` represents the root, so automatically - // skip that part and begin processing the next segment. - if strings.HasPrefix(path, longpath.Prefix) { - b.WriteString(longpath.Prefix) - path = path[4:] - continue - } - - // find next path component, p - var i = -1 - for j, c := range path { - if c < utf8RuneSelf && os.IsPathSeparator(uint8(c)) { - i = j - break - } - } - var p string - if i == -1 { - p, path = path, "" - } else { - p, path = path[:i], path[i+1:] - } - - if p == "" { - if b.Len() == 0 { - // must be absolute path - b.WriteRune(filepath.Separator) - } - continue - } - - // If this is the first segment after the long path prefix, accept the - // current segment as a volume root or UNC share and move on to the next. - if b.String() == longpath.Prefix { - b.WriteString(p) - b.WriteRune(filepath.Separator) - continue - } - - fi, err := os.Lstat(b.String() + p) - if err != nil { - return "", err - } - if fi.Mode()&os.ModeSymlink == 0 { - b.WriteString(p) - if path != "" || (b.Len() == 2 && len(p) == 2 && p[1] == ':') { - b.WriteRune(filepath.Separator) - } - continue - } - - // it's a symlink, put it at the front of path - dest, err := os.Readlink(b.String() + p) - if err != nil { - return "", err - } - if filepath.IsAbs(dest) || os.IsPathSeparator(dest[0]) { - b.Reset() - } - path = dest + string(filepath.Separator) + path - } - return filepath.Clean(b.String()), nil -} - -func isDriveOrRoot(p string) bool { - if p == string(filepath.Separator) { - return true - } - - length := len(p) - if length >= 2 { - if p[length-1] == ':' && (('a' <= p[length-2] && p[length-2] <= 'z') || ('A' <= p[length-2] && p[length-2] <= 'Z')) { - return true - } - } - return false -} 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 c26a4e24b..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes.go +++ /dev/null @@ -1,31 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "time" -) - -// Chtimes changes the access time and modified time of a file at the given path -func Chtimes(name string, atime time.Time, mtime time.Time) error { - unixMinTime := time.Unix(0, 0) - unixMaxTime := maxTime - - // If the modified time is prior to the Unix Epoch, or after the - // end of Unix Time, os.Chtimes has undefined behavior - // default to Unix Epoch in this case, just in case - - if atime.Before(unixMinTime) || atime.After(unixMaxTime) { - atime = unixMinTime - } - - if mtime.Before(unixMinTime) || mtime.After(unixMaxTime) { - mtime = unixMinTime - } - - 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_unix.go b/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go deleted file mode 100644 index 259138a45..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_unix.go +++ /dev/null @@ -1,14 +0,0 @@ -// +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 d3a115ff4..000000000 --- a/vendor/github.com/docker/docker/pkg/system/chtimes_windows.go +++ /dev/null @@ -1,26 +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 { - ctimespec := windows.NsecToTimespec(ctime.UnixNano()) - pathp, e := windows.UTF16PtrFromString(path) - if e != nil { - return e - } - h, e := windows.CreateFile(pathp, - windows.FILE_WRITE_ATTRIBUTES, windows.FILE_SHARE_WRITE, nil, - windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) - if e != nil { - return e - } - defer windows.Close(h) - c := windows.NsecToFiletime(windows.TimespecToNsec(ctimespec)) - 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/exitcode.go b/vendor/github.com/docker/docker/pkg/system/exitcode.go deleted file mode 100644 index 4ba8fe35b..000000000 --- a/vendor/github.com/docker/docker/pkg/system/exitcode.go +++ /dev/null @@ -1,19 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "os/exec" - "syscall" -) - -// 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") -} 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 adeb16305..000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys.go +++ /dev/null @@ -1,67 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "io/ioutil" - "os" - "path/filepath" -) - -// MkdirAllWithACL is a wrapper for MkdirAll on unix systems. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return MkdirAll(path, perm, sddl) -} - -// 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, sddl string) error { - return os.MkdirAll(path, perm) -} - -// IsAbs is a platform-specific wrapper for filepath.IsAbs. -func IsAbs(path string) bool { - return filepath.IsAbs(path) -} - -// The functions below here are wrappers for the equivalents in the os and ioutils packages. -// They are passthrough on Unix platforms, and only relevant on Windows. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return os.Create(name) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return os.Open(name) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. It opens the named file with specified flag -// (O_RDONLY etc.) and perm, (0666 etc.) if applicable. If successful, -// methods on the returned File can be used for I/O. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, perm os.FileMode) (*os.File, error) { - return os.OpenFile(name, flag, perm) -} - -// TempFileSequential creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *os.File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func TempFileSequential(dir, prefix string) (f *os.File, err error) { - return ioutil.TempFile(dir, prefix) -} 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 3049ff38a..000000000 --- a/vendor/github.com/docker/docker/pkg/system/filesys_windows.go +++ /dev/null @@ -1,294 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "path/filepath" - "regexp" - "strconv" - "strings" - "sync" - "syscall" - "time" - "unsafe" - - winio "github.com/Microsoft/go-winio" - "golang.org/x/sys/windows" -) - -const ( - // SddlAdministratorsLocalSystem is local administrators plus NT AUTHORITY\System - SddlAdministratorsLocalSystem = "D:P(A;OICI;GA;;;BA)(A;OICI;GA;;;SY)" -) - -// MkdirAllWithACL is a wrapper for MkdirAll that creates a directory -// with an appropriate SDDL defined ACL. -func MkdirAllWithACL(path string, perm os.FileMode, sddl string) error { - return mkdirall(path, true, sddl) -} - -// MkdirAll implementation that is volume path aware for Windows. -func MkdirAll(path string, _ os.FileMode, sddl string) error { - return mkdirall(path, false, sddl) -} - -// 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, applyACL bool, sddl string) error { - if re := regexp.MustCompile(`^\\\\\?\\Volume{[a-z0-9-]+}$`); re.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(path[0:j-1], false, sddl) - if err != nil { - return err - } - } - - // Parent now exists; invoke os.Mkdir or mkdirWithACL and use its result. - if applyACL { - err = mkdirWithACL(path, sddl) - } else { - err = os.Mkdir(path, 0) - } - - 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, sddl string) error { - sa := windows.SecurityAttributes{Length: 0} - sd, err := winio.SddlToSecurityDescriptor(sddl) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - sa.SecurityDescriptor = uintptr(unsafe.Pointer(&sd[0])) - - namep, err := windows.UTF16PtrFromString(name) - if err != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: err} - } - - e := windows.CreateDirectory(namep, &sa) - if e != nil { - return &os.PathError{Op: "mkdir", Path: name, Err: e} - } - return nil -} - -// IsAbs is a platform-specific 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 { - if !filepath.IsAbs(path) { - if !strings.HasPrefix(path, string(os.PathSeparator)) { - return false - } - } - return true -} - -// The origin of the functions below here are the golang OS and windows packages, -// slightly modified to only cope with files, not directories due to the -// specific use case. -// -// The alteration is to allow a file on Windows to be opened with -// FILE_FLAG_SEQUENTIAL_SCAN (particular for docker load), to avoid eating -// the standby list, particularly when accessing large files such as layer.tar. - -// CreateSequential creates the named file with mode 0666 (before umask), truncating -// it if it already exists. If successful, methods on the returned -// File can be used for I/O; the associated file descriptor has mode -// O_RDWR. -// If there is an error, it will be of type *PathError. -func CreateSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0) -} - -// OpenSequential opens the named file for reading. If successful, methods on -// the returned file can be used for reading; the associated file -// descriptor has mode O_RDONLY. -// If there is an error, it will be of type *PathError. -func OpenSequential(name string) (*os.File, error) { - return OpenFileSequential(name, os.O_RDONLY, 0) -} - -// OpenFileSequential is the generalized open call; most users will use Open -// or Create instead. -// If there is an error, it will be of type *PathError. -func OpenFileSequential(name string, flag int, _ os.FileMode) (*os.File, error) { - if name == "" { - return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOENT} - } - r, errf := windowsOpenFileSequential(name, flag, 0) - if errf == nil { - return r, nil - } - return nil, &os.PathError{Op: "open", Path: name, Err: errf} -} - -func windowsOpenFileSequential(name string, flag int, _ os.FileMode) (file *os.File, err error) { - r, e := windowsOpenSequential(name, flag|windows.O_CLOEXEC, 0) - if e != nil { - return nil, e - } - return os.NewFile(uintptr(r), name), nil -} - -func makeInheritSa() *windows.SecurityAttributes { - var sa windows.SecurityAttributes - sa.Length = uint32(unsafe.Sizeof(sa)) - sa.InheritHandle = 1 - return &sa -} - -func windowsOpenSequential(path string, mode int, _ uint32) (fd windows.Handle, err error) { - if len(path) == 0 { - return windows.InvalidHandle, windows.ERROR_FILE_NOT_FOUND - } - pathp, err := windows.UTF16PtrFromString(path) - if err != nil { - return windows.InvalidHandle, err - } - var access uint32 - switch mode & (windows.O_RDONLY | windows.O_WRONLY | windows.O_RDWR) { - case windows.O_RDONLY: - access = windows.GENERIC_READ - case windows.O_WRONLY: - access = windows.GENERIC_WRITE - case windows.O_RDWR: - access = windows.GENERIC_READ | windows.GENERIC_WRITE - } - if mode&windows.O_CREAT != 0 { - access |= windows.GENERIC_WRITE - } - if mode&windows.O_APPEND != 0 { - access &^= windows.GENERIC_WRITE - access |= windows.FILE_APPEND_DATA - } - sharemode := uint32(windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE) - var sa *windows.SecurityAttributes - if mode&windows.O_CLOEXEC == 0 { - sa = makeInheritSa() - } - var createmode uint32 - switch { - case mode&(windows.O_CREAT|windows.O_EXCL) == (windows.O_CREAT | windows.O_EXCL): - createmode = windows.CREATE_NEW - case mode&(windows.O_CREAT|windows.O_TRUNC) == (windows.O_CREAT | windows.O_TRUNC): - createmode = windows.CREATE_ALWAYS - case mode&windows.O_CREAT == windows.O_CREAT: - createmode = windows.OPEN_ALWAYS - case mode&windows.O_TRUNC == windows.O_TRUNC: - createmode = windows.TRUNCATE_EXISTING - default: - createmode = windows.OPEN_EXISTING - } - // Use FILE_FLAG_SEQUENTIAL_SCAN rather than FILE_ATTRIBUTE_NORMAL as implemented in golang. - //https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx - const fileFlagSequentialScan = 0x08000000 // FILE_FLAG_SEQUENTIAL_SCAN - h, e := windows.CreateFile(pathp, access, sharemode, sa, createmode, fileFlagSequentialScan, 0) - return h, e -} - -// Helpers for TempFileSequential -var rand uint32 -var randmu sync.Mutex - -func reseed() uint32 { - return uint32(time.Now().UnixNano() + int64(os.Getpid())) -} -func nextSuffix() string { - randmu.Lock() - r := rand - if r == 0 { - r = reseed() - } - r = r*1664525 + 1013904223 // constants from Numerical Recipes - rand = r - randmu.Unlock() - return strconv.Itoa(int(1e9 + r%1e9))[1:] -} - -// TempFileSequential is a copy of ioutil.TempFile, modified to use sequential -// file access. Below is the original comment from golang: -// TempFile creates a new temporary file in the directory dir -// with a name beginning with prefix, opens the file for reading -// and writing, and returns the resulting *os.File. -// If dir is the empty string, TempFile uses the default directory -// for temporary files (see os.TempDir). -// Multiple programs calling TempFile simultaneously -// will not choose the same file. The caller can use f.Name() -// to find the pathname of the file. It is the caller's responsibility -// to remove the file when no longer needed. -func TempFileSequential(dir, prefix string) (f *os.File, err error) { - if dir == "" { - dir = os.TempDir() - } - - nconflict := 0 - for i := 0; i < 10000; i++ { - name := filepath.Join(dir, prefix+nextSuffix()) - f, err = OpenFileSequential(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600) - if os.IsExist(err) { - if nconflict++; nconflict > 10 { - randmu.Lock() - rand = reseed() - randmu.Unlock() - } - continue - } - break - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/system/init.go b/vendor/github.com/docker/docker/pkg/system/init.go deleted file mode 100644 index a17597aab..000000000 --- a/vendor/github.com/docker/docker/pkg/system/init.go +++ /dev/null @@ -1,22 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "time" - "unsafe" -) - -// Used by chtimes -var maxTime time.Time - -func init() { - // chtimes initialization - if unsafe.Sizeof(syscall.Timespec{}.Nsec) == 8 { - // This is a 64 bit timespec - // os.Chtimes limits time to the following - maxTime = time.Unix(0, 1<<63-1) - } else { - // This is a 32 bit timespec - maxTime = time.Unix(1<<31-1, 0) - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/init_unix.go b/vendor/github.com/docker/docker/pkg/system/init_unix.go deleted file mode 100644 index c2bb0f4cc..000000000 --- a/vendor/github.com/docker/docker/pkg/system/init_unix.go +++ /dev/null @@ -1,12 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -// InitLCOW does nothing since LCOW is a windows only feature -func InitLCOW(experimental bool) { -} - -// ContainerdRuntimeSupported returns true if the use of ContainerD runtime is supported. -func ContainerdRuntimeSupported(_ bool, _ string) bool { - return true -} 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 f303aa906..000000000 --- a/vendor/github.com/docker/docker/pkg/system/init_windows.go +++ /dev/null @@ -1,41 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - - "github.com/Microsoft/hcsshim/osversion" - "github.com/sirupsen/logrus" -) - -var ( - // lcowSupported determines if Linux Containers on Windows are supported. - lcowSupported = false - - // containerdRuntimeSupported determines if ContainerD should be the runtime. - // As of March 2019, this is an experimental feature. - containerdRuntimeSupported = false -) - -// InitLCOW sets whether LCOW is supported or not. Requires RS5+ -func InitLCOW(experimental bool) { - v := GetOSVersion() - if experimental && v.Build >= osversion.RS5 { - lcowSupported = true - } -} - -// InitContainerdRuntime sets whether to use ContainerD for runtime -// on Windows. This is an experimental feature still in development, and -// also requires an environment variable to be set (so as not to turn the -// feature on from simply experimental which would also mean LCOW. -func InitContainerdRuntime(experimental bool, cdPath string) { - if experimental && len(cdPath) > 0 && len(os.Getenv("DOCKER_WINDOWS_CONTAINERD_RUNTIME")) > 0 { - logrus.Warnf("Using ContainerD runtime. This feature is experimental") - 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/lcow.go b/vendor/github.com/docker/docker/pkg/system/lcow.go deleted file mode 100644 index 5be3e2182..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lcow.go +++ /dev/null @@ -1,32 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "runtime" - "strings" - - specs "github.com/opencontainers/image-spec/specs-go/v1" - "github.com/pkg/errors" -) - -// IsOSSupported determines if an operating system is supported by the host -func IsOSSupported(os string) bool { - if strings.EqualFold(runtime.GOOS, os) { - return true - } - if LCOWSupported() && strings.EqualFold(os, "linux") { - return true - } - return false -} - -// ValidatePlatform determines if a platform structure is valid. -// TODO This is a temporary windows-only function, should be replaced by -// comparison of worker capabilities -func ValidatePlatform(platform specs.Platform) error { - if runtime.GOOS == "windows" { - if !(platform.OS == runtime.GOOS || (LCOWSupported() && platform.OS == "linux")) { - return errors.Errorf("unsupported os %s", platform.OS) - } - } - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/lcow_unix.go b/vendor/github.com/docker/docker/pkg/system/lcow_unix.go deleted file mode 100644 index 26397fb8a..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lcow_unix.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -// LCOWSupported returns true if Linux containers on Windows are supported. -func LCOWSupported() bool { - return false -} diff --git a/vendor/github.com/docker/docker/pkg/system/lcow_windows.go b/vendor/github.com/docker/docker/pkg/system/lcow_windows.go deleted file mode 100644 index f0139df8f..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lcow_windows.go +++ /dev/null @@ -1,6 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// LCOWSupported returns true if Linux containers on Windows are supported. -func LCOWSupported() bool { - return lcowSupported -} 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 de5a1c0fb..000000000 --- a/vendor/github.com/docker/docker/pkg/system/lstat_unix.go +++ /dev/null @@ -1,20 +0,0 @@ -// +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.go b/vendor/github.com/docker/docker/pkg/system/meminfo.go deleted file mode 100644 index 6667eb84d..000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo.go +++ /dev/null @@ -1,17 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// MemInfo contains memory statistics of the host system. -type MemInfo 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/system/meminfo_linux.go b/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go deleted file mode 100644 index d79e8b076..000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_linux.go +++ /dev/null @@ -1,65 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "bufio" - "io" - "os" - "strconv" - "strings" - - "github.com/docker/go-units" -) - -// ReadMemInfo retrieves memory statistics of the host system and returns a -// MemInfo type. -func ReadMemInfo() (*MemInfo, 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 MemInfo object given an io.Reader to the file. -// Throws error if there are problems reading from the file -func parseMemInfo(reader io.Reader) (*MemInfo, error) { - meminfo := &MemInfo{} - scanner := bufio.NewScanner(reader) - 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 - } - bytes := int64(size) * units.KiB - - switch parts[0] { - case "MemTotal:": - meminfo.MemTotal = bytes - case "MemFree:": - meminfo.MemFree = bytes - case "SwapTotal:": - meminfo.SwapTotal = bytes - case "SwapFree:": - meminfo.SwapFree = bytes - } - - } - - // 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/system/meminfo_unsupported.go b/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go deleted file mode 100644 index 56f449426..000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_unsupported.go +++ /dev/null @@ -1,8 +0,0 @@ -// +build !linux,!windows - -package system // import "github.com/docker/docker/pkg/system" - -// ReadMemInfo is not supported on platforms other than linux and windows. -func ReadMemInfo() (*MemInfo, error) { - return nil, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go b/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go deleted file mode 100644 index 6ed93f2fe..000000000 --- a/vendor/github.com/docker/docker/pkg/system/meminfo_windows.go +++ /dev/null @@ -1,45 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -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 -// MemInfo type. -func ReadMemInfo() (*MemInfo, error) { - msi := &memorystatusex{ - dwLength: 64, - } - r1, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(msi))) - if r1 == 0 { - return &MemInfo{}, nil - } - return &MemInfo{ - 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/system/mknod.go b/vendor/github.com/docker/docker/pkg/system/mknod.go deleted file mode 100644 index b132482e0..000000000 --- a/vendor/github.com/docker/docker/pkg/system/mknod.go +++ /dev/null @@ -1,22 +0,0 @@ -// +build !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) -} - -// 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_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.go b/vendor/github.com/docker/docker/pkg/system/path.go deleted file mode 100644 index a3d957afa..000000000 --- a/vendor/github.com/docker/docker/pkg/system/path.go +++ /dev/null @@ -1,60 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "path/filepath" - "runtime" - "strings" - - "github.com/containerd/continuity/pathdriver" -) - -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 . -func DefaultPathEnv(os string) string { - if runtime.GOOS == "windows" { - if os != runtime.GOOS { - return defaultUnixPathEnv - } - // Deliberately empty on Windows containers on Windows as the default path will be set by - // the container. Docker has no context of what the default path should be. - return "" - } - return defaultUnixPathEnv - -} - -// 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, driver pathdriver.PathDriver) (string, error) { - if runtime.GOOS != "windows" || LCOWSupported() { - return path, nil - } - - if len(path) == 2 && string(path[1]) == ":" { - return "", fmt.Errorf("No relative path specified in %q", path) - } - if !driver.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/system/path_unix.go b/vendor/github.com/docker/docker/pkg/system/path_unix.go deleted file mode 100644 index b0b93196a..000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_unix.go +++ /dev/null @@ -1,10 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - return path, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/path_windows.go b/vendor/github.com/docker/docker/pkg/system/path_windows.go deleted file mode 100644 index 188f2c295..000000000 --- a/vendor/github.com/docker/docker/pkg/system/path_windows.go +++ /dev/null @@ -1,24 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "syscall" - -// GetLongPathName converts Windows short pathnames to full pathnames. -// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. -// It is a no-op on non-Windows platforms -func GetLongPathName(path string) (string, error) { - // See https://groups.google.com/forum/#!topic/golang-dev/1tufzkruoTg - p := syscall.StringToUTF16(path) - b := p // GetLongPathName says we can reuse buffer - n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - if n > uint32(len(b)) { - b = make([]uint16, n) - _, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) - if err != nil { - return "", err - } - } - return syscall.UTF16ToString(b), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_unix.go b/vendor/github.com/docker/docker/pkg/system/process_unix.go deleted file mode 100644 index 0195a891b..000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_unix.go +++ /dev/null @@ -1,24 +0,0 @@ -// +build linux freebsd darwin - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - - "golang.org/x/sys/unix" -) - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - err := unix.Kill(pid, syscall.Signal(0)) - if err == nil || err == unix.EPERM { - return true - } - - return false -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - unix.Kill(pid, unix.SIGKILL) -} diff --git a/vendor/github.com/docker/docker/pkg/system/process_windows.go b/vendor/github.com/docker/docker/pkg/system/process_windows.go deleted file mode 100644 index 4e70c97b1..000000000 --- a/vendor/github.com/docker/docker/pkg/system/process_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import "os" - -// IsProcessAlive returns true if process with a given pid is running. -func IsProcessAlive(pid int) bool { - _, err := os.FindProcess(pid) - - return err == nil -} - -// KillProcess force-stops a process. -func KillProcess(pid int) { - p, err := os.FindProcess(pid) - if err == nil { - p.Kill() - } -} diff --git a/vendor/github.com/docker/docker/pkg/system/rm.go b/vendor/github.com/docker/docker/pkg/system/rm.go deleted file mode 100644 index b31099180..000000000 --- a/vendor/github.com/docker/docker/pkg/system/rm.go +++ /dev/null @@ -1,80 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "os" - "syscall" - "time" - - "github.com/docker/docker/pkg/mount" - "github.com/pkg/errors" -) - -// EnsureRemoveAll wraps `os.RemoveAll` to check for specific errors that can -// often be remedied. -// Only use `EnsureRemoveAll` if you really want to make every effort to remove -// a directory. -// -// Because of the way `os.Remove` (and by extension `os.RemoveAll`) works, there -// can be a race between reading directory entries and then actually attempting -// to remove everything in the directory. -// These types of errors do not need to be returned since it's ok for the dir to -// be gone we can just retry the remove operation. -// -// This should not return a `os.ErrNotExist` kind of error under any circumstances -func EnsureRemoveAll(dir string) error { - notExistErr := make(map[string]bool) - - // track retries - exitOnErr := make(map[string]int) - maxRetry := 50 - - // Attempt to unmount anything beneath this dir first - mount.RecursiveUnmount(dir) - - for { - err := os.RemoveAll(dir) - if err == nil { - return nil - } - - pe, ok := err.(*os.PathError) - if !ok { - return err - } - - if os.IsNotExist(err) { - if notExistErr[pe.Path] { - return err - } - notExistErr[pe.Path] = true - - // There is a race where some subdir can be removed but after the parent - // dir entries have been read. - // So the path could be from `os.Remove(subdir)` - // If the reported non-existent path is not the passed in `dir` we - // should just retry, but otherwise return with no error. - if pe.Path == dir { - return nil - } - continue - } - - if pe.Err != syscall.EBUSY { - return err - } - - if mounted, _ := mount.Mounted(pe.Path); mounted { - if e := mount.Unmount(pe.Path); e != nil { - if mounted, _ := mount.Mounted(pe.Path); mounted { - return errors.Wrapf(e, "error while removing %s", dir) - } - } - } - - if exitOnErr[pe.Path] == maxRetry { - return err - } - exitOnErr[pe.Path]++ - time.Sleep(100 * time.Millisecond) - } -} 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_freebsd.go b/vendor/github.com/docker/docker/pkg/system/stat_freebsd.go deleted file mode 100644 index c1c0ee9f3..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_freebsd.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 98c9eb18d..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_linux.go +++ /dev/null @@ -1,19 +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, - rdev: s.Rdev, - 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_solaris.go b/vendor/github.com/docker/docker/pkg/system/stat_solaris.go deleted file mode 100644 index 756b92d1e..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_solaris.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 86bb6dd55..000000000 --- a/vendor/github.com/docker/docker/pkg/system/stat_unix.go +++ /dev/null @@ -1,66 +0,0 @@ -// +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 b2456cb88..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 os.FileMode(s.mode) -} - -// Mtim returns file's last modification time. -func (s StatT) Mtim() time.Time { - return time.Time(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/syscall_unix.go b/vendor/github.com/docker/docker/pkg/system/syscall_unix.go deleted file mode 100644 index 919a412a7..000000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_unix.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build linux freebsd - -package system // import "github.com/docker/docker/pkg/system" - -import "golang.org/x/sys/unix" - -// Unmount is a platform-specific helper function to call -// the unmount syscall. -func Unmount(dest string) error { - return unix.Unmount(dest, 0) -} - -// CommandLineToArgv should not be used on Unix. -// It simply returns commandLine in the only element in the returned array. -func CommandLineToArgv(commandLine string) ([]string, error) { - return []string{commandLine}, nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go b/vendor/github.com/docker/docker/pkg/system/syscall_windows.go deleted file mode 100644 index 4ae92fa6c..000000000 --- a/vendor/github.com/docker/docker/pkg/system/syscall_windows.go +++ /dev/null @@ -1,193 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "fmt" - "syscall" - "unsafe" - - "github.com/sirupsen/logrus" - "golang.org/x/sys/windows" -) - -const ( - OWNER_SECURITY_INFORMATION = 0x00000001 - GROUP_SECURITY_INFORMATION = 0x00000002 - DACL_SECURITY_INFORMATION = 0x00000004 - SACL_SECURITY_INFORMATION = 0x00000008 - LABEL_SECURITY_INFORMATION = 0x00000010 - ATTRIBUTE_SECURITY_INFORMATION = 0x00000020 - SCOPE_SECURITY_INFORMATION = 0x00000040 - PROCESS_TRUST_LABEL_SECURITY_INFORMATION = 0x00000080 - ACCESS_FILTER_SECURITY_INFORMATION = 0x00000100 - BACKUP_SECURITY_INFORMATION = 0x00010000 - PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000 - PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000 - UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000 - UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000 -) - -const ( - SE_UNKNOWN_OBJECT_TYPE = iota - SE_FILE_OBJECT - SE_SERVICE - SE_PRINTER - SE_REGISTRY_KEY - SE_LMSHARE - SE_KERNEL_OBJECT - SE_WINDOW_OBJECT - SE_DS_OBJECT - SE_DS_OBJECT_ALL - SE_PROVIDER_DEFINED_OBJECT - SE_WMIGUID_OBJECT - SE_REGISTRY_WOW64_32KEY -) - -const ( - SeTakeOwnershipPrivilege = "SeTakeOwnershipPrivilege" -) - -const ( - ContainerAdministratorSidString = "S-1-5-93-2-1" - ContainerUserSidString = "S-1-5-93-2-2" -) - -var ( - ntuserApiset = windows.NewLazyDLL("ext-ms-win-ntuser-window-l1-1-0") - modadvapi32 = windows.NewLazySystemDLL("advapi32.dll") - procGetVersionExW = modkernel32.NewProc("GetVersionExW") - procGetProductInfo = modkernel32.NewProc("GetProductInfo") - procSetNamedSecurityInfo = modadvapi32.NewProc("SetNamedSecurityInfoW") - procGetSecurityDescriptorDacl = modadvapi32.NewProc("GetSecurityDescriptorDacl") -) - -// 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 -} - -// https://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx -type osVersionInfoEx struct { - OSVersionInfoSize uint32 - MajorVersion uint32 - MinorVersion uint32 - BuildNumber uint32 - PlatformID uint32 - CSDVersion [128]uint16 - ServicePackMajor uint16 - ServicePackMinor uint16 - SuiteMask uint16 - ProductType byte - Reserve byte -} - -// GetOSVersion gets the operating system version on Windows. Note that -// docker.exe must be manifested to get the correct version information. -func GetOSVersion() OSVersion { - 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 -} - -func (osv OSVersion) ToString() string { - return fmt.Sprintf("%d.%d.%d", osv.MajorVersion, osv.MinorVersion, osv.Build) -} - -// IsWindowsClient returns true if the SKU is client -// @engine maintainers - this function should not be removed or modified as it -// is used to enforce licensing restrictions on Windows. -func IsWindowsClient() bool { - osviex := &osVersionInfoEx{OSVersionInfoSize: 284} - r1, _, err := procGetVersionExW.Call(uintptr(unsafe.Pointer(osviex))) - if r1 == 0 { - logrus.Warnf("GetVersionExW failed - assuming server SKU: %v", err) - return false - } - const verNTWorkstation = 0x00000001 - return osviex.ProductType == verNTWorkstation -} - -// IsIoTCore returns true if the currently running image is based off of -// Windows 10 IoT Core. -// @engine maintainers - this function should not be removed or modified as it -// is used to enforce licensing restrictions on Windows. -func IsIoTCore() bool { - var returnedProductType uint32 - r1, _, err := procGetProductInfo.Call(6, 1, 0, 0, uintptr(unsafe.Pointer(&returnedProductType))) - if r1 == 0 { - logrus.Warnf("GetProductInfo failed - assuming this is not IoT: %v", err) - return false - } - const productIoTUAP = 0x0000007B - const productIoTUAPCommercial = 0x00000083 - return returnedProductType == productIoTUAP || returnedProductType == productIoTUAPCommercial -} - -// Unmount is a platform-specific helper function to call -// the unmount syscall. Not supported on Windows -func Unmount(dest string) error { - return nil -} - -// CommandLineToArgv wraps the Windows syscall to turn a commandline into an argument array. -func CommandLineToArgv(commandLine string) ([]string, error) { - var argc int32 - - argsPtr, err := windows.UTF16PtrFromString(commandLine) - if err != nil { - return nil, err - } - - argv, err := windows.CommandLineToArgv(argsPtr, &argc) - if err != nil { - return nil, err - } - defer windows.LocalFree(windows.Handle(uintptr(unsafe.Pointer(argv)))) - - newArgs := make([]string, argc) - for i, v := range (*argv)[:argc] { - newArgs[i] = string(windows.UTF16ToString((*v)[:])) - } - - return newArgs, nil -} - -// HasWin32KSupport determines whether containers that depend on win32k can -// run on this machine. Win32k is the driver used to implement windowing. -func HasWin32KSupport() bool { - // For now, check for ntuser API support on the host. In the future, a host - // may support win32k in containers even if the host does not support ntuser - // APIs. - return ntuserApiset.Load() == nil -} - -func SetNamedSecurityInfo(objectName *uint16, objectType uint32, securityInformation uint32, sidOwner *windows.SID, sidGroup *windows.SID, dacl *byte, sacl *byte) (result error) { - r0, _, _ := syscall.Syscall9(procSetNamedSecurityInfo.Addr(), 7, uintptr(unsafe.Pointer(objectName)), uintptr(objectType), uintptr(securityInformation), uintptr(unsafe.Pointer(sidOwner)), uintptr(unsafe.Pointer(sidGroup)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(sacl)), 0, 0) - if r0 != 0 { - result = syscall.Errno(r0) - } - return -} - -func GetSecurityDescriptorDacl(securityDescriptor *byte, daclPresent *uint32, dacl **byte, daclDefaulted *uint32) (result error) { - r1, _, e1 := syscall.Syscall6(procGetSecurityDescriptorDacl.Addr(), 4, uintptr(unsafe.Pointer(securityDescriptor)), uintptr(unsafe.Pointer(daclPresent)), uintptr(unsafe.Pointer(dacl)), uintptr(unsafe.Pointer(daclDefaulted)), 0, 0) - if r1 == 0 { - if e1 != 0 { - result = syscall.Errno(e1) - } else { - result = syscall.EINVAL - } - } - return -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask.go b/vendor/github.com/docker/docker/pkg/system/umask.go deleted file mode 100644 index 9912a2bab..000000000 --- a/vendor/github.com/docker/docker/pkg/system/umask.go +++ /dev/null @@ -1,13 +0,0 @@ -// +build !windows - -package system // import "github.com/docker/docker/pkg/system" - -import ( - "golang.org/x/sys/unix" -) - -// Umask sets current process's file mode creation mask to newmask -// and returns oldmask. -func Umask(newmask int) (oldmask int, err error) { - return unix.Umask(newmask), nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/umask_windows.go b/vendor/github.com/docker/docker/pkg/system/umask_windows.go deleted file mode 100644 index fc62388c3..000000000 --- a/vendor/github.com/docker/docker/pkg/system/umask_windows.go +++ /dev/null @@ -1,7 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -// Umask is not supported on the windows platform. -func Umask(newmask int) (oldmask int, err error) { - // should not be called on cli code path - return 0, ErrNotSupportedPlatform -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go b/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go deleted file mode 100644 index ed1b9fad5..000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_freebsd.go +++ /dev/null @@ -1,24 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "unsafe" - - "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 { - var _path *byte - _path, err := unix.BytePtrFromString(path) - if err != nil { - return err - } - - if _, _, err := unix.Syscall(unix.SYS_LUTIMES, uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), 0); err != 0 && err != unix.ENOSYS { - return err - } - - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/system/utimes_linux.go b/vendor/github.com/docker/docker/pkg/system/utimes_linux.go deleted file mode 100644 index 0afe85458..000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_linux.go +++ /dev/null @@ -1,25 +0,0 @@ -package system // import "github.com/docker/docker/pkg/system" - -import ( - "syscall" - "unsafe" - - "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 { - atFdCwd := unix.AT_FDCWD - - var _path *byte - _path, err := unix.BytePtrFromString(path) - if err != nil { - return err - } - if _, _, err := unix.Syscall6(unix.SYS_UTIMENSAT, uintptr(atFdCwd), uintptr(unsafe.Pointer(_path)), uintptr(unsafe.Pointer(&ts[0])), unix.AT_SYMLINK_NOFOLLOW, 0, 0); err != 0 && 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 095e072e1..000000000 --- a/vendor/github.com/docker/docker/pkg/system/utimes_unsupported.go +++ /dev/null @@ -1,10 +0,0 @@ -// +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 66d4895b2..000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_linux.go +++ /dev/null @@ -1,29 +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) { - dest := make([]byte, 128) - sz, errno := unix.Lgetxattr(path, attr, dest) - if errno == unix.ENODATA { - return nil, nil - } - if errno == unix.ERANGE { - dest = make([]byte, sz) - sz, errno = unix.Lgetxattr(path, attr, dest) - } - if 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 d780a90cd..000000000 --- a/vendor/github.com/docker/docker/pkg/system/xattrs_unsupported.go +++ /dev/null @@ -1,13 +0,0 @@ -// +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/pkg/tarsum/builder_context.go b/vendor/github.com/docker/docker/pkg/tarsum/builder_context.go deleted file mode 100644 index bc7d84df4..000000000 --- a/vendor/github.com/docker/docker/pkg/tarsum/builder_context.go +++ /dev/null @@ -1,21 +0,0 @@ -package tarsum // import "github.com/docker/docker/pkg/tarsum" - -// BuilderContext is an interface extending TarSum by adding the Remove method. -// In general there was concern about adding this method to TarSum itself -// so instead it is being added just to "BuilderContext" which will then -// only be used during the .dockerignore file processing -// - see builder/evaluator.go -type BuilderContext interface { - TarSum - Remove(string) -} - -func (bc *tarSum) Remove(filename string) { - for i, fis := range bc.sums { - if fis.Name() == filename { - bc.sums = append(bc.sums[:i], bc.sums[i+1:]...) - // Note, we don't just return because there could be - // more than one with this name - } - } -} diff --git a/vendor/github.com/docker/docker/pkg/tarsum/fileinfosums.go b/vendor/github.com/docker/docker/pkg/tarsum/fileinfosums.go deleted file mode 100644 index 01d4ed59b..000000000 --- a/vendor/github.com/docker/docker/pkg/tarsum/fileinfosums.go +++ /dev/null @@ -1,133 +0,0 @@ -package tarsum // import "github.com/docker/docker/pkg/tarsum" - -import ( - "runtime" - "sort" - "strings" -) - -// FileInfoSumInterface provides an interface for accessing file checksum -// information within a tar file. This info is accessed through interface -// so the actual name and sum cannot be melded with. -type FileInfoSumInterface interface { - // File name - Name() string - // Checksum of this particular file and its headers - Sum() string - // Position of file in the tar - Pos() int64 -} - -type fileInfoSum struct { - name string - sum string - pos int64 -} - -func (fis fileInfoSum) Name() string { - return fis.name -} -func (fis fileInfoSum) Sum() string { - return fis.sum -} -func (fis fileInfoSum) Pos() int64 { - return fis.pos -} - -// FileInfoSums provides a list of FileInfoSumInterfaces. -type FileInfoSums []FileInfoSumInterface - -// GetFile returns the first FileInfoSumInterface with a matching name. -func (fis FileInfoSums) GetFile(name string) FileInfoSumInterface { - // We do case insensitive matching on Windows as c:\APP and c:\app are - // the same. See issue #33107. - for i := range fis { - if (runtime.GOOS == "windows" && strings.EqualFold(fis[i].Name(), name)) || - (runtime.GOOS != "windows" && fis[i].Name() == name) { - return fis[i] - } - } - return nil -} - -// GetAllFile returns a FileInfoSums with all matching names. -func (fis FileInfoSums) GetAllFile(name string) FileInfoSums { - f := FileInfoSums{} - for i := range fis { - if fis[i].Name() == name { - f = append(f, fis[i]) - } - } - return f -} - -// GetDuplicatePaths returns a FileInfoSums with all duplicated paths. -func (fis FileInfoSums) GetDuplicatePaths() (dups FileInfoSums) { - seen := make(map[string]int, len(fis)) // allocate earl. no need to grow this map. - for i := range fis { - f := fis[i] - if _, ok := seen[f.Name()]; ok { - dups = append(dups, f) - } else { - seen[f.Name()] = 0 - } - } - return dups -} - -// Len returns the size of the FileInfoSums. -func (fis FileInfoSums) Len() int { return len(fis) } - -// Swap swaps two FileInfoSum values if a FileInfoSums list. -func (fis FileInfoSums) Swap(i, j int) { fis[i], fis[j] = fis[j], fis[i] } - -// SortByPos sorts FileInfoSums content by position. -func (fis FileInfoSums) SortByPos() { - sort.Sort(byPos{fis}) -} - -// SortByNames sorts FileInfoSums content by name. -func (fis FileInfoSums) SortByNames() { - sort.Sort(byName{fis}) -} - -// SortBySums sorts FileInfoSums content by sums. -func (fis FileInfoSums) SortBySums() { - dups := fis.GetDuplicatePaths() - if len(dups) > 0 { - sort.Sort(bySum{fis, dups}) - } else { - sort.Sort(bySum{fis, nil}) - } -} - -// byName is a sort.Sort helper for sorting by file names. -// If names are the same, order them by their appearance in the tar archive -type byName struct{ FileInfoSums } - -func (bn byName) Less(i, j int) bool { - if bn.FileInfoSums[i].Name() == bn.FileInfoSums[j].Name() { - return bn.FileInfoSums[i].Pos() < bn.FileInfoSums[j].Pos() - } - return bn.FileInfoSums[i].Name() < bn.FileInfoSums[j].Name() -} - -// bySum is a sort.Sort helper for sorting by the sums of all the fileinfos in the tar archive -type bySum struct { - FileInfoSums - dups FileInfoSums -} - -func (bs bySum) Less(i, j int) bool { - if bs.dups != nil && bs.FileInfoSums[i].Name() == bs.FileInfoSums[j].Name() { - return bs.FileInfoSums[i].Pos() < bs.FileInfoSums[j].Pos() - } - return bs.FileInfoSums[i].Sum() < bs.FileInfoSums[j].Sum() -} - -// byPos is a sort.Sort helper for sorting by the sums of all the fileinfos by their original order -type byPos struct{ FileInfoSums } - -func (bp byPos) Less(i, j int) bool { - return bp.FileInfoSums[i].Pos() < bp.FileInfoSums[j].Pos() -} diff --git a/vendor/github.com/docker/docker/pkg/tarsum/tarsum.go b/vendor/github.com/docker/docker/pkg/tarsum/tarsum.go deleted file mode 100644 index 5542e1b2c..000000000 --- a/vendor/github.com/docker/docker/pkg/tarsum/tarsum.go +++ /dev/null @@ -1,301 +0,0 @@ -// Package tarsum provides algorithms to perform checksum calculation on -// filesystem layers. -// -// The transportation of filesystems, regarding Docker, is done with tar(1) -// archives. There are a variety of tar serialization formats [2], and a key -// concern here is ensuring a repeatable checksum given a set of inputs from a -// generic tar archive. Types of transportation include distribution to and from a -// registry endpoint, saving and loading through commands or Docker daemon APIs, -// transferring the build context from client to Docker daemon, and committing the -// filesystem of a container to become an image. -// -// As tar archives are used for transit, but not preserved in many situations, the -// focus of the algorithm is to ensure the integrity of the preserved filesystem, -// while maintaining a deterministic accountability. This includes neither -// constraining the ordering or manipulation of the files during the creation or -// unpacking of the archive, nor include additional metadata state about the file -// system attributes. -package tarsum // import "github.com/docker/docker/pkg/tarsum" - -import ( - "archive/tar" - "bytes" - "compress/gzip" - "crypto" - "crypto/sha256" - "encoding/hex" - "errors" - "fmt" - "hash" - "io" - "path" - "strings" -) - -const ( - buf8K = 8 * 1024 - buf16K = 16 * 1024 - buf32K = 32 * 1024 -) - -// NewTarSum creates a new interface for calculating a fixed time checksum of a -// tar archive. -// -// This is used for calculating checksums of layers of an image, in some cases -// including the byte payload of the image's json metadata as well, and for -// calculating the checksums for buildcache. -func NewTarSum(r io.Reader, dc bool, v Version) (TarSum, error) { - return NewTarSumHash(r, dc, v, DefaultTHash) -} - -// NewTarSumHash creates a new TarSum, providing a THash to use rather than -// the DefaultTHash. -func NewTarSumHash(r io.Reader, dc bool, v Version, tHash THash) (TarSum, error) { - headerSelector, err := getTarHeaderSelector(v) - if err != nil { - return nil, err - } - ts := &tarSum{Reader: r, DisableCompression: dc, tarSumVersion: v, headerSelector: headerSelector, tHash: tHash} - err = ts.initTarSum() - return ts, err -} - -// NewTarSumForLabel creates a new TarSum using the provided TarSum version+hash label. -func NewTarSumForLabel(r io.Reader, disableCompression bool, label string) (TarSum, error) { - parts := strings.SplitN(label, "+", 2) - if len(parts) != 2 { - return nil, errors.New("tarsum label string should be of the form: {tarsum_version}+{hash_name}") - } - - versionName, hashName := parts[0], parts[1] - - version, ok := tarSumVersionsByName[versionName] - if !ok { - return nil, fmt.Errorf("unknown TarSum version name: %q", versionName) - } - - hashConfig, ok := standardHashConfigs[hashName] - if !ok { - return nil, fmt.Errorf("unknown TarSum hash name: %q", hashName) - } - - tHash := NewTHash(hashConfig.name, hashConfig.hash.New) - - return NewTarSumHash(r, disableCompression, version, tHash) -} - -// TarSum is the generic interface for calculating fixed time -// checksums of a tar archive. -type TarSum interface { - io.Reader - GetSums() FileInfoSums - Sum([]byte) string - Version() Version - Hash() THash -} - -// tarSum struct is the structure for a Version0 checksum calculation. -type tarSum struct { - io.Reader - tarR *tar.Reader - tarW *tar.Writer - writer writeCloseFlusher - bufTar *bytes.Buffer - bufWriter *bytes.Buffer - bufData []byte - h hash.Hash - tHash THash - sums FileInfoSums - fileCounter int64 - currentFile string - finished bool - first bool - DisableCompression bool // false by default. When false, the output gzip compressed. - tarSumVersion Version // this field is not exported so it can not be mutated during use - headerSelector tarHeaderSelector // handles selecting and ordering headers for files in the archive -} - -func (ts tarSum) Hash() THash { - return ts.tHash -} - -func (ts tarSum) Version() Version { - return ts.tarSumVersion -} - -// THash provides a hash.Hash type generator and its name. -type THash interface { - Hash() hash.Hash - Name() string -} - -// NewTHash is a convenience method for creating a THash. -func NewTHash(name string, h func() hash.Hash) THash { - return simpleTHash{n: name, h: h} -} - -type tHashConfig struct { - name string - hash crypto.Hash -} - -var ( - // NOTE: DO NOT include MD5 or SHA1, which are considered insecure. - standardHashConfigs = map[string]tHashConfig{ - "sha256": {name: "sha256", hash: crypto.SHA256}, - "sha512": {name: "sha512", hash: crypto.SHA512}, - } -) - -// DefaultTHash is default TarSum hashing algorithm - "sha256". -var DefaultTHash = NewTHash("sha256", sha256.New) - -type simpleTHash struct { - n string - h func() hash.Hash -} - -func (sth simpleTHash) Name() string { return sth.n } -func (sth simpleTHash) Hash() hash.Hash { return sth.h() } - -func (ts *tarSum) encodeHeader(h *tar.Header) error { - for _, elem := range ts.headerSelector.selectHeaders(h) { - // Ignore these headers to be compatible with versions - // before go 1.10 - if elem[0] == "gname" || elem[0] == "uname" { - elem[1] = "" - } - if _, err := ts.h.Write([]byte(elem[0] + elem[1])); err != nil { - return err - } - } - return nil -} - -func (ts *tarSum) initTarSum() error { - ts.bufTar = bytes.NewBuffer([]byte{}) - ts.bufWriter = bytes.NewBuffer([]byte{}) - ts.tarR = tar.NewReader(ts.Reader) - ts.tarW = tar.NewWriter(ts.bufTar) - if !ts.DisableCompression { - ts.writer = gzip.NewWriter(ts.bufWriter) - } else { - ts.writer = &nopCloseFlusher{Writer: ts.bufWriter} - } - if ts.tHash == nil { - ts.tHash = DefaultTHash - } - ts.h = ts.tHash.Hash() - ts.h.Reset() - ts.first = true - ts.sums = FileInfoSums{} - return nil -} - -func (ts *tarSum) Read(buf []byte) (int, error) { - if ts.finished { - return ts.bufWriter.Read(buf) - } - if len(ts.bufData) < len(buf) { - switch { - case len(buf) <= buf8K: - ts.bufData = make([]byte, buf8K) - case len(buf) <= buf16K: - ts.bufData = make([]byte, buf16K) - case len(buf) <= buf32K: - ts.bufData = make([]byte, buf32K) - default: - ts.bufData = make([]byte, len(buf)) - } - } - buf2 := ts.bufData[:len(buf)] - - n, err := ts.tarR.Read(buf2) - if err != nil { - if err == io.EOF { - if _, err := ts.h.Write(buf2[:n]); err != nil { - return 0, err - } - if !ts.first { - ts.sums = append(ts.sums, fileInfoSum{name: ts.currentFile, sum: hex.EncodeToString(ts.h.Sum(nil)), pos: ts.fileCounter}) - ts.fileCounter++ - ts.h.Reset() - } else { - ts.first = false - } - - if _, err := ts.tarW.Write(buf2[:n]); err != nil { - return 0, err - } - - currentHeader, err := ts.tarR.Next() - if err != nil { - if err == io.EOF { - if err := ts.tarW.Close(); err != nil { - return 0, err - } - if _, err := io.Copy(ts.writer, ts.bufTar); err != nil { - return 0, err - } - if err := ts.writer.Close(); err != nil { - return 0, err - } - ts.finished = true - return ts.bufWriter.Read(buf) - } - return 0, err - } - - ts.currentFile = path.Join(".", path.Join("/", currentHeader.Name)) - if err := ts.encodeHeader(currentHeader); err != nil { - return 0, err - } - if err := ts.tarW.WriteHeader(currentHeader); err != nil { - return 0, err - } - - if _, err := io.Copy(ts.writer, ts.bufTar); err != nil { - return 0, err - } - ts.writer.Flush() - - return ts.bufWriter.Read(buf) - } - return 0, err - } - - // Filling the hash buffer - if _, err = ts.h.Write(buf2[:n]); err != nil { - return 0, err - } - - // Filling the tar writer - if _, err = ts.tarW.Write(buf2[:n]); err != nil { - return 0, err - } - - // Filling the output writer - if _, err = io.Copy(ts.writer, ts.bufTar); err != nil { - return 0, err - } - ts.writer.Flush() - - return ts.bufWriter.Read(buf) -} - -func (ts *tarSum) Sum(extra []byte) string { - ts.sums.SortBySums() - h := ts.tHash.Hash() - if extra != nil { - h.Write(extra) - } - for _, fis := range ts.sums { - h.Write([]byte(fis.Sum())) - } - checksum := ts.Version().String() + "+" + ts.tHash.Name() + ":" + hex.EncodeToString(h.Sum(nil)) - return checksum -} - -func (ts *tarSum) GetSums() FileInfoSums { - return ts.sums -} diff --git a/vendor/github.com/docker/docker/pkg/tarsum/versioning.go b/vendor/github.com/docker/docker/pkg/tarsum/versioning.go deleted file mode 100644 index aa1f17186..000000000 --- a/vendor/github.com/docker/docker/pkg/tarsum/versioning.go +++ /dev/null @@ -1,158 +0,0 @@ -package tarsum // import "github.com/docker/docker/pkg/tarsum" - -import ( - "archive/tar" - "errors" - "io" - "sort" - "strconv" - "strings" -) - -// Version is used for versioning of the TarSum algorithm -// based on the prefix of the hash used -// i.e. "tarsum+sha256:e58fcf7418d4390dec8e8fb69d88c06ec07039d651fedd3aa72af9972e7d046b" -type Version int - -// Prefix of "tarsum" -const ( - Version0 Version = iota - Version1 - // VersionDev this constant will be either the latest or an unsettled next-version of the TarSum calculation - VersionDev -) - -// WriteV1Header writes a tar header to a writer in V1 tarsum format. -func WriteV1Header(h *tar.Header, w io.Writer) { - for _, elem := range v1TarHeaderSelect(h) { - w.Write([]byte(elem[0] + elem[1])) - } -} - -// VersionLabelForChecksum returns the label for the given tarsum -// checksum, i.e., everything before the first `+` character in -// the string or an empty string if no label separator is found. -func VersionLabelForChecksum(checksum string) string { - // Checksums are in the form: {versionLabel}+{hashID}:{hex} - sepIndex := strings.Index(checksum, "+") - if sepIndex < 0 { - return "" - } - return checksum[:sepIndex] -} - -// GetVersions gets a list of all known tarsum versions. -func GetVersions() []Version { - v := []Version{} - for k := range tarSumVersions { - v = append(v, k) - } - return v -} - -var ( - tarSumVersions = map[Version]string{ - Version0: "tarsum", - Version1: "tarsum.v1", - VersionDev: "tarsum.dev", - } - tarSumVersionsByName = map[string]Version{ - "tarsum": Version0, - "tarsum.v1": Version1, - "tarsum.dev": VersionDev, - } -) - -func (tsv Version) String() string { - return tarSumVersions[tsv] -} - -// GetVersionFromTarsum returns the Version from the provided string. -func GetVersionFromTarsum(tarsum string) (Version, error) { - tsv := tarsum - if strings.Contains(tarsum, "+") { - tsv = strings.SplitN(tarsum, "+", 2)[0] - } - for v, s := range tarSumVersions { - if s == tsv { - return v, nil - } - } - return -1, ErrNotVersion -} - -// Errors that may be returned by functions in this package -var ( - ErrNotVersion = errors.New("string does not include a TarSum Version") - ErrVersionNotImplemented = errors.New("TarSum Version is not yet implemented") -) - -// tarHeaderSelector is the interface which different versions -// of tarsum should use for selecting and ordering tar headers -// for each item in the archive. -type tarHeaderSelector interface { - selectHeaders(h *tar.Header) (orderedHeaders [][2]string) -} - -type tarHeaderSelectFunc func(h *tar.Header) (orderedHeaders [][2]string) - -func (f tarHeaderSelectFunc) selectHeaders(h *tar.Header) (orderedHeaders [][2]string) { - return f(h) -} - -func v0TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) { - return [][2]string{ - {"name", h.Name}, - {"mode", strconv.FormatInt(h.Mode, 10)}, - {"uid", strconv.Itoa(h.Uid)}, - {"gid", strconv.Itoa(h.Gid)}, - {"size", strconv.FormatInt(h.Size, 10)}, - {"mtime", strconv.FormatInt(h.ModTime.UTC().Unix(), 10)}, - {"typeflag", string([]byte{h.Typeflag})}, - {"linkname", h.Linkname}, - {"uname", h.Uname}, - {"gname", h.Gname}, - {"devmajor", strconv.FormatInt(h.Devmajor, 10)}, - {"devminor", strconv.FormatInt(h.Devminor, 10)}, - } -} - -func v1TarHeaderSelect(h *tar.Header) (orderedHeaders [][2]string) { - // Get extended attributes. - xAttrKeys := make([]string, len(h.Xattrs)) - for k := range h.Xattrs { - xAttrKeys = append(xAttrKeys, k) - } - sort.Strings(xAttrKeys) - - // Make the slice with enough capacity to hold the 11 basic headers - // we want from the v0 selector plus however many xattrs we have. - orderedHeaders = make([][2]string, 0, 11+len(xAttrKeys)) - - // Copy all headers from v0 excluding the 'mtime' header (the 5th element). - v0headers := v0TarHeaderSelect(h) - orderedHeaders = append(orderedHeaders, v0headers[0:5]...) - orderedHeaders = append(orderedHeaders, v0headers[6:]...) - - // Finally, append the sorted xattrs. - for _, k := range xAttrKeys { - orderedHeaders = append(orderedHeaders, [2]string{k, h.Xattrs[k]}) - } - - return -} - -var registeredHeaderSelectors = map[Version]tarHeaderSelectFunc{ - Version0: v0TarHeaderSelect, - Version1: v1TarHeaderSelect, - VersionDev: v1TarHeaderSelect, -} - -func getTarHeaderSelector(v Version) (tarHeaderSelector, error) { - headerSelector, ok := registeredHeaderSelectors[v] - if !ok { - return nil, ErrVersionNotImplemented - } - - return headerSelector, nil -} diff --git a/vendor/github.com/docker/docker/pkg/tarsum/writercloser.go b/vendor/github.com/docker/docker/pkg/tarsum/writercloser.go deleted file mode 100644 index c4c45a35e..000000000 --- a/vendor/github.com/docker/docker/pkg/tarsum/writercloser.go +++ /dev/null @@ -1,22 +0,0 @@ -package tarsum // import "github.com/docker/docker/pkg/tarsum" - -import ( - "io" -) - -type writeCloseFlusher interface { - io.WriteCloser - Flush() error -} - -type nopCloseFlusher struct { - io.Writer -} - -func (n *nopCloseFlusher) Close() error { - return nil -} - -func (n *nopCloseFlusher) Flush() error { - return nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/ascii.go b/vendor/github.com/docker/docker/pkg/term/ascii.go deleted file mode 100644 index 87bca8d4a..000000000 --- a/vendor/github.com/docker/docker/pkg/term/ascii.go +++ /dev/null @@ -1,66 +0,0 @@ -package term // import "github.com/docker/docker/pkg/term" - -import ( - "fmt" - "strings" -) - -// ASCII list the possible supported ASCII key sequence -var ASCII = []string{ - "ctrl-@", - "ctrl-a", - "ctrl-b", - "ctrl-c", - "ctrl-d", - "ctrl-e", - "ctrl-f", - "ctrl-g", - "ctrl-h", - "ctrl-i", - "ctrl-j", - "ctrl-k", - "ctrl-l", - "ctrl-m", - "ctrl-n", - "ctrl-o", - "ctrl-p", - "ctrl-q", - "ctrl-r", - "ctrl-s", - "ctrl-t", - "ctrl-u", - "ctrl-v", - "ctrl-w", - "ctrl-x", - "ctrl-y", - "ctrl-z", - "ctrl-[", - "ctrl-\\", - "ctrl-]", - "ctrl-^", - "ctrl-_", -} - -// ToBytes converts a string representing a suite of key-sequence to the corresponding ASCII code. -func ToBytes(keys string) ([]byte, error) { - codes := []byte{} -next: - for _, key := range strings.Split(keys, ",") { - if len(key) != 1 { - for code, ctrl := range ASCII { - if ctrl == key { - codes = append(codes, byte(code)) - continue next - } - } - if key == "DEL" { - codes = append(codes, 127) - } else { - return nil, fmt.Errorf("Unknown character: '%s'", key) - } - } else { - codes = append(codes, key[0]) - } - } - return codes, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/proxy.go b/vendor/github.com/docker/docker/pkg/term/proxy.go deleted file mode 100644 index da733e584..000000000 --- a/vendor/github.com/docker/docker/pkg/term/proxy.go +++ /dev/null @@ -1,78 +0,0 @@ -package term // import "github.com/docker/docker/pkg/term" - -import ( - "io" -) - -// EscapeError is special error which returned by a TTY proxy reader's Read() -// method in case its detach escape sequence is read. -type EscapeError struct{} - -func (EscapeError) Error() string { - return "read escape sequence" -} - -// escapeProxy is used only for attaches with a TTY. It is used to proxy -// stdin keypresses from the underlying reader and look for the passed in -// escape key sequence to signal a detach. -type escapeProxy struct { - escapeKeys []byte - escapeKeyPos int - r io.Reader -} - -// NewEscapeProxy returns a new TTY proxy reader which wraps the given reader -// and detects when the specified escape keys are read, in which case the Read -// method will return an error of type EscapeError. -func NewEscapeProxy(r io.Reader, escapeKeys []byte) io.Reader { - return &escapeProxy{ - escapeKeys: escapeKeys, - r: r, - } -} - -func (r *escapeProxy) Read(buf []byte) (int, error) { - nr, err := r.r.Read(buf) - - if len(r.escapeKeys) == 0 { - return nr, err - } - - preserve := func() { - // this preserves the original key presses in the passed in buffer - nr += r.escapeKeyPos - preserve := make([]byte, 0, r.escapeKeyPos+len(buf)) - preserve = append(preserve, r.escapeKeys[:r.escapeKeyPos]...) - preserve = append(preserve, buf...) - r.escapeKeyPos = 0 - copy(buf[0:nr], preserve) - } - - if nr != 1 || err != nil { - if r.escapeKeyPos > 0 { - preserve() - } - return nr, err - } - - if buf[0] != r.escapeKeys[r.escapeKeyPos] { - if r.escapeKeyPos > 0 { - preserve() - } - return nr, nil - } - - if r.escapeKeyPos == len(r.escapeKeys)-1 { - return 0, EscapeError{} - } - - // Looks like we've got an escape key, but we need to match again on the next - // read. - // Store the current escape key we found so we can look for the next one on - // the next read. - // Since this is an escape key, make sure we don't let the caller read it - // If later on we find that this is not the escape sequence, we'll add the - // keys back - r.escapeKeyPos++ - return nr - r.escapeKeyPos, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/tc.go b/vendor/github.com/docker/docker/pkg/term/tc.go deleted file mode 100644 index 01bcaa8ab..000000000 --- a/vendor/github.com/docker/docker/pkg/term/tc.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package term // import "github.com/docker/docker/pkg/term" - -import ( - "syscall" - "unsafe" - - "golang.org/x/sys/unix" -) - -func tcget(fd uintptr, p *Termios) syscall.Errno { - _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, uintptr(getTermios), uintptr(unsafe.Pointer(p))) - return err -} - -func tcset(fd uintptr, p *Termios) syscall.Errno { - _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(p))) - return err -} diff --git a/vendor/github.com/docker/docker/pkg/term/term.go b/vendor/github.com/docker/docker/pkg/term/term.go deleted file mode 100644 index 0589a9551..000000000 --- a/vendor/github.com/docker/docker/pkg/term/term.go +++ /dev/null @@ -1,124 +0,0 @@ -// +build !windows - -// Package term provides structures and helper functions to work with -// terminal (state, sizes). -package term // import "github.com/docker/docker/pkg/term" - -import ( - "errors" - "fmt" - "io" - "os" - "os/signal" - - "golang.org/x/sys/unix" -) - -var ( - // ErrInvalidState is returned if the state of the terminal is invalid. - ErrInvalidState = errors.New("Invalid terminal state") -) - -// State represents the state of the terminal. -type State struct { - termios Termios -} - -// Winsize represents the size of the terminal window. -type Winsize struct { - Height uint16 - Width uint16 - x uint16 - y uint16 -} - -// StdStreams returns the standard streams (stdin, stdout, stderr). -func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { - return os.Stdin, os.Stdout, os.Stderr -} - -// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. -func GetFdInfo(in interface{}) (uintptr, bool) { - var inFd uintptr - var isTerminalIn bool - if file, ok := in.(*os.File); ok { - inFd = file.Fd() - isTerminalIn = IsTerminal(inFd) - } - return inFd, isTerminalIn -} - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(fd uintptr) bool { - var termios Termios - return tcget(fd, &termios) == 0 -} - -// RestoreTerminal restores the terminal connected to the given file descriptor -// to a previous state. -func RestoreTerminal(fd uintptr, state *State) error { - if state == nil { - return ErrInvalidState - } - if err := tcset(fd, &state.termios); err != 0 { - return err - } - return nil -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - var oldState State - if err := tcget(fd, &oldState.termios); err != 0 { - return nil, err - } - - return &oldState, nil -} - -// DisableEcho applies the specified state to the terminal connected to the file -// descriptor, with echo disabled. -func DisableEcho(fd uintptr, state *State) error { - newState := state.termios - newState.Lflag &^= unix.ECHO - - if err := tcset(fd, &newState); err != 0 { - return err - } - handleInterrupt(fd, state) - return nil -} - -// SetRawTerminal puts the terminal connected to the given file descriptor into -// raw mode and returns the previous state. On UNIX, this puts both the input -// and output into raw mode. On Windows, it only puts the input into raw mode. -func SetRawTerminal(fd uintptr) (*State, error) { - oldState, err := MakeRaw(fd) - if err != nil { - return nil, err - } - handleInterrupt(fd, oldState) - return oldState, err -} - -// SetRawTerminalOutput puts the output of terminal connected to the given file -// descriptor into raw mode. On UNIX, this does nothing and returns nil for the -// state. On Windows, it disables LF -> CRLF translation. -func SetRawTerminalOutput(fd uintptr) (*State, error) { - return nil, nil -} - -func handleInterrupt(fd uintptr, state *State) { - sigchan := make(chan os.Signal, 1) - signal.Notify(sigchan, os.Interrupt) - go func() { - for range sigchan { - // quit cleanly and the new terminal item is on a new line - fmt.Println() - signal.Stop(sigchan) - close(sigchan) - RestoreTerminal(fd, state) - os.Exit(1) - } - }() -} diff --git a/vendor/github.com/docker/docker/pkg/term/term_windows.go b/vendor/github.com/docker/docker/pkg/term/term_windows.go deleted file mode 100644 index a3c3db131..000000000 --- a/vendor/github.com/docker/docker/pkg/term/term_windows.go +++ /dev/null @@ -1,221 +0,0 @@ -package term // import "github.com/docker/docker/pkg/term" - -import ( - "io" - "os" - "os/signal" - "syscall" // used for STD_INPUT_HANDLE, STD_OUTPUT_HANDLE and STD_ERROR_HANDLE - - "github.com/Azure/go-ansiterm/winterm" - "github.com/docker/docker/pkg/term/windows" -) - -// State holds the console mode for the terminal. -type State struct { - mode uint32 -} - -// Winsize is used for window size. -type Winsize struct { - Height uint16 - Width uint16 -} - -// vtInputSupported is true if winterm.ENABLE_VIRTUAL_TERMINAL_INPUT is supported by the console -var vtInputSupported bool - -// StdStreams returns the standard streams (stdin, stdout, stderr). -func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { - // Turn on VT handling on all std handles, if possible. This might - // fail, in which case we will fall back to terminal emulation. - var emulateStdin, emulateStdout, emulateStderr bool - fd := os.Stdin.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate that winterm.ENABLE_VIRTUAL_TERMINAL_INPUT is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|winterm.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil { - emulateStdin = true - } else { - vtInputSupported = true - } - // Unconditionally set the console mode back even on failure because SetConsoleMode - // remembers invalid bits on input handles. - winterm.SetConsoleMode(fd, mode) - } - - fd = os.Stdout.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|winterm.ENABLE_VIRTUAL_TERMINAL_PROCESSING|winterm.DISABLE_NEWLINE_AUTO_RETURN); err != nil { - emulateStdout = true - } else { - winterm.SetConsoleMode(fd, mode|winterm.ENABLE_VIRTUAL_TERMINAL_PROCESSING) - } - } - - fd = os.Stderr.Fd() - if mode, err := winterm.GetConsoleMode(fd); err == nil { - // Validate winterm.DISABLE_NEWLINE_AUTO_RETURN is supported, but do not set it. - if err = winterm.SetConsoleMode(fd, mode|winterm.ENABLE_VIRTUAL_TERMINAL_PROCESSING|winterm.DISABLE_NEWLINE_AUTO_RETURN); err != nil { - emulateStderr = true - } else { - winterm.SetConsoleMode(fd, mode|winterm.ENABLE_VIRTUAL_TERMINAL_PROCESSING) - } - } - - // Temporarily use STD_INPUT_HANDLE, STD_OUTPUT_HANDLE and - // STD_ERROR_HANDLE from syscall rather than x/sys/windows as long as - // go-ansiterm hasn't switch to x/sys/windows. - // TODO: switch back to x/sys/windows once go-ansiterm has switched - if emulateStdin { - stdIn = windowsconsole.NewAnsiReader(syscall.STD_INPUT_HANDLE) - } else { - stdIn = os.Stdin - } - - if emulateStdout { - stdOut = windowsconsole.NewAnsiWriter(syscall.STD_OUTPUT_HANDLE) - } else { - stdOut = os.Stdout - } - - if emulateStderr { - stdErr = windowsconsole.NewAnsiWriter(syscall.STD_ERROR_HANDLE) - } else { - stdErr = os.Stderr - } - - return -} - -// GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. -func GetFdInfo(in interface{}) (uintptr, bool) { - return windowsconsole.GetHandleInfo(in) -} - -// GetWinsize returns the window size based on the specified file descriptor. -func GetWinsize(fd uintptr) (*Winsize, error) { - info, err := winterm.GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil, err - } - - winsize := &Winsize{ - Width: uint16(info.Window.Right - info.Window.Left + 1), - Height: uint16(info.Window.Bottom - info.Window.Top + 1), - } - - return winsize, nil -} - -// IsTerminal returns true if the given file descriptor is a terminal. -func IsTerminal(fd uintptr) bool { - return windowsconsole.IsConsole(fd) -} - -// RestoreTerminal restores the terminal connected to the given file descriptor -// to a previous state. -func RestoreTerminal(fd uintptr, state *State) error { - return winterm.SetConsoleMode(fd, state.mode) -} - -// SaveState saves the state of the terminal connected to the given file descriptor. -func SaveState(fd uintptr) (*State, error) { - mode, e := winterm.GetConsoleMode(fd) - if e != nil { - return nil, e - } - - return &State{mode: mode}, nil -} - -// DisableEcho disables echo for the terminal connected to the given file descriptor. -// -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx -func DisableEcho(fd uintptr, state *State) error { - mode := state.mode - mode &^= winterm.ENABLE_ECHO_INPUT - mode |= winterm.ENABLE_PROCESSED_INPUT | winterm.ENABLE_LINE_INPUT - err := winterm.SetConsoleMode(fd, mode) - if err != nil { - return err - } - - // Register an interrupt handler to catch and restore prior state - restoreAtInterrupt(fd, state) - return nil -} - -// SetRawTerminal puts the terminal connected to the given file descriptor into -// raw mode and returns the previous state. On UNIX, this puts both the input -// and output into raw mode. On Windows, it only puts the input into raw mode. -func SetRawTerminal(fd uintptr) (*State, error) { - state, err := MakeRaw(fd) - if err != nil { - return nil, err - } - - // Register an interrupt handler to catch and restore prior state - restoreAtInterrupt(fd, state) - return state, err -} - -// SetRawTerminalOutput puts the output of terminal connected to the given file -// descriptor into raw mode. On UNIX, this does nothing and returns nil for the -// state. On Windows, it disables LF -> CRLF translation. -func SetRawTerminalOutput(fd uintptr) (*State, error) { - state, err := SaveState(fd) - if err != nil { - return nil, err - } - - // Ignore failures, since winterm.DISABLE_NEWLINE_AUTO_RETURN might not be supported on this - // version of Windows. - winterm.SetConsoleMode(fd, state.mode|winterm.DISABLE_NEWLINE_AUTO_RETURN) - return state, err -} - -// MakeRaw puts the terminal (Windows Console) connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be restored. -func MakeRaw(fd uintptr) (*State, error) { - state, err := SaveState(fd) - if err != nil { - return nil, err - } - - mode := state.mode - - // 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 &^= winterm.ENABLE_ECHO_INPUT - mode &^= winterm.ENABLE_LINE_INPUT - mode &^= winterm.ENABLE_MOUSE_INPUT - mode &^= winterm.ENABLE_WINDOW_INPUT - mode &^= winterm.ENABLE_PROCESSED_INPUT - - // Enable these modes - mode |= winterm.ENABLE_EXTENDED_FLAGS - mode |= winterm.ENABLE_INSERT_MODE - mode |= winterm.ENABLE_QUICK_EDIT_MODE - if vtInputSupported { - mode |= winterm.ENABLE_VIRTUAL_TERMINAL_INPUT - } - - err = winterm.SetConsoleMode(fd, mode) - if err != nil { - return nil, err - } - return state, nil -} - -func restoreAtInterrupt(fd uintptr, state *State) { - sigchan := make(chan os.Signal, 1) - signal.Notify(sigchan, os.Interrupt) - - go func() { - _ = <-sigchan - RestoreTerminal(fd, state) - os.Exit(0) - }() -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_bsd.go b/vendor/github.com/docker/docker/pkg/term/termios_bsd.go deleted file mode 100644 index 48b16f520..000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_bsd.go +++ /dev/null @@ -1,42 +0,0 @@ -// +build darwin freebsd openbsd netbsd - -package term // import "github.com/docker/docker/pkg/term" - -import ( - "unsafe" - - "golang.org/x/sys/unix" -) - -const ( - getTermios = unix.TIOCGETA - setTermios = unix.TIOCSETA -) - -// Termios is the Unix API for terminal I/O. -type Termios unix.Termios - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - var oldState State - if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, getTermios, uintptr(unsafe.Pointer(&oldState.termios))); err != 0 { - return nil, err - } - - newState := oldState.termios - newState.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON) - newState.Oflag &^= unix.OPOST - newState.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN) - newState.Cflag &^= (unix.CSIZE | unix.PARENB) - newState.Cflag |= unix.CS8 - newState.Cc[unix.VMIN] = 1 - newState.Cc[unix.VTIME] = 0 - - if _, _, err := unix.Syscall(unix.SYS_IOCTL, fd, setTermios, uintptr(unsafe.Pointer(&newState))); err != 0 { - return nil, err - } - - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/termios_linux.go b/vendor/github.com/docker/docker/pkg/term/termios_linux.go deleted file mode 100644 index 6d4c63fdb..000000000 --- a/vendor/github.com/docker/docker/pkg/term/termios_linux.go +++ /dev/null @@ -1,39 +0,0 @@ -package term // import "github.com/docker/docker/pkg/term" - -import ( - "golang.org/x/sys/unix" -) - -const ( - getTermios = unix.TCGETS - setTermios = unix.TCSETS -) - -// Termios is the Unix API for terminal I/O. -type Termios unix.Termios - -// MakeRaw put the terminal connected to the given file descriptor into raw -// mode and returns the previous state of the terminal so that it can be -// restored. -func MakeRaw(fd uintptr) (*State, error) { - termios, err := unix.IoctlGetTermios(int(fd), getTermios) - if err != nil { - return nil, err - } - - var oldState State - oldState.termios = Termios(*termios) - - termios.Iflag &^= (unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON) - termios.Oflag &^= unix.OPOST - termios.Lflag &^= (unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN) - termios.Cflag &^= (unix.CSIZE | unix.PARENB) - termios.Cflag |= unix.CS8 - termios.Cc[unix.VMIN] = 1 - termios.Cc[unix.VTIME] = 0 - - if err := unix.IoctlSetTermios(int(fd), setTermios, termios); err != nil { - return nil, err - } - return &oldState, nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go deleted file mode 100644 index 1d7c452cc..000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/ansi_reader.go +++ /dev/null @@ -1,263 +0,0 @@ -// +build windows - -package windowsconsole // import "github.com/docker/docker/pkg/term/windows" - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "strings" - "unsafe" - - ansiterm "github.com/Azure/go-ansiterm" - "github.com/Azure/go-ansiterm/winterm" -) - -const ( - escapeSequence = ansiterm.KEY_ESC_CSI -) - -// ansiReader wraps a standard input file (e.g., os.Stdin) providing ANSI sequence translation. -type ansiReader struct { - file *os.File - fd uintptr - buffer []byte - cbBuffer int - command []byte -} - -// NewAnsiReader returns an io.ReadCloser that provides VT100 terminal emulation on top of a -// Windows console input handle. -func NewAnsiReader(nFile int) io.ReadCloser { - initLogger() - file, fd := winterm.GetStdFile(nFile) - return &ansiReader{ - file: file, - fd: fd, - command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), - buffer: make([]byte, 0), - } -} - -// Close closes the wrapped file. -func (ar *ansiReader) Close() (err error) { - return ar.file.Close() -} - -// Fd returns the file descriptor of the wrapped file. -func (ar *ansiReader) Fd() uintptr { - return ar.fd -} - -// Read reads up to len(p) bytes of translated input events into p. -func (ar *ansiReader) Read(p []byte) (int, error) { - if len(p) == 0 { - return 0, nil - } - - // Previously read bytes exist, read as much as we can and return - if len(ar.buffer) > 0 { - logger.Debugf("Reading previously cached bytes") - - originalLength := len(ar.buffer) - copiedLength := copy(p, ar.buffer) - - if copiedLength == originalLength { - ar.buffer = make([]byte, 0, len(p)) - } else { - ar.buffer = ar.buffer[copiedLength:] - } - - logger.Debugf("Read from cache p[%d]: % x", copiedLength, p) - return copiedLength, nil - } - - // Read and translate key events - events, err := readInputEvents(ar.fd, len(p)) - if err != nil { - return 0, err - } else if len(events) == 0 { - logger.Debug("No input events detected") - return 0, nil - } - - keyBytes := translateKeyEvents(events, []byte(escapeSequence)) - - // Save excess bytes and right-size keyBytes - if len(keyBytes) > len(p) { - logger.Debugf("Received %d keyBytes, only room for %d bytes", len(keyBytes), len(p)) - ar.buffer = keyBytes[len(p):] - keyBytes = keyBytes[:len(p)] - } else if len(keyBytes) == 0 { - logger.Debug("No key bytes returned from the translator") - return 0, nil - } - - copiedLength := copy(p, keyBytes) - if copiedLength != len(keyBytes) { - return 0, errors.New("unexpected copy length encountered") - } - - logger.Debugf("Read p[%d]: % x", copiedLength, p) - logger.Debugf("Read keyBytes[%d]: % x", copiedLength, keyBytes) - return copiedLength, nil -} - -// readInputEvents polls until at least one event is available. -func readInputEvents(fd uintptr, maxBytes int) ([]winterm.INPUT_RECORD, error) { - // Determine the maximum number of records to retrieve - // -- Cast around the type system to obtain the size of a single INPUT_RECORD. - // unsafe.Sizeof requires an expression vs. a type-reference; the casting - // tricks the type system into believing it has such an expression. - recordSize := int(unsafe.Sizeof(*((*winterm.INPUT_RECORD)(unsafe.Pointer(&maxBytes))))) - countRecords := maxBytes / recordSize - if countRecords > ansiterm.MAX_INPUT_EVENTS { - countRecords = ansiterm.MAX_INPUT_EVENTS - } else if countRecords == 0 { - countRecords = 1 - } - logger.Debugf("[windows] readInputEvents: Reading %v records (buffer size %v, record size %v)", countRecords, maxBytes, recordSize) - - // Wait for and read input events - events := make([]winterm.INPUT_RECORD, countRecords) - nEvents := uint32(0) - eventsExist, err := winterm.WaitForSingleObject(fd, winterm.WAIT_INFINITE) - if err != nil { - return nil, err - } - - if eventsExist { - err = winterm.ReadConsoleInput(fd, events, &nEvents) - if err != nil { - return nil, err - } - } - - // Return a slice restricted to the number of returned records - logger.Debugf("[windows] readInputEvents: Read %v events", nEvents) - return events[:nEvents], nil -} - -// KeyEvent Translation Helpers - -var arrowKeyMapPrefix = map[uint16]string{ - winterm.VK_UP: "%s%sA", - winterm.VK_DOWN: "%s%sB", - winterm.VK_RIGHT: "%s%sC", - winterm.VK_LEFT: "%s%sD", -} - -var keyMapPrefix = map[uint16]string{ - winterm.VK_UP: "\x1B[%sA", - winterm.VK_DOWN: "\x1B[%sB", - winterm.VK_RIGHT: "\x1B[%sC", - winterm.VK_LEFT: "\x1B[%sD", - winterm.VK_HOME: "\x1B[1%s~", // showkey shows ^[[1 - winterm.VK_END: "\x1B[4%s~", // showkey shows ^[[4 - winterm.VK_INSERT: "\x1B[2%s~", - winterm.VK_DELETE: "\x1B[3%s~", - winterm.VK_PRIOR: "\x1B[5%s~", - winterm.VK_NEXT: "\x1B[6%s~", - winterm.VK_F1: "", - winterm.VK_F2: "", - winterm.VK_F3: "\x1B[13%s~", - winterm.VK_F4: "\x1B[14%s~", - winterm.VK_F5: "\x1B[15%s~", - winterm.VK_F6: "\x1B[17%s~", - winterm.VK_F7: "\x1B[18%s~", - winterm.VK_F8: "\x1B[19%s~", - winterm.VK_F9: "\x1B[20%s~", - winterm.VK_F10: "\x1B[21%s~", - winterm.VK_F11: "\x1B[23%s~", - winterm.VK_F12: "\x1B[24%s~", -} - -// translateKeyEvents converts the input events into the appropriate ANSI string. -func translateKeyEvents(events []winterm.INPUT_RECORD, escapeSequence []byte) []byte { - var buffer bytes.Buffer - for _, event := range events { - if event.EventType == winterm.KEY_EVENT && event.KeyEvent.KeyDown != 0 { - buffer.WriteString(keyToString(&event.KeyEvent, escapeSequence)) - } - } - - return buffer.Bytes() -} - -// keyToString maps the given input event record to the corresponding string. -func keyToString(keyEvent *winterm.KEY_EVENT_RECORD, escapeSequence []byte) string { - if keyEvent.UnicodeChar == 0 { - return formatVirtualKey(keyEvent.VirtualKeyCode, keyEvent.ControlKeyState, escapeSequence) - } - - _, alt, control := getControlKeys(keyEvent.ControlKeyState) - if control { - // TODO(azlinux): Implement following control sequences - // -D Signals the end of input from the keyboard; also exits current shell. - // -H Deletes the first character to the left of the cursor. Also called the ERASE key. - // -Q Restarts printing after it has been stopped with -s. - // -S Suspends printing on the screen (does not stop the program). - // -U Deletes all characters on the current line. Also called the KILL key. - // -E Quits current command and creates a core - - } - - // +Key generates ESC N Key - if !control && alt { - return ansiterm.KEY_ESC_N + strings.ToLower(string(keyEvent.UnicodeChar)) - } - - return string(keyEvent.UnicodeChar) -} - -// formatVirtualKey converts a virtual key (e.g., up arrow) into the appropriate ANSI string. -func formatVirtualKey(key uint16, controlState uint32, escapeSequence []byte) string { - shift, alt, control := getControlKeys(controlState) - modifier := getControlKeysModifier(shift, alt, control) - - if format, ok := arrowKeyMapPrefix[key]; ok { - return fmt.Sprintf(format, escapeSequence, modifier) - } - - if format, ok := keyMapPrefix[key]; ok { - return fmt.Sprintf(format, modifier) - } - - return "" -} - -// getControlKeys extracts the shift, alt, and ctrl key states. -func getControlKeys(controlState uint32) (shift, alt, control bool) { - shift = 0 != (controlState & winterm.SHIFT_PRESSED) - alt = 0 != (controlState & (winterm.LEFT_ALT_PRESSED | winterm.RIGHT_ALT_PRESSED)) - control = 0 != (controlState & (winterm.LEFT_CTRL_PRESSED | winterm.RIGHT_CTRL_PRESSED)) - return shift, alt, control -} - -// getControlKeysModifier returns the ANSI modifier for the given combination of control keys. -func getControlKeysModifier(shift, alt, control bool) string { - if shift && alt && control { - return ansiterm.KEY_CONTROL_PARAM_8 - } - if alt && control { - return ansiterm.KEY_CONTROL_PARAM_7 - } - if shift && control { - return ansiterm.KEY_CONTROL_PARAM_6 - } - if control { - return ansiterm.KEY_CONTROL_PARAM_5 - } - if shift && alt { - return ansiterm.KEY_CONTROL_PARAM_4 - } - if alt { - return ansiterm.KEY_CONTROL_PARAM_3 - } - if shift { - return ansiterm.KEY_CONTROL_PARAM_2 - } - return "" -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go b/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go deleted file mode 100644 index 7799a03fc..000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/ansi_writer.go +++ /dev/null @@ -1,64 +0,0 @@ -// +build windows - -package windowsconsole // import "github.com/docker/docker/pkg/term/windows" - -import ( - "io" - "os" - - ansiterm "github.com/Azure/go-ansiterm" - "github.com/Azure/go-ansiterm/winterm" -) - -// ansiWriter wraps a standard output file (e.g., os.Stdout) providing ANSI sequence translation. -type ansiWriter struct { - file *os.File - fd uintptr - infoReset *winterm.CONSOLE_SCREEN_BUFFER_INFO - command []byte - escapeSequence []byte - inAnsiSequence bool - parser *ansiterm.AnsiParser -} - -// NewAnsiWriter returns an io.Writer that provides VT100 terminal emulation on top of a -// Windows console output handle. -func NewAnsiWriter(nFile int) io.Writer { - initLogger() - file, fd := winterm.GetStdFile(nFile) - info, err := winterm.GetConsoleScreenBufferInfo(fd) - if err != nil { - return nil - } - - parser := ansiterm.CreateParser("Ground", winterm.CreateWinEventHandler(fd, file)) - logger.Infof("newAnsiWriter: parser %p", parser) - - aw := &ansiWriter{ - file: file, - fd: fd, - infoReset: info, - command: make([]byte, 0, ansiterm.ANSI_MAX_CMD_LENGTH), - escapeSequence: []byte(ansiterm.KEY_ESC_CSI), - parser: parser, - } - - logger.Infof("newAnsiWriter: aw.parser %p", aw.parser) - logger.Infof("newAnsiWriter: %v", aw) - return aw -} - -func (aw *ansiWriter) Fd() uintptr { - return aw.fd -} - -// Write writes len(p) bytes from p to the underlying data stream. -func (aw *ansiWriter) Write(p []byte) (total int, err error) { - if len(p) == 0 { - return 0, nil - } - - logger.Infof("Write: % x", p) - logger.Infof("Write: %s", string(p)) - return aw.parser.Parse(p) -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/console.go b/vendor/github.com/docker/docker/pkg/term/windows/console.go deleted file mode 100644 index 527401975..000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/console.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build windows - -package windowsconsole // import "github.com/docker/docker/pkg/term/windows" - -import ( - "os" - - "github.com/Azure/go-ansiterm/winterm" -) - -// GetHandleInfo returns file descriptor and bool indicating whether the file is a console. -func GetHandleInfo(in interface{}) (uintptr, bool) { - switch t := in.(type) { - case *ansiReader: - return t.Fd(), true - case *ansiWriter: - return t.Fd(), true - } - - var inFd uintptr - var isTerminal bool - - if file, ok := in.(*os.File); ok { - inFd = file.Fd() - isTerminal = IsConsole(inFd) - } - return inFd, isTerminal -} - -// IsConsole returns true if the given file descriptor is a Windows Console. -// The code assumes that GetConsoleMode will return an error for file descriptors that are not a console. -func IsConsole(fd uintptr) bool { - _, e := winterm.GetConsoleMode(fd) - return e == nil -} diff --git a/vendor/github.com/docker/docker/pkg/term/windows/windows.go b/vendor/github.com/docker/docker/pkg/term/windows/windows.go deleted file mode 100644 index 3e5593ca6..000000000 --- a/vendor/github.com/docker/docker/pkg/term/windows/windows.go +++ /dev/null @@ -1,33 +0,0 @@ -// These files implement ANSI-aware input and output streams for use by the Docker Windows client. -// When asked for the set of standard streams (e.g., stdin, stdout, stderr), the code will create -// and return pseudo-streams that convert ANSI sequences to / from Windows Console API calls. - -package windowsconsole // import "github.com/docker/docker/pkg/term/windows" - -import ( - "io/ioutil" - "os" - "sync" - - "github.com/Azure/go-ansiterm" - "github.com/sirupsen/logrus" -) - -var logger *logrus.Logger -var initOnce sync.Once - -func initLogger() { - initOnce.Do(func() { - logFile := ioutil.Discard - - if isDebugEnv := os.Getenv(ansiterm.LogEnv); isDebugEnv == "1" { - logFile, _ = os.Create("ansiReaderWriter.log") - } - - logger = &logrus.Logger{ - Out: logFile, - Formatter: new(logrus.TextFormatter), - Level: logrus.DebugLevel, - } - }) -} diff --git a/vendor/github.com/docker/docker/pkg/term/winsize.go b/vendor/github.com/docker/docker/pkg/term/winsize.go deleted file mode 100644 index a19663ad8..000000000 --- a/vendor/github.com/docker/docker/pkg/term/winsize.go +++ /dev/null @@ -1,20 +0,0 @@ -// +build !windows - -package term // import "github.com/docker/docker/pkg/term" - -import ( - "golang.org/x/sys/unix" -) - -// GetWinsize returns the window size based on the specified file descriptor. -func GetWinsize(fd uintptr) (*Winsize, error) { - uws, err := unix.IoctlGetWinsize(int(fd), unix.TIOCGWINSZ) - ws := &Winsize{Height: uws.Row, Width: uws.Col, x: uws.Xpixel, y: uws.Ypixel} - return ws, err -} - -// SetWinsize tries to set the specified window size for the specified file descriptor. -func SetWinsize(fd uintptr, ws *Winsize) error { - uws := &unix.Winsize{Row: ws.Height, Col: ws.Width, Xpixel: ws.x, Ypixel: ws.y} - return unix.IoctlSetWinsize(int(fd), unix.TIOCSWINSZ, uws) -} diff --git a/vendor/github.com/docker/docker/pkg/urlutil/urlutil.go b/vendor/github.com/docker/docker/pkg/urlutil/urlutil.go deleted file mode 100644 index 9cf348c72..000000000 --- a/vendor/github.com/docker/docker/pkg/urlutil/urlutil.go +++ /dev/null @@ -1,52 +0,0 @@ -// Package urlutil provides helper function to check urls kind. -// It supports http urls, git urls and transport url (tcp://, …) -package urlutil // import "github.com/docker/docker/pkg/urlutil" - -import ( - "regexp" - "strings" -) - -var ( - validPrefixes = map[string][]string{ - "url": {"http://", "https://"}, - - // 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. - "git": {"git://", "github.com/", "git@"}, - "transport": {"tcp://", "tcp+tls://", "udp://", "unix://", "unixgram://"}, - } - urlPathWithFragmentSuffix = regexp.MustCompile(".git(?:#.+)?$") -) - -// IsURL returns true if the provided str is an HTTP(S) URL. -func IsURL(str string) bool { - return checkURL(str, "url") -} - -// IsGitURL returns true if the provided str is a git repository URL. -func IsGitURL(str string) bool { - if IsURL(str) && urlPathWithFragmentSuffix.MatchString(str) { - return true - } - return checkURL(str, "git") -} - -// IsTransportURL returns true if the provided str is a transport (tcp, tcp+tls, udp, unix) URL. -func IsTransportURL(str string) bool { - return checkURL(str, "transport") -} - -func checkURL(str, kind string) bool { - for _, prefix := range validPrefixes[kind] { - if strings.HasPrefix(str, prefix) { - return true - } - } - return false -} 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 3f58fc6cf..000000000 --- a/vendor/github.com/docker/docker/registry/auth.go +++ /dev/null @@ -1,295 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "io/ioutil" - "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" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -const ( - // AuthClientID is used the ClientID used for the token server - AuthClientID = "docker" -) - -// loginV1 tries to register/login to the v1 registry server. -func loginV1(authConfig *types.AuthConfig, apiEndpoint APIEndpoint, userAgent string) (string, string, error) { - registryEndpoint := apiEndpoint.ToV1Endpoint(userAgent, nil) - serverAddress := registryEndpoint.String() - - logrus.Debugf("attempting v1 login to registry endpoint %s", serverAddress) - - if serverAddress == "" { - return "", "", errdefs.System(errors.New("server Error: Server Address not set")) - } - - req, err := http.NewRequest("GET", serverAddress+"users/", nil) - if err != nil { - return "", "", err - } - req.SetBasicAuth(authConfig.Username, authConfig.Password) - resp, err := registryEndpoint.client.Do(req) - if err != nil { - // fallback when request could not be completed - return "", "", fallbackError{ - err: err, - } - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", "", errdefs.System(err) - } - - switch resp.StatusCode { - case http.StatusOK: - return "Login Succeeded", "", nil - case http.StatusUnauthorized: - return "", "", errdefs.Unauthorized(errors.New("Wrong login/password, please try again")) - case http.StatusForbidden: - // *TODO: Use registry configuration to determine what this says, if anything? - return "", "", errdefs.Forbidden(errors.Errorf("Login: Account is not active. Please see the documentation of the registry %s for instructions how to activate it.", serverAddress)) - case http.StatusInternalServerError: - logrus.Errorf("%s returned status code %d. Response Body :\n%s", req.URL.String(), resp.StatusCode, body) - return "", "", errdefs.System(errors.New("Internal Server Error")) - } - return "", "", errdefs.System(errors.Errorf("Login: %s (Code: %d; Headers: %s)", body, - resp.StatusCode, resp.Header)) -} - -type loginCredentialStore struct { - authConfig *types.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 *types.AuthConfig -} - -// NewStaticCredentialStore returns a credential store -// which always returns the same credential values. -func NewStaticCredentialStore(auth *types.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) { -} - -type fallbackError struct { - err error -} - -func (err fallbackError) Error() string { - return err.err.Error() -} - -// 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 *types.AuthConfig, endpoint APIEndpoint, userAgent string) (string, string, error) { - logrus.Debugf("attempting v2 login to registry endpoint %s", strings.TrimRight(endpoint.URL.String(), "/")+"/v2/") - - modifiers := Headers(userAgent, nil) - authTransport := transport.NewTransport(NewTransport(endpoint.TLSConfig), modifiers...) - - credentialAuthConfig := *authConfig - creds := loginCredentialStore{ - authConfig: &credentialAuthConfig, - } - - loginClient, foundV2, err := v2AuthHTTPClient(endpoint.URL, authTransport, modifiers, creds, nil) - if err != nil { - return "", "", err - } - - endpointStr := strings.TrimRight(endpoint.URL.String(), "/") + "/v2/" - req, err := http.NewRequest("GET", endpointStr, nil) - if err != nil { - if !foundV2 { - err = fallbackError{err: err} - } - return "", "", err - } - - resp, err := loginClient.Do(req) - if err != nil { - err = translateV2AuthError(err) - if !foundV2 { - err = fallbackError{err: 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 - err = errors.Errorf("login attempt to %s failed with status: %d %s", endpointStr, resp.StatusCode, http.StatusText(resp.StatusCode)) - if !foundV2 { - err = fallbackError{err: err} - } - return "", "", err -} - -func v2AuthHTTPClient(endpoint *url.URL, authTransport http.RoundTripper, modifiers []transport.RequestModifier, creds auth.CredentialStore, scopes []auth.Scope) (*http.Client, bool, error) { - challengeManager, foundV2, err := PingV2Registry(endpoint, authTransport) - if err != nil { - if !foundV2 { - err = fallbackError{err: err} - } - return nil, foundV2, 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)) - tr := transport.NewTransport(authTransport, modifiers...) - - return &http.Client{ - Transport: tr, - Timeout: 15 * time.Second, - }, foundV2, 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://") - } - - nameParts := strings.SplitN(stripped, "/", 2) - - return nameParts[0] -} - -// ResolveAuthConfig matches an auth configuration to a server address or a URL -func ResolveAuthConfig(authConfigs map[string]types.AuthConfig, index *registrytypes.IndexInfo) types.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 types.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 and -// whether v2 was confirmed by the response. If a response is received but -// cannot be interpreted a PingResponseError will be returned. -func PingV2Registry(endpoint *url.URL, transport http.RoundTripper) (challenge.Manager, bool, error) { - var ( - foundV2 = false - v2Version = auth.APIVersion{ - Type: "registry", - Version: "2.0", - } - ) - - pingClient := &http.Client{ - Transport: transport, - Timeout: 15 * time.Second, - } - endpointStr := strings.TrimRight(endpoint.String(), "/") + "/v2/" - req, err := http.NewRequest("GET", endpointStr, nil) - if err != nil { - return nil, false, err - } - resp, err := pingClient.Do(req) - if err != nil { - return nil, false, err - } - defer resp.Body.Close() - - versions := auth.APIVersions(resp, DefaultRegistryVersionHeader) - for _, pingVersion := range versions { - if pingVersion == v2Version { - // The version header indicates we're definitely - // talking to a v2 registry. So don't allow future - // fallbacks to the v1 protocol. - - foundV2 = true - break - } - } - - challengeManager := challenge.NewSimpleManager() - if err := challengeManager.AddResponse(resp); err != nil { - return nil, foundV2, PingResponseError{ - Err: err, - } - } - - return challengeManager, foundV2, 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 6bb9258c9..000000000 --- a/vendor/github.com/docker/docker/registry/config.go +++ /dev/null @@ -1,436 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "fmt" - "net" - "net/url" - "regexp" - "strconv" - "strings" - - "github.com/docker/distribution/reference" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/pkg/errors" - "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 struct { - registrytypes.ServiceConfig -} - -var ( - // DefaultNamespace is the default namespace - DefaultNamespace = "docker.io" - // DefaultRegistryVersionHeader is the name of the default HTTP header - // that carries Registry version info - DefaultRegistryVersionHeader = "Docker-Distribution-Api-Version" - - // IndexHostname is the index hostname - 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" - - // DefaultV2Registry is the URI of the default v2 registry - DefaultV2Registry = &url.URL{ - Scheme: "https", - Host: "registry-1.docker.io", - } -) - -var ( - // ErrInvalidRepositoryName is an error returned if the repository name did - // not have the correct form - ErrInvalidRepositoryName = errors.New("Invalid repository name (ex: \"registry.domain.tld/myrepos\")") - - emptyServiceConfig, _ = newServiceConfig(ServiceOptions{}) -) - -var ( - validHostPortRegex = regexp.MustCompile(`^` + reference.DomainRegexp.String() + `$`) -) - -// for mocking in unit tests -var lookupIP = net.LookupIP - -// newServiceConfig returns a new instance of ServiceConfig -func newServiceConfig(options ServiceOptions) (*serviceConfig, error) { - config := &serviceConfig{ - ServiceConfig: registrytypes.ServiceConfig{ - InsecureRegistryCIDRs: make([]*registrytypes.NetIPNet, 0), - IndexConfigs: make(map[string]*registrytypes.IndexInfo), - // Hack: Bypass setting the mirrors to IndexConfigs since they are going away - // and Mirrors are only for the official registry anyways. - }, - } - 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 -} - -// LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries into config. -func (config *serviceConfig) LoadAllowNondistributableArtifacts(registries []string) error { - cidrs := map[string]*registrytypes.NetIPNet{} - hostnames := map[string]bool{} - - for _, r := range registries { - if _, err := ValidateIndexName(r); err != nil { - return err - } - if validateNoScheme(r) != nil { - return fmt.Errorf("allow-nondistributable-artifacts registry %s should not contain '://'", r) - } - - if _, ipnet, err := net.ParseCIDR(r); err == nil { - // Valid CIDR. - cidrs[ipnet.String()] = (*registrytypes.NetIPNet)(ipnet) - } else if err := validateHostPort(r); err == nil { - // Must be `host:port` if not CIDR. - hostnames[r] = true - } else { - return fmt.Errorf("allow-nondistributable-artifacts registry %s is not valid: %v", r, err) - } - } - - config.AllowNondistributableArtifactsCIDRs = make([]*(registrytypes.NetIPNet), 0) - for _, c := range cidrs { - config.AllowNondistributableArtifactsCIDRs = append(config.AllowNondistributableArtifactsCIDRs, c) - } - - config.AllowNondistributableArtifactsHostnames = make([]string, 0) - 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[IndexName] = ®istrytypes.IndexInfo{ - Name: IndexName, - Mirrors: config.Mirrors, - 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 (especially on Boot2docker). - // - // TODO: should we deprecate this once it is easier for people to set up a TLS registry or change - // daemon flags on boot2docker? - registries = append(registries, "127.0.0.0/8") - - // Store original InsecureRegistryCIDRs and IndexConfigs - // Clean InsecureRegistryCIDRs and IndexConfigs in config, as passed registries has all insecure registry info. - originalCIDRs := config.ServiceConfig.InsecureRegistryCIDRs - originalIndexInfos := config.ServiceConfig.IndexConfigs - - config.ServiceConfig.InsecureRegistryCIDRs = make([]*registrytypes.NetIPNet, 0) - config.ServiceConfig.IndexConfigs = make(map[string]*registrytypes.IndexInfo) - -skip: - for _, r := range registries { - // validate insecure registry - if _, err := ValidateIndexName(r); err != nil { - // before returning err, roll back to original data - config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs - config.ServiceConfig.IndexConfigs = originalIndexInfos - 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 validateNoScheme(r) != nil { - // Insecure registry should not contain '://' - // before returning err, roll back to original data - config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs - config.ServiceConfig.IndexConfigs = originalIndexInfos - return fmt.Errorf("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 := (*registrytypes.NetIPNet)(ipnet) - for _, value := range config.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 - config.InsecureRegistryCIDRs = append(config.InsecureRegistryCIDRs, data) - - } else { - if err := validateHostPort(r); err != nil { - config.ServiceConfig.InsecureRegistryCIDRs = originalCIDRs - config.ServiceConfig.IndexConfigs = originalIndexInfos - return fmt.Errorf("insecure registry %s is not valid: %v", r, err) - - } - // Assume `host:port` if not CIDR. - config.IndexConfigs[r] = ®istrytypes.IndexInfo{ - Name: r, - Mirrors: make([]string, 0), - Secure: false, - Official: false, - } - } - } - - // Configure public registry. - config.IndexConfigs[IndexName] = ®istrytypes.IndexInfo{ - Name: IndexName, - Mirrors: config.Mirrors, - Secure: true, - Official: true, - } - - 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 allowNondistributableArtifacts(config *serviceConfig, 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 isSecureIndex(config *serviceConfig, 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 []*registrytypes.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 "", fmt.Errorf("invalid mirror: %q is not a valid URI", val) - } - if uri.Scheme != "http" && uri.Scheme != "https" { - return "", fmt.Errorf("invalid mirror: unsupported scheme %q in %q", uri.Scheme, uri) - } - if (uri.Path != "" && uri.Path != "/") || uri.RawQuery != "" || uri.Fragment != "" { - return "", fmt.Errorf("invalid mirror: path, 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 "", fmt.Errorf("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 "", fmt.Errorf("invalid index name (%s). Cannot begin or end with a hyphen", val) - } - return val, nil -} - -func validateNoScheme(reposName string) error { - if strings.Contains(reposName, "://") { - // It cannot contain a scheme! - return ErrInvalidRepositoryName - } - return nil -} - -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 fmt.Errorf("invalid host %q", host) - } - if port != "" { - v, err := strconv.Atoi(port) - if err != nil { - return err - } - if v < 0 || v > 65535 { - return fmt.Errorf("invalid port %q", port) - } - } - return nil -} - -// newIndexInfo returns IndexInfo configuration from indexName -func newIndexInfo(config *serviceConfig, indexName string) (*registrytypes.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. - index := ®istrytypes.IndexInfo{ - Name: indexName, - Mirrors: make([]string, 0), - Official: false, - } - index.Secure = isSecureIndex(config, indexName) - return index, 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 *registrytypes.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. -func ParseSearchIndexInfo(reposName string) (*registrytypes.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 20fb47bca..000000000 --- a/vendor/github.com/docker/docker/registry/config_unix.go +++ /dev/null @@ -1,16 +0,0 @@ -// +build !windows - -package registry // import "github.com/docker/docker/registry" - -var ( - // CertsDir is the directory where certificates are stored - CertsDir = "/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 6de0508f8..000000000 --- a/vendor/github.com/docker/docker/registry/config_windows.go +++ /dev/null @@ -1,18 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "os" - "path/filepath" - "strings" -) - -// CertsDir is the directory where certificates are stored -var CertsDir = 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.Replace(s, ":", "", -1)) -} 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 832fdb95a..000000000 --- a/vendor/github.com/docker/docker/registry/endpoint_v1.go +++ /dev/null @@ -1,198 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "crypto/tls" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/docker/distribution/registry/client/transport" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/sirupsen/logrus" -) - -// 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. -func NewV1Endpoint(index *registrytypes.IndexInfo, userAgent string, metaHeaders http.Header) (*V1Endpoint, error) { - tlsConfig, err := newTLSConfig(index.Name, index.Secure) - if err != nil { - return nil, err - } - - endpoint, err := newV1EndpointFromStr(GetAuthConfigKey(index), tlsConfig, userAgent, metaHeaders) - if err != nil { - return nil, err - } - - if err := validateEndpoint(endpoint); 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 fmt.Errorf("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.Debugf("Error from registry %q marked as insecure: %v. Insecurely falling back to HTTP", endpoint, err) - endpoint.URL.Scheme = "http" - - var err2 error - if _, err2 = endpoint.Ping(); err2 == nil { - return nil - } - - return fmt.Errorf("invalid registry endpoint %q. HTTPS attempt: %v. HTTP attempt: %v", endpoint, err, err2) - } - - return nil -} - -func newV1Endpoint(address url.URL, tlsConfig *tls.Config, userAgent string, metaHeaders http.Header) *V1Endpoint { - endpoint := &V1Endpoint{ - IsSecure: tlsConfig == nil || !tlsConfig.InsecureSkipVerify, - URL: new(url.URL), - } - - *endpoint.URL = address - - // TODO(tiborvass): make sure a ConnectTimeout transport is used - tr := NewTransport(tlsConfig) - endpoint.client = HTTPClient(transport.NewTransport(tr, Headers(userAgent, metaHeaders)...)) - return endpoint -} - -// 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) { - var ( - chunks []string - apiVersionStr string - ) - - if strings.HasSuffix(address, "/") { - address = address[:len(address)-1] - } - - 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 "", fmt.Errorf("unsupported V1 version path %s", apiVersionStr) - } - } - - return address, nil -} - -func newV1EndpointFromStr(address string, tlsConfig *tls.Config, userAgent string, metaHeaders 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, err - } - - endpoint := newV1Endpoint(*uri, tlsConfig, userAgent, metaHeaders) - if err != nil { - return nil, err - } - - return endpoint, nil -} - -// Get the formatted URL for the root of this registry Endpoint -func (e *V1Endpoint) String() string { - return e.URL.String() + "/v1/" -} - -// Path returns a formatted string for the URL -// of this endpoint with the given path appended. -func (e *V1Endpoint) Path(path string) string { - return e.URL.String() + "/v1/" + path -} - -// Ping returns a PingResult which indicates whether the registry is standalone or not. -func (e *V1Endpoint) Ping() (PingResult, error) { - logrus.Debugf("attempting v1 ping for registry endpoint %s", e) - - 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 PingResult{Standalone: false}, nil - } - - req, err := http.NewRequest("GET", e.Path("_ping"), nil) - if err != nil { - return PingResult{Standalone: false}, err - } - - resp, err := e.client.Do(req) - if err != nil { - return PingResult{Standalone: false}, err - } - - defer resp.Body.Close() - - jsonString, err := ioutil.ReadAll(resp.Body) - if err != nil { - return PingResult{Standalone: false}, fmt.Errorf("error while reading the http response: %s", err) - } - - // If the header is absent, we assume true for compatibility with earlier - // versions of the registry. default to true - info := PingResult{ - Standalone: true, - } - if err := json.Unmarshal(jsonString, &info); err != nil { - logrus.Debugf("Error unmarshaling the _ping PingResult: %s", err) - // don't stop here. Just assume sane defaults - } - if hdr := resp.Header.Get("X-Docker-Registry-Version"); hdr != "" { - logrus.Debugf("Registry version header: '%s'", hdr) - info.Version = hdr - } - logrus.Debugf("PingResult.Version: %q", info.Version) - - standalone := resp.Header.Get("X-Docker-Registry-Standalone") - logrus.Debugf("Registry standalone header: '%s'", 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("PingResult.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 5bab02e5e..000000000 --- a/vendor/github.com/docker/docker/registry/errors.go +++ /dev/null @@ -1,31 +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" -) - -type notFoundError string - -func (e notFoundError) Error() string { - return string(e) -} - -func (notFoundError) NotFound() {} - -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 -} 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 6727b7dc3..000000000 --- a/vendor/github.com/docker/docker/registry/registry.go +++ /dev/null @@ -1,191 +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" - "errors" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "path/filepath" - "strings" - "time" - - "github.com/docker/distribution/registry/client/transport" - "github.com/docker/go-connections/sockets" - "github.com/docker/go-connections/tlsconfig" - "github.com/sirupsen/logrus" -) - -var ( - // ErrAlreadyExists is an error returned if an image being pushed - // already exists on the remote side - ErrAlreadyExists = errors.New("Image already exists") -) - -func newTLSConfig(hostname string, isSecure bool) (*tls.Config, error) { - // PreferredServerCipherSuites should have no effect - tlsConfig := tlsconfig.ServerDefault() - - tlsConfig.InsecureSkipVerify = !isSecure - - if isSecure && CertsDir != "" { - hostDir := filepath.Join(CertsDir, cleanPath(hostname)) - logrus.Debugf("hostDir: %s", hostDir) - if err := ReadCertsDirectory(tlsConfig, hostDir); err != nil { - return nil, err - } - } - - return tlsConfig, nil -} - -func hasFile(files []os.FileInfo, 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 := ioutil.ReadDir(directory) - if err != nil && !os.IsNotExist(err) { - return err - } - - for _, f := range fs { - if strings.HasSuffix(f.Name(), ".crt") { - if tlsConfig.RootCAs == nil { - systemPool, err := tlsconfig.SystemCertPool() - if err != nil { - return fmt.Errorf("unable to get system cert pool: %v", err) - } - tlsConfig.RootCAs = systemPool - } - logrus.Debugf("crt: %s", filepath.Join(directory, f.Name())) - data, err := ioutil.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 fmt.Errorf("missing key %s for client certificate %s. Note that CA certificates should 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 fmt.Errorf("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, - DualStack: true, - } - - base := &http.Transport{ - Proxy: http.ProxyFromEnvironment, - Dial: direct.Dial, - TLSHandshakeTimeout: 10 * time.Second, - TLSClientConfig: tlsConfig, - // TODO(dmcgowan): Call close idle connections when complete and use keep alive - DisableKeepAlives: true, - } - - proxyDialer, err := sockets.DialerFromEnvironment(direct) - if err == nil { - base.Dial = proxyDialer.Dial - } - return base -} diff --git a/vendor/github.com/docker/docker/registry/resumable/resumablerequestreader.go b/vendor/github.com/docker/docker/registry/resumable/resumablerequestreader.go deleted file mode 100644 index 8e97a1a4d..000000000 --- a/vendor/github.com/docker/docker/registry/resumable/resumablerequestreader.go +++ /dev/null @@ -1,96 +0,0 @@ -package resumable // import "github.com/docker/docker/registry/resumable" - -import ( - "fmt" - "io" - "net/http" - "time" - - "github.com/sirupsen/logrus" -) - -type requestReader struct { - client *http.Client - request *http.Request - lastRange int64 - totalSize int64 - currentResponse *http.Response - failures uint32 - maxFailures uint32 - waitDuration time.Duration -} - -// NewRequestReader makes it possible to resume reading a request's body transparently -// maxfail is the number of times we retry to make requests again (not resumes) -// totalsize is the total length of the body; auto detect if not provided -func NewRequestReader(c *http.Client, r *http.Request, maxfail uint32, totalsize int64) io.ReadCloser { - return &requestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize, waitDuration: 5 * time.Second} -} - -// NewRequestReaderWithInitialResponse makes it possible to resume -// reading the body of an already initiated request. -func NewRequestReaderWithInitialResponse(c *http.Client, r *http.Request, maxfail uint32, totalsize int64, initialResponse *http.Response) io.ReadCloser { - return &requestReader{client: c, request: r, maxFailures: maxfail, totalSize: totalsize, currentResponse: initialResponse, waitDuration: 5 * time.Second} -} - -func (r *requestReader) Read(p []byte) (n int, err error) { - if r.client == nil || r.request == nil { - return 0, fmt.Errorf("client and request can't be nil") - } - isFreshRequest := false - if r.lastRange != 0 && r.currentResponse == nil { - readRange := fmt.Sprintf("bytes=%d-%d", r.lastRange, r.totalSize) - r.request.Header.Set("Range", readRange) - time.Sleep(r.waitDuration) - } - if r.currentResponse == nil { - r.currentResponse, err = r.client.Do(r.request) - isFreshRequest = true - } - if err != nil && r.failures+1 != r.maxFailures { - r.cleanUpResponse() - r.failures++ - time.Sleep(time.Duration(r.failures) * r.waitDuration) - return 0, nil - } else if err != nil { - r.cleanUpResponse() - return 0, err - } - if r.currentResponse.StatusCode == 416 && r.lastRange == r.totalSize && r.currentResponse.ContentLength == 0 { - r.cleanUpResponse() - return 0, io.EOF - } else if r.currentResponse.StatusCode != 206 && r.lastRange != 0 && isFreshRequest { - r.cleanUpResponse() - return 0, fmt.Errorf("the server doesn't support byte ranges") - } - if r.totalSize == 0 { - r.totalSize = r.currentResponse.ContentLength - } else if r.totalSize <= 0 { - r.cleanUpResponse() - return 0, fmt.Errorf("failed to auto detect content length") - } - n, err = r.currentResponse.Body.Read(p) - r.lastRange += int64(n) - if err != nil { - r.cleanUpResponse() - } - if err != nil && err != io.EOF { - logrus.Infof("encountered error during pull and clearing it before resume: %s", err) - err = nil - } - return n, err -} - -func (r *requestReader) Close() error { - r.cleanUpResponse() - r.client = nil - r.request = nil - return nil -} - -func (r *requestReader) cleanUpResponse() { - if r.currentResponse != nil { - r.currentResponse.Body.Close() - r.currentResponse = nil - } -} 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 08f5c7a4e..000000000 --- a/vendor/github.com/docker/docker/registry/service.go +++ /dev/null @@ -1,313 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "context" - "crypto/tls" - "net/http" - "net/url" - "strings" - "sync" - - "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/client/auth" - "github.com/docker/docker/api/types" - registrytypes "github.com/docker/docker/api/types/registry" - "github.com/docker/docker/errdefs" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -const ( - // DefaultSearchLimit is the default value for maximum number of returned search results. - DefaultSearchLimit = 25 -) - -// Service is the interface defining what a registry service should implement. -type Service interface { - Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) - LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) - LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) - ResolveRepository(name reference.Named) (*RepositoryInfo, error) - Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) - ServiceConfig() *registrytypes.ServiceConfig - TLSConfig(hostname string) (*tls.Config, error) - LoadAllowNondistributableArtifacts([]string) error - LoadMirrors([]string) error - LoadInsecureRegistries([]string) error -} - -// DefaultService is a registry service. It tracks configuration data such as a list -// of mirrors. -type DefaultService struct { - config *serviceConfig - mu sync.Mutex -} - -// NewService returns a new instance of DefaultService ready to be -// installed into an engine. -func NewService(options ServiceOptions) (*DefaultService, error) { - config, err := newServiceConfig(options) - - return &DefaultService{config: config}, err -} - -// ServiceConfig returns the public registry service configuration. -func (s *DefaultService) ServiceConfig() *registrytypes.ServiceConfig { - s.mu.Lock() - defer s.mu.Unlock() - - servConfig := registrytypes.ServiceConfig{ - AllowNondistributableArtifactsCIDRs: make([]*(registrytypes.NetIPNet), 0), - AllowNondistributableArtifactsHostnames: make([]string, 0), - InsecureRegistryCIDRs: make([]*(registrytypes.NetIPNet), 0), - IndexConfigs: make(map[string]*(registrytypes.IndexInfo)), - Mirrors: make([]string, 0), - } - - // construct a new ServiceConfig which will not retrieve s.Config directly, - // and look up items in s.config with mu locked - servConfig.AllowNondistributableArtifactsCIDRs = append(servConfig.AllowNondistributableArtifactsCIDRs, s.config.ServiceConfig.AllowNondistributableArtifactsCIDRs...) - servConfig.AllowNondistributableArtifactsHostnames = append(servConfig.AllowNondistributableArtifactsHostnames, s.config.ServiceConfig.AllowNondistributableArtifactsHostnames...) - servConfig.InsecureRegistryCIDRs = append(servConfig.InsecureRegistryCIDRs, s.config.ServiceConfig.InsecureRegistryCIDRs...) - - for key, value := range s.config.ServiceConfig.IndexConfigs { - servConfig.IndexConfigs[key] = value - } - - servConfig.Mirrors = append(servConfig.Mirrors, s.config.ServiceConfig.Mirrors...) - - return &servConfig -} - -// LoadAllowNondistributableArtifacts loads allow-nondistributable-artifacts registries for Service. -func (s *DefaultService) LoadAllowNondistributableArtifacts(registries []string) error { - s.mu.Lock() - defer s.mu.Unlock() - - return s.config.LoadAllowNondistributableArtifacts(registries) -} - -// LoadMirrors loads registry mirrors for Service -func (s *DefaultService) LoadMirrors(mirrors []string) error { - s.mu.Lock() - defer s.mu.Unlock() - - return s.config.LoadMirrors(mirrors) -} - -// LoadInsecureRegistries loads insecure registries for Service -func (s *DefaultService) 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 *DefaultService) Auth(ctx context.Context, authConfig *types.AuthConfig, userAgent string) (status, token string, err error) { - // TODO Use ctx when searching for repositories - serverAddress := authConfig.ServerAddress - if serverAddress == "" { - serverAddress = IndexServer - } - if !strings.HasPrefix(serverAddress, "https://") && !strings.HasPrefix(serverAddress, "http://") { - serverAddress = "https://" + serverAddress - } - u, err := url.Parse(serverAddress) - if err != nil { - return "", "", errdefs.InvalidParameter(errors.Errorf("unable to parse server address: %v", err)) - } - - endpoints, err := s.LookupPushEndpoints(u.Host) - if err != nil { - return "", "", errdefs.InvalidParameter(err) - } - - for _, endpoint := range endpoints { - login := loginV2 - if endpoint.Version == APIVersion1 { - login = loginV1 - } - - status, token, err = login(authConfig, endpoint, userAgent) - if err == nil { - return - } - if fErr, ok := err.(fallbackError); ok { - err = fErr.err - logrus.Infof("Error logging in to %s endpoint, trying next endpoint: %v", endpoint.Version, err) - continue - } - - return "", "", err - } - - 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) - var indexName, remoteName string - if len(nameParts) == 1 || (!strings.Contains(nameParts[0], ".") && - !strings.Contains(nameParts[0], ":") && nameParts[0] != "localhost") { - // This is a Docker Index repos (ex: samalba/hipache or ubuntu) - // 'docker.io' - indexName = IndexName - remoteName = reposName - } else { - indexName = nameParts[0] - remoteName = nameParts[1] - } - return indexName, remoteName -} - -// Search queries the public registry for images matching the specified -// search terms, and returns the results. -func (s *DefaultService) Search(ctx context.Context, term string, limit int, authConfig *types.AuthConfig, userAgent string, headers map[string][]string) (*registrytypes.SearchResults, error) { - // TODO Use ctx when searching for repositories - if err := validateNoScheme(term); err != nil { - return nil, err - } - - indexName, remoteName := splitReposSearchTerm(term) - - // Search is a long-running operation, just lock s.config to avoid block others. - s.mu.Lock() - index, err := newIndexInfo(s.config, indexName) - s.mu.Unlock() - - if err != nil { - return nil, err - } - - // *TODO: Search multiple indexes. - endpoint, err := NewV1Endpoint(index, userAgent, http.Header(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"}, - }, - } - - modifiers := Headers(userAgent, nil) - v2Client, foundV2, err := v2AuthHTTPClient(endpoint.URL, endpoint.client.Transport, modifiers, creds, scopes) - if err != nil { - if fErr, ok := err.(fallbackError); ok { - logrus.Errorf("Cannot use identity token for search, v2 auth not supported: %v", fErr.err) - } else { - return nil, err - } - } else if foundV2 { - // 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 - } - } - - if client == nil { - client = endpoint.client - if err := authorizeClient(client, authConfig, endpoint); err != nil { - return nil, err - } - } - - r := newSession(client, authConfig, endpoint) - - if index.Official { - localName := remoteName - if strings.HasPrefix(localName, "library/") { - // If pull "library/foo", it's stored locally under "foo" - localName = strings.SplitN(localName, "/", 2)[1] - } - - return r.SearchRepositories(localName, limit) - } - return r.SearchRepositories(remoteName, limit) -} - -// ResolveRepository splits a repository name into its components -// and configuration of the associated registry. -func (s *DefaultService) ResolveRepository(name reference.Named) (*RepositoryInfo, error) { - s.mu.Lock() - defer s.mu.Unlock() - 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 -} - -// ToV1Endpoint returns a V1 API endpoint based on the APIEndpoint -func (e APIEndpoint) ToV1Endpoint(userAgent string, metaHeaders http.Header) *V1Endpoint { - return newV1Endpoint(*e.URL, e.TLSConfig, userAgent, metaHeaders) -} - -// TLSConfig constructs a client TLS configuration based on server defaults -func (s *DefaultService) TLSConfig(hostname string) (*tls.Config, error) { - s.mu.Lock() - defer s.mu.Unlock() - - return newTLSConfig(hostname, isSecureIndex(s.config, hostname)) -} - -// tlsConfig constructs a client TLS configuration based on server defaults -func (s *DefaultService) tlsConfig(hostname string) (*tls.Config, error) { - return newTLSConfig(hostname, isSecureIndex(s.config, hostname)) -} - -func (s *DefaultService) tlsConfigForMirror(mirrorURL *url.URL) (*tls.Config, error) { - return s.tlsConfig(mirrorURL.Host) -} - -// LookupPullEndpoints creates a list of endpoints to try to pull from, in order of preference. -// It gives preference to v2 endpoints over v1, mirrors over the actual -// registry, and HTTPS over plain HTTP. -func (s *DefaultService) LookupPullEndpoints(hostname string) (endpoints []APIEndpoint, err error) { - s.mu.Lock() - defer s.mu.Unlock() - - return s.lookupEndpoints(hostname) -} - -// LookupPushEndpoints creates a list of endpoints to try to push to, in order of preference. -// It gives preference to v2 endpoints over v1, and HTTPS over plain HTTP. -// Mirrors are not included. -func (s *DefaultService) LookupPushEndpoints(hostname string) (endpoints []APIEndpoint, err error) { - s.mu.Lock() - defer s.mu.Unlock() - - allEndpoints, err := s.lookupEndpoints(hostname) - if err == nil { - for _, endpoint := range allEndpoints { - if !endpoint.Mirror { - endpoints = append(endpoints, endpoint) - } - } - } - return endpoints, err -} - -func (s *DefaultService) lookupEndpoints(hostname string) (endpoints []APIEndpoint, err error) { - return s.lookupV2Endpoints(hostname) -} 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 1a4c9e310..000000000 --- a/vendor/github.com/docker/docker/registry/service_v2.go +++ /dev/null @@ -1,82 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "net/url" - "strings" - - "github.com/docker/go-connections/tlsconfig" -) - -func (s *DefaultService) lookupV2Endpoints(hostname string) (endpoints []APIEndpoint, err error) { - tlsConfig := tlsconfig.ServerDefault() - if hostname == DefaultNamespace || hostname == IndexHostname { - // v2 mirrors - 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, err - } - mirrorTLSConfig, err := s.tlsConfigForMirror(mirrorURL) - if err != nil { - return nil, err - } - endpoints = append(endpoints, APIEndpoint{ - URL: mirrorURL, - // guess mirrors are v2 - Version: APIVersion2, - Mirror: true, - TrimHostname: true, - TLSConfig: mirrorTLSConfig, - }) - } - // v2 registry - endpoints = append(endpoints, APIEndpoint{ - URL: DefaultV2Registry, - Version: APIVersion2, - Official: true, - TrimHostname: true, - TLSConfig: tlsConfig, - }) - - return endpoints, nil - } - - ana := allowNondistributableArtifacts(s.config, hostname) - - tlsConfig, err = s.tlsConfig(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 ef1429959..000000000 --- a/vendor/github.com/docker/docker/registry/session.go +++ /dev/null @@ -1,779 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "bytes" - "crypto/sha256" - // this is required for some certificates - _ "crypto/sha512" - "encoding/hex" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/http/cookiejar" - "net/url" - "strconv" - "strings" - "sync" - - "github.com/docker/distribution/reference" - "github.com/docker/distribution/registry/api/errcode" - "github.com/docker/docker/api/types" - registrytypes "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/docker/docker/pkg/stringid" - "github.com/docker/docker/pkg/tarsum" - "github.com/docker/docker/registry/resumable" - "github.com/pkg/errors" - "github.com/sirupsen/logrus" -) - -var ( - // ErrRepoNotFound is returned if the repository didn't exist on the - // remote side - ErrRepoNotFound notFoundError = "Repository not found" -) - -// A Session is used to communicate with a V1 registry -type Session struct { - indexEndpoint *V1Endpoint - client *http.Client - // TODO(tiborvass): remove authConfig - authConfig *types.AuthConfig - id string -} - -type authTransport struct { - http.RoundTripper - *types.AuthConfig - - alwaysSetBasicAuth bool - token []string - - mu sync.Mutex // guards modReq - modReq map[*http.Request]*http.Request // original -> modified -} - -// AuthTransport 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 AuthTransport(base http.RoundTripper, authConfig *types.AuthConfig, alwaysSetBasicAuth bool) http.RoundTripper { - 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 { - delete(tr.modReq, orig) - 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 *types.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 = AuthTransport(client.Transport, authConfig, alwaysSetBasicAuth) - - jar, err := cookiejar.New(nil) - if err != nil { - return errors.New("cookiejar.New is not supposed to return an error") - } - client.Jar = jar - - return nil -} - -func newSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) *Session { - return &Session{ - authConfig: authConfig, - client: client, - indexEndpoint: endpoint, - id: stringid.GenerateRandomID(), - } -} - -// NewSession creates a new session -// TODO(tiborvass): remove authConfig param once registry client v2 is vendored -func NewSession(client *http.Client, authConfig *types.AuthConfig, endpoint *V1Endpoint) (*Session, error) { - if err := authorizeClient(client, authConfig, endpoint); err != nil { - return nil, err - } - - return newSession(client, authConfig, endpoint), nil -} - -// ID returns this registry session's ID. -func (r *Session) ID() string { - return r.id -} - -// GetRemoteHistory retrieves the history of a given image from the registry. -// It returns a list of the parent's JSON files (including the requested image). -func (r *Session) GetRemoteHistory(imgID, registry string) ([]string, error) { - res, err := r.client.Get(registry + "images/" + imgID + "/ancestry") - if err != nil { - return nil, err - } - defer res.Body.Close() - if res.StatusCode != 200 { - if res.StatusCode == 401 { - return nil, errcode.ErrorCodeUnauthorized.WithArgs() - } - return nil, newJSONError(fmt.Sprintf("Server error: %d trying to fetch remote history for %s", res.StatusCode, imgID), res) - } - - var history []string - if err := json.NewDecoder(res.Body).Decode(&history); err != nil { - return nil, fmt.Errorf("Error while reading the http response: %v", err) - } - - logrus.Debugf("Ancestry: %v", history) - return history, nil -} - -// LookupRemoteImage checks if an image exists in the registry -func (r *Session) LookupRemoteImage(imgID, registry string) error { - res, err := r.client.Get(registry + "images/" + imgID + "/json") - if err != nil { - return err - } - res.Body.Close() - if res.StatusCode != 200 { - return newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) - } - return nil -} - -// GetRemoteImageJSON retrieves an image's JSON metadata from the registry. -func (r *Session) GetRemoteImageJSON(imgID, registry string) ([]byte, int64, error) { - res, err := r.client.Get(registry + "images/" + imgID + "/json") - if err != nil { - return nil, -1, fmt.Errorf("Failed to download json: %s", err) - } - defer res.Body.Close() - if res.StatusCode != 200 { - return nil, -1, newJSONError(fmt.Sprintf("HTTP code %d", res.StatusCode), res) - } - // if the size header is not present, then set it to '-1' - imageSize := int64(-1) - if hdr := res.Header.Get("X-Docker-Size"); hdr != "" { - imageSize, err = strconv.ParseInt(hdr, 10, 64) - if err != nil { - return nil, -1, err - } - } - - jsonString, err := ioutil.ReadAll(res.Body) - if err != nil { - return nil, -1, fmt.Errorf("Failed to parse downloaded json: %v (%s)", err, jsonString) - } - return jsonString, imageSize, nil -} - -// GetRemoteImageLayer retrieves an image layer from the registry -func (r *Session) GetRemoteImageLayer(imgID, registry string, imgSize int64) (io.ReadCloser, error) { - var ( - statusCode = 0 - res *http.Response - err error - imageURL = fmt.Sprintf("%simages/%s/layer", registry, imgID) - ) - - req, err := http.NewRequest("GET", imageURL, nil) - if err != nil { - return nil, fmt.Errorf("Error while getting from the server: %v", err) - } - - res, err = r.client.Do(req) - if err != nil { - logrus.Debugf("Error contacting registry %s: %v", registry, err) - // the only case err != nil && res != nil is https://golang.org/src/net/http/client.go#L515 - if res != nil { - if res.Body != nil { - res.Body.Close() - } - statusCode = res.StatusCode - } - return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", - statusCode, imgID) - } - - if res.StatusCode != 200 { - res.Body.Close() - return nil, fmt.Errorf("Server error: Status %d while fetching image layer (%s)", - res.StatusCode, imgID) - } - - if res.Header.Get("Accept-Ranges") == "bytes" && imgSize > 0 { - logrus.Debug("server supports resume") - return resumable.NewRequestReaderWithInitialResponse(r.client, req, 5, imgSize, res), nil - } - logrus.Debug("server doesn't support resume") - return res.Body, nil -} - -// GetRemoteTag retrieves the tag named in the askedTag argument from the given -// repository. It queries each of the registries supplied in the registries -// argument, and returns data from the first one that answers the query -// successfully. -func (r *Session) GetRemoteTag(registries []string, repositoryRef reference.Named, askedTag string) (string, error) { - repository := reference.Path(repositoryRef) - - if strings.Count(repository, "/") == 0 { - // This will be removed once the registry supports auto-resolution on - // the "library" namespace - repository = "library/" + repository - } - for _, host := range registries { - endpoint := fmt.Sprintf("%srepositories/%s/tags/%s", host, repository, askedTag) - res, err := r.client.Get(endpoint) - if err != nil { - return "", err - } - - logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) - defer res.Body.Close() - - if res.StatusCode == 404 { - return "", ErrRepoNotFound - } - if res.StatusCode != 200 { - continue - } - - var tagID string - if err := json.NewDecoder(res.Body).Decode(&tagID); err != nil { - return "", err - } - return tagID, nil - } - return "", fmt.Errorf("Could not reach any registry endpoint") -} - -// GetRemoteTags retrieves all tags from the given repository. It queries each -// of the registries supplied in the registries argument, and returns data from -// the first one that answers the query successfully. It returns a map with -// tag names as the keys and image IDs as the values. -func (r *Session) GetRemoteTags(registries []string, repositoryRef reference.Named) (map[string]string, error) { - repository := reference.Path(repositoryRef) - - if strings.Count(repository, "/") == 0 { - // This will be removed once the registry supports auto-resolution on - // the "library" namespace - repository = "library/" + repository - } - for _, host := range registries { - endpoint := fmt.Sprintf("%srepositories/%s/tags", host, repository) - res, err := r.client.Get(endpoint) - if err != nil { - return nil, err - } - - logrus.Debugf("Got status code %d from %s", res.StatusCode, endpoint) - defer res.Body.Close() - - if res.StatusCode == 404 { - return nil, ErrRepoNotFound - } - if res.StatusCode != 200 { - continue - } - - result := make(map[string]string) - if err := json.NewDecoder(res.Body).Decode(&result); err != nil { - return nil, err - } - return result, nil - } - return nil, fmt.Errorf("Could not reach any registry endpoint") -} - -func buildEndpointsList(headers []string, indexEp string) ([]string, error) { - var endpoints []string - parsedURL, err := url.Parse(indexEp) - if err != nil { - return nil, err - } - var urlScheme = parsedURL.Scheme - // The registry's URL scheme has to match the Index' - for _, ep := range headers { - epList := strings.Split(ep, ",") - for _, epListElement := range epList { - endpoints = append( - endpoints, - fmt.Sprintf("%s://%s/v1/", urlScheme, strings.TrimSpace(epListElement))) - } - } - return endpoints, nil -} - -// GetRepositoryData returns lists of images and endpoints for the repository -func (r *Session) GetRepositoryData(name reference.Named) (*RepositoryData, error) { - repositoryTarget := fmt.Sprintf("%srepositories/%s/images", r.indexEndpoint.String(), reference.Path(name)) - - logrus.Debugf("[registry] Calling GET %s", repositoryTarget) - - req, err := http.NewRequest("GET", repositoryTarget, nil) - if err != nil { - return nil, err - } - // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests - req.Header.Set("X-Docker-Token", "true") - res, err := r.client.Do(req) - if err != nil { - // check if the error is because of i/o timeout - // and return a non-obtuse error message for users - // "Get https://index.docker.io/v1/repositories/library/busybox/images: i/o timeout" - // was a top search on the docker user forum - if isTimeout(err) { - return nil, fmt.Errorf("network timed out while trying to connect to %s. You may want to check your internet connection or if you are behind a proxy", repositoryTarget) - } - return nil, fmt.Errorf("Error while pulling image: %v", err) - } - defer res.Body.Close() - if res.StatusCode == 401 { - return nil, errcode.ErrorCodeUnauthorized.WithArgs() - } - // TODO: Right now we're ignoring checksums in the response body. - // In the future, we need to use them to check image validity. - if res.StatusCode == 404 { - return nil, newJSONError(fmt.Sprintf("HTTP code: %d", res.StatusCode), res) - } else if res.StatusCode != 200 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - logrus.Debugf("Error reading response body: %s", err) - } - return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to pull repository %s: %q", res.StatusCode, reference.Path(name), errBody), res) - } - - var endpoints []string - if res.Header.Get("X-Docker-Endpoints") != "" { - endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) - if err != nil { - return nil, err - } - } else { - // Assume the endpoint is on the same host - endpoints = append(endpoints, fmt.Sprintf("%s://%s/v1/", r.indexEndpoint.URL.Scheme, req.URL.Host)) - } - - remoteChecksums := []*ImgData{} - if err := json.NewDecoder(res.Body).Decode(&remoteChecksums); err != nil { - return nil, err - } - - // Forge a better object from the retrieved data - imgsData := make(map[string]*ImgData, len(remoteChecksums)) - for _, elem := range remoteChecksums { - imgsData[elem.ID] = elem - } - - return &RepositoryData{ - ImgList: imgsData, - Endpoints: endpoints, - }, nil -} - -// PushImageChecksumRegistry uploads checksums for an image -func (r *Session) PushImageChecksumRegistry(imgData *ImgData, registry string) error { - u := registry + "images/" + imgData.ID + "/checksum" - - logrus.Debugf("[registry] Calling PUT %s", u) - - req, err := http.NewRequest("PUT", u, nil) - if err != nil { - return err - } - req.Header.Set("X-Docker-Checksum", imgData.Checksum) - req.Header.Set("X-Docker-Checksum-Payload", imgData.ChecksumPayload) - - res, err := r.client.Do(req) - if err != nil { - return fmt.Errorf("Failed to upload metadata: %v", err) - } - defer res.Body.Close() - if len(res.Cookies()) > 0 { - r.client.Jar.SetCookies(req.URL, res.Cookies()) - } - if res.StatusCode != 200 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return fmt.Errorf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err) - } - var jsonBody map[string]string - if err := json.Unmarshal(errBody, &jsonBody); err != nil { - errBody = []byte(err.Error()) - } else if jsonBody["error"] == "Image already exists" { - return ErrAlreadyExists - } - return fmt.Errorf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody) - } - return nil -} - -// PushImageJSONRegistry pushes JSON metadata for a local image to the registry -func (r *Session) PushImageJSONRegistry(imgData *ImgData, jsonRaw []byte, registry string) error { - - u := registry + "images/" + imgData.ID + "/json" - - logrus.Debugf("[registry] Calling PUT %s", u) - - req, err := http.NewRequest("PUT", u, bytes.NewReader(jsonRaw)) - if err != nil { - return err - } - req.Header.Add("Content-type", "application/json") - - res, err := r.client.Do(req) - if err != nil { - return fmt.Errorf("Failed to upload metadata: %s", err) - } - defer res.Body.Close() - if res.StatusCode == 401 && strings.HasPrefix(registry, "http://") { - return newJSONError("HTTP code 401, Docker will not send auth headers over HTTP.", res) - } - if res.StatusCode != 200 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) - } - var jsonBody map[string]string - if err := json.Unmarshal(errBody, &jsonBody); err != nil { - errBody = []byte(err.Error()) - } else if jsonBody["error"] == "Image already exists" { - return ErrAlreadyExists - } - return newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata: %q", res.StatusCode, errBody), res) - } - return nil -} - -// PushImageLayerRegistry sends the checksum of an image layer to the registry -func (r *Session) PushImageLayerRegistry(imgID string, layer io.Reader, registry string, jsonRaw []byte) (checksum string, checksumPayload string, err error) { - u := registry + "images/" + imgID + "/layer" - - logrus.Debugf("[registry] Calling PUT %s", u) - - tarsumLayer, err := tarsum.NewTarSum(layer, false, tarsum.Version0) - if err != nil { - return "", "", err - } - h := sha256.New() - h.Write(jsonRaw) - h.Write([]byte{'\n'}) - checksumLayer := io.TeeReader(tarsumLayer, h) - - req, err := http.NewRequest("PUT", u, checksumLayer) - if err != nil { - return "", "", err - } - req.Header.Add("Content-Type", "application/octet-stream") - req.ContentLength = -1 - req.TransferEncoding = []string{"chunked"} - res, err := r.client.Do(req) - if err != nil { - return "", "", fmt.Errorf("Failed to upload layer: %v", err) - } - if rc, ok := layer.(io.Closer); ok { - if err := rc.Close(); err != nil { - return "", "", err - } - } - defer res.Body.Close() - - if res.StatusCode != 200 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - return "", "", newJSONError(fmt.Sprintf("HTTP code %d while uploading metadata and error when trying to parse response body: %s", res.StatusCode, err), res) - } - return "", "", newJSONError(fmt.Sprintf("Received HTTP code %d while uploading layer: %q", res.StatusCode, errBody), res) - } - - checksumPayload = "sha256:" + hex.EncodeToString(h.Sum(nil)) - return tarsumLayer.Sum(jsonRaw), checksumPayload, nil -} - -// PushRegistryTag pushes a tag on the registry. -// Remote has the format '/ -func (r *Session) PushRegistryTag(remote reference.Named, revision, tag, registry string) error { - // "jsonify" the string - revision = "\"" + revision + "\"" - path := fmt.Sprintf("repositories/%s/tags/%s", reference.Path(remote), tag) - - req, err := http.NewRequest("PUT", registry+path, strings.NewReader(revision)) - if err != nil { - return err - } - req.Header.Add("Content-type", "application/json") - req.ContentLength = int64(len(revision)) - res, err := r.client.Do(req) - if err != nil { - return err - } - res.Body.Close() - if res.StatusCode != 200 && res.StatusCode != 201 { - return newJSONError(fmt.Sprintf("Internal server error: %d trying to push tag %s on %s", res.StatusCode, tag, reference.Path(remote)), res) - } - return nil -} - -// PushImageJSONIndex uploads an image list to the repository -func (r *Session) PushImageJSONIndex(remote reference.Named, imgList []*ImgData, validate bool, regs []string) (*RepositoryData, error) { - cleanImgList := []*ImgData{} - if validate { - for _, elem := range imgList { - if elem.Checksum != "" { - cleanImgList = append(cleanImgList, elem) - } - } - } else { - cleanImgList = imgList - } - - imgListJSON, err := json.Marshal(cleanImgList) - if err != nil { - return nil, err - } - var suffix string - if validate { - suffix = "images" - } - u := fmt.Sprintf("%srepositories/%s/%s", r.indexEndpoint.String(), reference.Path(remote), suffix) - logrus.Debugf("[registry] PUT %s", u) - logrus.Debugf("Image list pushed to index:\n%s", imgListJSON) - headers := map[string][]string{ - "Content-type": {"application/json"}, - // this will set basic auth in r.client.Transport and send cached X-Docker-Token headers for all subsequent requests - "X-Docker-Token": {"true"}, - } - if validate { - headers["X-Docker-Endpoints"] = regs - } - - // Redirect if necessary - var res *http.Response - for { - if res, err = r.putImageRequest(u, headers, imgListJSON); err != nil { - return nil, err - } - if !shouldRedirect(res) { - break - } - res.Body.Close() - u = res.Header.Get("Location") - logrus.Debugf("Redirected to %s", u) - } - defer res.Body.Close() - - if res.StatusCode == 401 { - return nil, errcode.ErrorCodeUnauthorized.WithArgs() - } - - var tokens, endpoints []string - if !validate { - if res.StatusCode != 200 && res.StatusCode != 201 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - logrus.Debugf("Error reading response body: %s", err) - } - return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push repository %s: %q", res.StatusCode, reference.Path(remote), errBody), res) - } - tokens = res.Header["X-Docker-Token"] - logrus.Debugf("Auth token: %v", tokens) - - if res.Header.Get("X-Docker-Endpoints") == "" { - return nil, fmt.Errorf("Index response didn't contain any endpoints") - } - endpoints, err = buildEndpointsList(res.Header["X-Docker-Endpoints"], r.indexEndpoint.String()) - if err != nil { - return nil, err - } - } else { - if res.StatusCode != 204 { - errBody, err := ioutil.ReadAll(res.Body) - if err != nil { - logrus.Debugf("Error reading response body: %s", err) - } - return nil, newJSONError(fmt.Sprintf("Error: Status %d trying to push checksums %s: %q", res.StatusCode, reference.Path(remote), errBody), res) - } - } - - return &RepositoryData{ - Endpoints: endpoints, - }, nil -} - -func (r *Session) putImageRequest(u string, headers map[string][]string, body []byte) (*http.Response, error) { - req, err := http.NewRequest("PUT", u, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.ContentLength = int64(len(body)) - for k, v := range headers { - req.Header[k] = v - } - response, err := r.client.Do(req) - if err != nil { - return nil, err - } - return response, nil -} - -func shouldRedirect(response *http.Response) bool { - return response.StatusCode >= 300 && response.StatusCode < 400 -} - -// SearchRepositories performs a search against the remote repository -func (r *Session) SearchRepositories(term string, limit int) (*registrytypes.SearchResults, error) { - if limit < 1 || limit > 100 { - return nil, errdefs.InvalidParameter(errors.Errorf("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("GET", u, nil) - if err != nil { - return nil, errors.Wrap(errdefs.InvalidParameter(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 != 200 { - return nil, newJSONError(fmt.Sprintf("Unexpected status code %d", res.StatusCode), res) - } - result := new(registrytypes.SearchResults) - return result, errors.Wrap(json.NewDecoder(res.Body).Decode(result), "error decoding registry search results") -} - -func isTimeout(err error) bool { - type timeout interface { - Timeout() bool - } - e := err - switch urlErr := err.(type) { - case *url.Error: - e = urlErr.Err - } - t, ok := e.(timeout) - return ok && t.Timeout() -} - -func newJSONError(msg string, res *http.Response) error { - return &jsonmessage.JSONError{ - Message: msg, - Code: res.StatusCode, - } -} 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 28ed2bfa5..000000000 --- a/vendor/github.com/docker/docker/registry/types.go +++ /dev/null @@ -1,70 +0,0 @@ -package registry // import "github.com/docker/docker/registry" - -import ( - "github.com/docker/distribution/reference" - registrytypes "github.com/docker/docker/api/types/registry" -) - -// RepositoryData tracks the image list, list of endpoints for a repository -type RepositoryData struct { - // ImgList is a list of images in the repository - ImgList map[string]*ImgData - // Endpoints is a list of endpoints returned in X-Docker-Endpoints - Endpoints []string -} - -// ImgData is used to transfer image checksums to and from the registry -type ImgData struct { - // ID is an opaque string that identifies the image - ID string `json:"id"` - Checksum string `json:"checksum,omitempty"` - ChecksumPayload string `json:"-"` - Tag string `json:",omitempty"` -} - -// PingResult 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 PingResult 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"` -} - -// 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 ( - _ = iota - APIVersion1 APIVersion = iota - APIVersion2 -) - -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 *registrytypes.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 4d5f5ae63..000000000 --- a/vendor/github.com/docker/go-connections/nat/nat.go +++ /dev/null @@ -1,242 +0,0 @@ -// Package nat is a convenience package for manipulation of strings describing network ports. -package nat - -import ( - "fmt" - "net" - "strconv" - "strings" -) - -const ( - // portSpecTemplate is the expected format for port specifications - portSpecTemplate = "ip:hostPort:containerPort" -) - -// 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"} { - 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 - rawIP, hostPort, containerPort := splitParts(rawPort) - proto, containerPort = SplitProtoPort(containerPort) - - // Strip [] from IPV6 addresses - ip, _, err := net.SplitHostPort(rawIP + ":") - if err != nil { - return nil, fmt.Errorf("Invalid ip address %v: %s", rawIP, err) - } - 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 892adf8c6..000000000 --- a/vendor/github.com/docker/go-connections/nat/parse.go +++ /dev/null @@ -1,57 +0,0 @@ -package nat - -import ( - "fmt" - "strconv" - "strings" -) - -// PartParser parses and validates the specified string (data) using the specified template -// e.g. ip:public:private -> 192.168.0.1:80:8000 -// DEPRECATED: do not use, this function may be removed in a future version -func PartParser(template, data string) (map[string]string, error) { - // ip:public:private - var ( - templateParts = strings.Split(template, ":") - parts = strings.Split(data, ":") - out = make(map[string]string, len(templateParts)) - ) - if len(parts) != len(templateParts) { - return nil, fmt.Errorf("Invalid format to parse. %s should match template %s", data, template) - } - - for i, t := range templateParts { - value := "" - if len(parts) > i { - value = parts[i] - } - out[t] = value - } - return out, nil -} - -// 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 the 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 ce950171e..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] } - -// sort 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 { - 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/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 98e9a1dc6..000000000 --- a/vendor/github.com/docker/go-connections/sockets/proxy.go +++ /dev/null @@ -1,51 +0,0 @@ -package sockets - -import ( - "net" - "net/url" - "os" - "strings" - - "golang.org/x/net/proxy" -) - -// 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 takes in a "direct" *net.Dialer and returns a -// proxy.Dialer which will route the connections through the proxy using the -// given dialer. -func DialerFromEnvironment(direct *net.Dialer) (proxy.Dialer, error) { - allProxy := GetProxyEnv("all_proxy") - if len(allProxy) == 0 { - return direct, nil - } - - proxyURL, err := url.Parse(allProxy) - if err != nil { - return direct, err - } - - proxyFromURL, err := proxy.FromURL(proxyURL, direct) - if err != nil { - return direct, err - } - - noProxy := GetProxyEnv("no_proxy") - if len(noProxy) == 0 { - return proxyFromURL, nil - } - - perHost := proxy.NewPerHost(proxyFromURL, direct) - perHost.AddFromString(noProxy) - - return perHost, 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 a1d7beb4d..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets.go +++ /dev/null @@ -1,38 +0,0 @@ -// Package sockets provides helper functions to create and configure Unix or TCP sockets. -package sockets - -import ( - "errors" - "net" - "net/http" - "time" -) - -// Why 32? See https://github.com/docker/docker/pull/8035. -const defaultTimeout = 32 * 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 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. -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 - dialer, err := DialerFromEnvironment(&net.Dialer{ - Timeout: defaultTimeout, - }) - if err != nil { - return err - } - tr.Dial = dialer.Dial - } - 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 386cf0dbb..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_unix.go +++ /dev/null @@ -1,35 +0,0 @@ -// +build !windows - -package sockets - -import ( - "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 - tr.Dial = func(_, _ string) (net.Conn, error) { - return net.DialTimeout(proto, addr, defaultTimeout) - } - 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 5c21644e1..000000000 --- a/vendor/github.com/docker/go-connections/sockets/sockets_windows.go +++ /dev/null @@ -1,27 +0,0 @@ -package sockets - -import ( - "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.Dial = func(_, _ string) (net.Conn, error) { - return DialPipe(addr, defaultTimeout) - } - 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 a8b5dbb6f..000000000 --- a/vendor/github.com/docker/go-connections/sockets/unix_socket.go +++ /dev/null @@ -1,32 +0,0 @@ -// +build !windows - -package sockets - -import ( - "net" - "os" - "syscall" -) - -// NewUnixSocket creates a unix socket with the specified path and group. -func NewUnixSocket(path string, gid int) (net.Listener, error) { - if err := syscall.Unlink(path); err != nil && !os.IsNotExist(err) { - return nil, err - } - mask := syscall.Umask(0777) - defer syscall.Umask(mask) - - l, err := net.Listen("unix", path) - if err != nil { - return nil, err - } - if err := os.Chown(path, 0, gid); err != nil { - l.Close() - return nil, err - } - if err := os.Chmod(path, 0660); err != nil { - l.Close() - return nil, err - } - return l, nil -} diff --git a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go deleted file mode 100644 index 1ca0965e0..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_go17.go +++ /dev/null @@ -1,18 +0,0 @@ -// +build go1.7 - -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/certpool_other.go b/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go deleted file mode 100644 index 9ca974539..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/certpool_other.go +++ /dev/null @@ -1,14 +0,0 @@ -// +build !go1.7 - -package tlsconfig - -import ( - "crypto/x509" - -) - -// SystemCertPool returns an new empty cert pool, -// accessing system cert pool is supported in go 1.7 -func SystemCertPool() (*x509.CertPool, error) { - return x509.NewCertPool(), nil -} 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 1b31bbb8b..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config.go +++ /dev/null @@ -1,244 +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" - "fmt" - "io/ioutil" - "os" - - "github.com/pkg/errors" -) - -// 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 - 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, - tls.TLS_RSA_WITH_AES_256_CBC_SHA, - tls.TLS_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...) - -// 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.VersionSSL30: {}, - tls.VersionTLS10: {}, - tls.VersionTLS11: {}, - tls.VersionTLS12: {}, -} - -// ServerDefault returns a secure-enough TLS configuration for the server TLS configuration. -func ServerDefault() *tls.Config { - return &tls.Config{ - // Avoid fallback to SSL protocols < TLS1.0 - MinVersion: tls.VersionTLS10, - PreferServerCipherSuites: true, - CipherSuites: DefaultServerAcceptedCiphers, - } -} - -// ClientDefault returns a secure-enough TLS configuration for the client TLS configuration. -func ClientDefault() *tls.Config { - return &tls.Config{ - // Prefer TLS1.2 as the client minimum - MinVersion: tls.VersionTLS12, - CipherSuites: clientCipherSuites, - } -} - -// 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) - } - } - pem, err := ioutil.ReadFile(caFile) - if err != nil { - return nil, fmt.Errorf("could not read CA certificate %q: %v", caFile, err) - } - if !certPool.AppendCertsFromPEM(pem) { - return nil, fmt.Errorf("failed to append certificates from PEM file: %q", caFile) - } - return certPool, nil -} - -// 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 tryin to decrypt a TLS private key -func IsErrEncryptedKey(err error) bool { - return errors.Cause(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) { - keyBytes, err = x509.DecryptPEMBlock(pemBlock, []byte(passphrase)) - if err != nil { - return nil, errors.Wrap(err, "private key is encrypted, but could not decrypt it") - } - 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 - } - - errMessage := "Could not load X509 key pair" - - cert, err := ioutil.ReadFile(options.CertFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err := ioutil.ReadFile(options.KeyFile) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - prKeyBytes, err = getPrivateKey(prKeyBytes, options.Passphrase) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - tlsCert, err := tls.X509KeyPair(cert, prKeyBytes) - if err != nil { - return nil, errors.Wrap(err, errMessage) - } - - 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, 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 (cert: %q, key: %q): %v. Make sure the key is not encrypted.", 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 6b4c6a7c0..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_client_ciphers.go +++ /dev/null @@ -1,17 +0,0 @@ -// +build go1.5 - -// 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-connections/tlsconfig/config_legacy_client_ciphers.go b/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go deleted file mode 100644 index ee22df47c..000000000 --- a/vendor/github.com/docker/go-connections/tlsconfig/config_legacy_client_ciphers.go +++ /dev/null @@ -1,15 +0,0 @@ -// +build !go1.5 - -// 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_128_GCM_SHA256, - tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, -} 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/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/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/duration.go b/vendor/github.com/docker/go-units/duration.go deleted file mode 100644 index ba02af26d..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 < 46 { - 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 44616c271..000000000 --- a/vendor/github.com/docker/go-units/size.go +++ /dev/null @@ -1,108 +0,0 @@ -package units - -import ( - "fmt" - "regexp" - "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[string]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} - sizeRegex = regexp.MustCompile(`^(\d+(\.\d+)*) ?([kKmMgGtTpP])?[bB]?$`) -) - -var decimapAbbrs = []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"} -var 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) { - matches := sizeRegex.FindStringSubmatch(sizeStr) - if len(matches) != 4 { - return -1, fmt.Errorf("invalid size: '%s'", sizeStr) - } - - size, err := strconv.ParseFloat(matches[1], 64) - if err != nil { - return -1, err - } - - unitPrefix := strings.ToLower(matches[3]) - if mul, ok := uMap[unitPrefix]; ok { - size *= float64(mul) - } - - return int64(size), nil -} 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 5ac7fd825..000000000 --- a/vendor/github.com/docker/go-units/ulimit.go +++ /dev/null @@ -1,118 +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 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/libcompose/LICENSE b/vendor/github.com/docker/libcompose/LICENSE deleted file mode 100644 index 9023c749e..000000000 --- a/vendor/github.com/docker/libcompose/LICENSE +++ /dev/null @@ -1,191 +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 - - 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 - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/libcompose/config/convert.go b/vendor/github.com/docker/libcompose/config/convert.go deleted file mode 100644 index dacee03b5..000000000 --- a/vendor/github.com/docker/libcompose/config/convert.go +++ /dev/null @@ -1,44 +0,0 @@ -package config - -import ( - "github.com/docker/libcompose/utils" - "github.com/docker/libcompose/yaml" -) - -// ConvertServices converts a set of v1 service configs to v2 service configs -func ConvertServices(v1Services map[string]*ServiceConfigV1) (map[string]*ServiceConfig, error) { - v2Services := make(map[string]*ServiceConfig) - replacementFields := make(map[string]*ServiceConfig) - - for name, service := range v1Services { - replacementFields[name] = &ServiceConfig{ - Build: yaml.Build{ - Context: service.Build, - Dockerfile: service.Dockerfile, - }, - Logging: Log{ - Driver: service.LogDriver, - Options: service.LogOpt, - }, - NetworkMode: service.Net, - } - - v1Services[name].Build = "" - v1Services[name].Dockerfile = "" - v1Services[name].LogDriver = "" - v1Services[name].LogOpt = nil - v1Services[name].Net = "" - } - - if err := utils.Convert(v1Services, &v2Services); err != nil { - return nil, err - } - - for name := range v2Services { - v2Services[name].Build = replacementFields[name].Build - v2Services[name].Logging = replacementFields[name].Logging - v2Services[name].NetworkMode = replacementFields[name].NetworkMode - } - - return v2Services, nil -} diff --git a/vendor/github.com/docker/libcompose/config/hash.go b/vendor/github.com/docker/libcompose/config/hash.go deleted file mode 100644 index c3c16d8b1..000000000 --- a/vendor/github.com/docker/libcompose/config/hash.go +++ /dev/null @@ -1,99 +0,0 @@ -package config - -import ( - "crypto/sha1" - "encoding/hex" - "fmt" - "io" - "reflect" - "sort" - - "github.com/docker/libcompose/yaml" -) - -// GetServiceHash computes and returns a hash that will identify a service. -// This hash will be then used to detect if the service definition/configuration -// have changed and needs to be recreated. -func GetServiceHash(name string, config *ServiceConfig) string { - hash := sha1.New() - - io.WriteString(hash, name) - - //Get values of Service through reflection - val := reflect.ValueOf(config).Elem() - - //Create slice to sort the keys in Service Config, which allow constant hash ordering - serviceKeys := []string{} - - //Create a data structure of map of values keyed by a string - unsortedKeyValue := make(map[string]interface{}) - - //Get all keys and values in Service Configuration - for i := 0; i < val.NumField(); i++ { - valueField := val.Field(i) - keyField := val.Type().Field(i) - - serviceKeys = append(serviceKeys, keyField.Name) - unsortedKeyValue[keyField.Name] = valueField.Interface() - } - - //Sort serviceKeys alphabetically - sort.Strings(serviceKeys) - - //Go through keys and write hash - for _, serviceKey := range serviceKeys { - serviceValue := unsortedKeyValue[serviceKey] - - io.WriteString(hash, fmt.Sprintf("\n %v: ", serviceKey)) - - switch s := serviceValue.(type) { - case yaml.SliceorMap: - sliceKeys := []string{} - for lkey := range s { - sliceKeys = append(sliceKeys, lkey) - } - sort.Strings(sliceKeys) - - for _, sliceKey := range sliceKeys { - io.WriteString(hash, fmt.Sprintf("%s=%v, ", sliceKey, s[sliceKey])) - } - case yaml.MaporEqualSlice: - for _, sliceKey := range s { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case yaml.MaporColonSlice: - for _, sliceKey := range s { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case yaml.MaporSpaceSlice: - for _, sliceKey := range s { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case yaml.Command: - for _, sliceKey := range s { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case yaml.Stringorslice: - sort.Strings(s) - - for _, sliceKey := range s { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case []string: - sliceKeys := s - sort.Strings(sliceKeys) - - for _, sliceKey := range sliceKeys { - io.WriteString(hash, fmt.Sprintf("%s, ", sliceKey)) - } - case *yaml.Networks: - io.WriteString(hash, fmt.Sprintf("%s, ", s.HashString())) - case *yaml.Volumes: - io.WriteString(hash, fmt.Sprintf("%s, ", s.HashString())) - default: - io.WriteString(hash, fmt.Sprintf("%v, ", serviceValue)) - } - } - - return hex.EncodeToString(hash.Sum(nil)) -} diff --git a/vendor/github.com/docker/libcompose/config/interpolation.go b/vendor/github.com/docker/libcompose/config/interpolation.go deleted file mode 100644 index 1d7406ed4..000000000 --- a/vendor/github.com/docker/libcompose/config/interpolation.go +++ /dev/null @@ -1,199 +0,0 @@ -package config - -import ( - "bytes" - "fmt" - "strings" - - "github.com/sirupsen/logrus" -) - -var defaultValues = make(map[string]string) - -func isNum(c uint8) bool { - return c >= '0' && c <= '9' -} - -func validVariableDefault(c uint8, line string, pos int) bool { - return (c == ':' && line[pos+1] == '-') || (c == '-') -} - -func validVariableNameChar(c uint8) bool { - return c == '_' || - c >= 'A' && c <= 'Z' || - c >= 'a' && c <= 'z' || - isNum(c) -} - -func parseVariable(line string, pos int, mapping func(string) string) (string, int, bool) { - var buffer bytes.Buffer - - for ; pos < len(line); pos++ { - c := line[pos] - - switch { - case validVariableNameChar(c): - buffer.WriteByte(c) - default: - return mapping(buffer.String()), pos - 1, true - } - } - - return mapping(buffer.String()), pos, true -} - -func parseDefaultValue(line string, pos int) (string, int, bool) { - var buffer bytes.Buffer - - // only skip :, :- and - at the beginning - for ; pos < len(line); pos++ { - c := line[pos] - if c == ':' || c == '-' { - continue - } - break - } - for ; pos < len(line); pos++ { - c := line[pos] - if c == '}' { - return buffer.String(), pos - 1, true - } - err := buffer.WriteByte(c) - if err != nil { - return "", pos, false - } - } - return "", 0, false -} - -func parseVariableWithBraces(line string, pos int, mapping func(string) string) (string, int, bool) { - var buffer bytes.Buffer - - for ; pos < len(line); pos++ { - c := line[pos] - - switch { - case c == '}': - bufferString := buffer.String() - - if bufferString == "" { - return "", 0, false - } - return mapping(buffer.String()), pos, true - case validVariableNameChar(c): - buffer.WriteByte(c) - case validVariableDefault(c, line, pos): - defaultValue := "" - defaultValue, pos, _ = parseDefaultValue(line, pos) - defaultValues[buffer.String()] = defaultValue - default: - return "", 0, false - } - } - - return "", 0, false -} - -func parseInterpolationExpression(line string, pos int, mapping func(string) string) (string, int, bool) { - c := line[pos] - - switch { - case c == '$': - return "$", pos, true - case c == '{': - return parseVariableWithBraces(line, pos+1, mapping) - case !isNum(c) && validVariableNameChar(c): - // Variables can't start with a number - return parseVariable(line, pos, mapping) - default: - return "", 0, false - } -} - -func parseLine(line string, mapping func(string) string) (string, bool) { - var buffer bytes.Buffer - - for pos := 0; pos < len(line); pos++ { - c := line[pos] - switch { - case c == '$': - var replaced string - var success bool - - replaced, pos, success = parseInterpolationExpression(line, pos+1, mapping) - - if !success { - return "", false - } - - buffer.WriteString(replaced) - default: - buffer.WriteByte(c) - } - } - - return buffer.String(), true -} - -func parseConfig(key string, data *interface{}, mapping func(string) string) error { - switch typedData := (*data).(type) { - case string: - var success bool - - *data, success = parseLine(typedData, mapping) - - if !success { - return fmt.Errorf("Invalid interpolation format for key \"%s\": \"%s\"", key, typedData) - } - case []interface{}: - for k, v := range typedData { - err := parseConfig(key, &v, mapping) - - if err != nil { - return err - } - - typedData[k] = v - } - case map[interface{}]interface{}: - for k, v := range typedData { - err := parseConfig(key, &v, mapping) - - if err != nil { - return err - } - - typedData[k] = v - } - } - - return nil -} - -// Interpolate replaces variables in a map entry -func Interpolate(key string, data *interface{}, environmentLookup EnvironmentLookup) error { - return parseConfig(key, data, func(s string) string { - values := environmentLookup.Lookup(s, nil) - - if len(values) == 0 { - if val, ok := defaultValues[s]; ok { - return val - } - logrus.Warnf("The %s variable is not set. Substituting a blank string.", s) - return "" - } - - if strings.SplitN(values[0], "=", 2)[1] == "" { - if val, ok := defaultValues[s]; ok { - return val - } - } - - // Use first result if many are given - value := values[0] - - // Environment variables come in key=value format - // Return everything past first '=' - return strings.SplitN(value, "=", 2)[1] - }) -} diff --git a/vendor/github.com/docker/libcompose/config/merge.go b/vendor/github.com/docker/libcompose/config/merge.go deleted file mode 100644 index 504914090..000000000 --- a/vendor/github.com/docker/libcompose/config/merge.go +++ /dev/null @@ -1,285 +0,0 @@ -package config - -import ( - "bufio" - "bytes" - "fmt" - "strconv" - "strings" - - "reflect" - - "github.com/docker/docker/pkg/urlutil" - "github.com/docker/libcompose/utils" - composeYaml "github.com/docker/libcompose/yaml" - "github.com/sirupsen/logrus" - "gopkg.in/yaml.v2" -) - -var ( - noMerge = []string{ - "links", - "volumes_from", - } - defaultParseOptions = ParseOptions{ - Interpolate: true, - Validate: true, - } -) - -func getComposeMajorVersion(version string) (int, error) { - if version == "" { - return 1, nil - } - parts := strings.Split(version, ".") - if len(parts) == 1 { - return strconv.Atoi(version) - } else if len(parts) == 2 { - return strconv.Atoi(parts[0]) - } else { - return -1, fmt.Errorf("Invalid version string, expected single integer or dot delimited int.int. Got: %s", version) - } -} - -// CreateConfig unmarshals bytes of a YAML manifest file and returns a new -// Config. Initialize any defaults that can't be parsed (but are optional) -// across various file formats. Most of these can remain unused. -// -// This function only handles parsing YAML in the general case. Any other file -// format validation should be handled by the caller. -func CreateConfig(bytes []byte) (*Config, error) { - var config Config - if err := yaml.Unmarshal(bytes, &config); err != nil { - return nil, err - } - - major, err := getComposeMajorVersion(config.Version) - if err != nil { - return nil, err - } - if major < 2 { - var baseRawServices RawServiceMap - if err := yaml.Unmarshal(bytes, &baseRawServices); err != nil { - return nil, err - } - config.Services = baseRawServices - } - - if config.Volumes == nil { - config.Volumes = make(map[string]interface{}) - } - if config.Networks == nil { - config.Networks = make(map[string]interface{}) - } - - return &config, nil -} - -// Merge merges a compose file into an existing set of service configs -func Merge(existingServices *ServiceConfigs, environmentLookup EnvironmentLookup, resourceLookup ResourceLookup, file string, bytes []byte, options *ParseOptions) (string, map[string]*ServiceConfig, map[string]*VolumeConfig, map[string]*NetworkConfig, error) { - if options == nil { - options = &defaultParseOptions - } - - config, err := CreateConfig(bytes) - if err != nil { - return "", nil, nil, nil, err - } - baseRawServices := config.Services - - for service, data := range baseRawServices { - for key, value := range data { - //check for "extends" key and check whether it is string or not - if key == "extends" && reflect.TypeOf(value).Kind() == reflect.String { - //converting string to map - extendMap := make(map[interface{}]interface{}) - extendMap["service"] = value - baseRawServices[service][key] = extendMap - } - } - } - - if options.Interpolate { - if err := InterpolateRawServiceMap(&baseRawServices, environmentLookup); err != nil { - return "", nil, nil, nil, err - } - - for k, v := range config.Volumes { - if err := Interpolate(k, &v, environmentLookup); err != nil { - return "", nil, nil, nil, err - } - config.Volumes[k] = v - } - - for k, v := range config.Networks { - if err := Interpolate(k, &v, environmentLookup); err != nil { - return "", nil, nil, nil, err - } - config.Networks[k] = v - } - } - - if options.Preprocess != nil { - var err error - baseRawServices, err = options.Preprocess(baseRawServices) - if err != nil { - return "", nil, nil, nil, err - } - } - - major, err := getComposeMajorVersion(config.Version) - if err != nil { - return "", nil, nil, nil, err - } - - var serviceConfigs map[string]*ServiceConfig - switch major { - case 3: - logrus.Fatal("Note: Compose file version 3 is not yet implemented") - case 2: - var err error - serviceConfigs, err = MergeServicesV2(existingServices, environmentLookup, resourceLookup, file, baseRawServices, options) - if err != nil { - return "", nil, nil, nil, err - } - default: - serviceConfigsV1, err := MergeServicesV1(existingServices, environmentLookup, resourceLookup, file, baseRawServices, options) - if err != nil { - return "", nil, nil, nil, err - } - serviceConfigs, err = ConvertServices(serviceConfigsV1) - if err != nil { - return "", nil, nil, nil, err - } - } - - adjustValues(serviceConfigs) - - if options.Postprocess != nil { - var err error - serviceConfigs, err = options.Postprocess(serviceConfigs) - if err != nil { - return "", nil, nil, nil, err - } - } - - var volumes map[string]*VolumeConfig - var networks map[string]*NetworkConfig - if err := utils.Convert(config.Volumes, &volumes); err != nil { - return "", nil, nil, nil, err - } - if err := utils.Convert(config.Networks, &networks); err != nil { - return "", nil, nil, nil, err - } - - return config.Version, serviceConfigs, volumes, networks, nil -} - -// InterpolateRawServiceMap replaces varialbse in raw service map struct based on environment lookup -func InterpolateRawServiceMap(baseRawServices *RawServiceMap, environmentLookup EnvironmentLookup) error { - for k, v := range *baseRawServices { - for k2, v2 := range v { - if err := Interpolate(k2, &v2, environmentLookup); err != nil { - return err - } - (*baseRawServices)[k][k2] = v2 - } - } - return nil -} - -func adjustValues(configs map[string]*ServiceConfig) { - // yaml parser turns "no" into "false" but that is not valid for a restart policy - for _, v := range configs { - if v.Restart == "false" { - v.Restart = "no" - } - } -} - -func readEnvFile(resourceLookup ResourceLookup, inFile string, serviceData RawService) (RawService, error) { - if _, ok := serviceData["env_file"]; !ok { - return serviceData, nil - } - - var envFiles composeYaml.Stringorslice - - if err := utils.Convert(serviceData["env_file"], &envFiles); err != nil { - return nil, err - } - - if len(envFiles) == 0 { - return serviceData, nil - } - - if resourceLookup == nil { - return nil, fmt.Errorf("Can not use env_file in file %s no mechanism provided to load files", inFile) - } - - var vars composeYaml.MaporEqualSlice - - if _, ok := serviceData["environment"]; ok { - if err := utils.Convert(serviceData["environment"], &vars); err != nil { - return nil, err - } - } - - for i := len(envFiles) - 1; i >= 0; i-- { - envFile := envFiles[i] - content, _, err := resourceLookup.Lookup(envFile, inFile) - if err != nil { - return nil, err - } - - if err != nil { - return nil, err - } - - scanner := bufio.NewScanner(bytes.NewBuffer(content)) - for scanner.Scan() { - line := strings.TrimSpace(scanner.Text()) - - if len(line) > 0 && !strings.HasPrefix(line, "#") { - key := strings.SplitAfter(line, "=")[0] - - found := false - for _, v := range vars { - if strings.HasPrefix(v, key) { - found = true - break - } - } - - if !found { - vars = append(vars, line) - } - } - } - - if scanner.Err() != nil { - return nil, scanner.Err() - } - } - - serviceData["environment"] = vars - - return serviceData, nil -} - -func mergeConfig(baseService, serviceData RawService) RawService { - for k, v := range serviceData { - existing, ok := baseService[k] - if ok { - baseService[k] = merge(existing, v) - } else { - baseService[k] = v - } - } - - return baseService -} - -// IsValidRemote checks if the specified string is a valid remote (for builds) -func IsValidRemote(remote string) bool { - return urlutil.IsGitURL(remote) || urlutil.IsURL(remote) -} diff --git a/vendor/github.com/docker/libcompose/config/merge_v1.go b/vendor/github.com/docker/libcompose/config/merge_v1.go deleted file mode 100644 index 78c1249e5..000000000 --- a/vendor/github.com/docker/libcompose/config/merge_v1.go +++ /dev/null @@ -1,198 +0,0 @@ -package config - -import ( - "fmt" - "path" - - "github.com/docker/libcompose/utils" - "github.com/sirupsen/logrus" -) - -// MergeServicesV1 merges a v1 compose file into an existing set of service configs -func MergeServicesV1(existingServices *ServiceConfigs, environmentLookup EnvironmentLookup, resourceLookup ResourceLookup, file string, datas RawServiceMap, options *ParseOptions) (map[string]*ServiceConfigV1, error) { - if options.Validate { - if err := validate(datas); err != nil { - return nil, err - } - } - - for name, data := range datas { - data, err := parseV1(resourceLookup, environmentLookup, file, data, datas, options) - if err != nil { - logrus.Errorf("Failed to parse service %s: %v", name, err) - return nil, err - } - - if serviceConfig, ok := existingServices.Get(name); ok { - var rawExistingService RawService - if err := utils.Convert(serviceConfig, &rawExistingService); err != nil { - return nil, err - } - - data = mergeConfigV1(rawExistingService, data) - } - - datas[name] = data - } - - if options.Validate { - for name, data := range datas { - err := validateServiceConstraints(data, name) - if err != nil { - return nil, err - } - } - } - - serviceConfigs := make(map[string]*ServiceConfigV1) - if err := utils.Convert(datas, &serviceConfigs); err != nil { - return nil, err - } - - return serviceConfigs, nil -} - -func parseV1(resourceLookup ResourceLookup, environmentLookup EnvironmentLookup, inFile string, serviceData RawService, datas RawServiceMap, options *ParseOptions) (RawService, error) { - serviceData, err := readEnvFile(resourceLookup, inFile, serviceData) - if err != nil { - return nil, err - } - - serviceData = resolveContextV1(inFile, serviceData) - - value, ok := serviceData["extends"] - if !ok { - return serviceData, nil - } - - mapValue, ok := value.(map[interface{}]interface{}) - if !ok { - return serviceData, nil - } - - if resourceLookup == nil { - return nil, fmt.Errorf("Can not use extends in file %s no mechanism provided to files", inFile) - } - - file := asString(mapValue["file"]) - service := asString(mapValue["service"]) - - if service == "" { - return serviceData, nil - } - - var baseService RawService - - if file == "" { - if serviceData, ok := datas[service]; ok { - baseService, err = parseV1(resourceLookup, environmentLookup, inFile, serviceData, datas, options) - } else { - return nil, fmt.Errorf("Failed to find service %s to extend", service) - } - } else { - bytes, resolved, err := resourceLookup.Lookup(file, inFile) - if err != nil { - logrus.Errorf("Failed to lookup file %s: %v", file, err) - return nil, err - } - - config, err := CreateConfig(bytes) - if err != nil { - return nil, err - } - baseRawServices := config.Services - - if options.Interpolate { - if err = InterpolateRawServiceMap(&baseRawServices, environmentLookup); err != nil { - return nil, err - } - } - - if options.Preprocess != nil { - var err error - baseRawServices, err = options.Preprocess(baseRawServices) - if err != nil { - return nil, err - } - } - - if options.Validate { - if err := validate(baseRawServices); err != nil { - return nil, err - } - } - - baseService, ok = baseRawServices[service] - if !ok { - return nil, fmt.Errorf("Failed to find service %s in file %s", service, file) - } - - baseService, err = parseV1(resourceLookup, environmentLookup, resolved, baseService, baseRawServices, options) - } - - if err != nil { - return nil, err - } - - baseService = clone(baseService) - - logrus.Debugf("Merging %#v, %#v", baseService, serviceData) - - for _, k := range noMerge { - if _, ok := baseService[k]; ok { - source := file - if source == "" { - source = inFile - } - return nil, fmt.Errorf("Cannot extend service '%s' in %s: services with '%s' cannot be extended", service, source, k) - } - } - - baseService = mergeConfigV1(baseService, serviceData) - - logrus.Debugf("Merged result %#v", baseService) - - return baseService, nil -} - -func resolveContextV1(inFile string, serviceData RawService) RawService { - context := asString(serviceData["build"]) - if context == "" { - return serviceData - } - - if IsValidRemote(context) { - return serviceData - } - - current := path.Dir(inFile) - - if context == "." { - context = current - } else { - current = path.Join(current, context) - } - - serviceData["build"] = current - - return serviceData -} - -func mergeConfigV1(baseService, serviceData RawService) RawService { - for k, v := range serviceData { - // Image and build are mutually exclusive in merge - if k == "image" { - delete(baseService, "build") - } else if k == "build" { - delete(baseService, "image") - } - existing, ok := baseService[k] - if ok { - baseService[k] = merge(existing, v) - } else { - baseService[k] = v - } - } - - return baseService -} diff --git a/vendor/github.com/docker/libcompose/config/merge_v2.go b/vendor/github.com/docker/libcompose/config/merge_v2.go deleted file mode 100644 index de653696c..000000000 --- a/vendor/github.com/docker/libcompose/config/merge_v2.go +++ /dev/null @@ -1,192 +0,0 @@ -package config - -import ( - "fmt" - "path" - "strings" - - "github.com/docker/libcompose/utils" - "github.com/sirupsen/logrus" -) - -// MergeServicesV2 merges a v2 compose file into an existing set of service configs -func MergeServicesV2(existingServices *ServiceConfigs, environmentLookup EnvironmentLookup, resourceLookup ResourceLookup, file string, datas RawServiceMap, options *ParseOptions) (map[string]*ServiceConfig, error) { - if options.Validate { - if err := validateV2(datas); err != nil { - return nil, err - } - } - - for name, data := range datas { - data, err := parseV2(resourceLookup, environmentLookup, file, data, datas, options) - if err != nil { - logrus.Errorf("Failed to parse service %s: %v", name, err) - return nil, err - } - - if serviceConfig, ok := existingServices.Get(name); ok { - var rawExistingService RawService - if err := utils.Convert(serviceConfig, &rawExistingService); err != nil { - return nil, err - } - - data = mergeConfig(rawExistingService, data) - } - - datas[name] = data - } - - if options.Validate { - var errs []string - for name, data := range datas { - err := validateServiceConstraintsv2(data, name) - if err != nil { - errs = append(errs, err.Error()) - } - } - if len(errs) != 0 { - return nil, fmt.Errorf(strings.Join(errs, "\n")) - } - } - - serviceConfigs := make(map[string]*ServiceConfig) - if err := utils.Convert(datas, &serviceConfigs); err != nil { - return nil, err - } - - return serviceConfigs, nil -} - -func parseV2(resourceLookup ResourceLookup, environmentLookup EnvironmentLookup, inFile string, serviceData RawService, datas RawServiceMap, options *ParseOptions) (RawService, error) { - serviceData, err := readEnvFile(resourceLookup, inFile, serviceData) - if err != nil { - return nil, err - } - - serviceData = resolveContextV2(inFile, serviceData) - - value, ok := serviceData["extends"] - if !ok { - return serviceData, nil - } - - mapValue, ok := value.(map[interface{}]interface{}) - if !ok { - return serviceData, nil - } - - if resourceLookup == nil { - return nil, fmt.Errorf("Can not use extends in file %s no mechanism provided to files", inFile) - } - - file := asString(mapValue["file"]) - service := asString(mapValue["service"]) - - if service == "" { - return serviceData, nil - } - - var baseService RawService - - if file == "" { - if serviceData, ok := datas[service]; ok { - baseService, err = parseV2(resourceLookup, environmentLookup, inFile, serviceData, datas, options) - } else { - return nil, fmt.Errorf("Failed to find service %s to extend", service) - } - } else { - bytes, resolved, err := resourceLookup.Lookup(file, inFile) - if err != nil { - logrus.Errorf("Failed to lookup file %s: %v", file, err) - return nil, err - } - - config, err := CreateConfig(bytes) - if err != nil { - return nil, err - } - baseRawServices := config.Services - - if options.Interpolate { - if err = InterpolateRawServiceMap(&baseRawServices, environmentLookup); err != nil { - return nil, err - } - } - - if options.Validate { - if err := validateV2(baseRawServices); err != nil { - return nil, err - } - } - - baseService, ok = baseRawServices[service] - if !ok { - return nil, fmt.Errorf("Failed to find service %s in file %s", service, file) - } - - baseService, err = parseV2(resourceLookup, environmentLookup, resolved, baseService, baseRawServices, options) - } - - if err != nil { - return nil, err - } - - baseService = clone(baseService) - - logrus.Debugf("Merging %#v, %#v", baseService, serviceData) - - for _, k := range noMerge { - if _, ok := baseService[k]; ok { - source := file - if source == "" { - source = inFile - } - return nil, fmt.Errorf("Cannot extend service '%s' in %s: services with '%s' cannot be extended", service, source, k) - } - } - - baseService = mergeConfig(baseService, serviceData) - - logrus.Debugf("Merged result %#v", baseService) - - return baseService, nil -} - -func resolveContextV2(inFile string, serviceData RawService) RawService { - if _, ok := serviceData["build"]; !ok { - return serviceData - } - var build map[interface{}]interface{} - if buildAsString, ok := serviceData["build"].(string); ok { - build = map[interface{}]interface{}{ - "context": buildAsString, - } - } else { - build = serviceData["build"].(map[interface{}]interface{}) - } - context := asString(build["context"]) - if context == "" { - return serviceData - } - - if IsValidRemote(context) { - return serviceData - } - - current := path.Dir(inFile) - - if context == "." { - context = current - } else { - current = path.Join(current, context) - } - if _, ok := serviceData["build"].(string); ok { - //build is specified as a string containing a path to the build context - serviceData["build"] = current - } else { - //build is specified as an object with the path specified under context - build["context"] = current - } - - return serviceData -} diff --git a/vendor/github.com/docker/libcompose/config/schema.go b/vendor/github.com/docker/libcompose/config/schema.go deleted file mode 100644 index 3f42404ca..000000000 --- a/vendor/github.com/docker/libcompose/config/schema.go +++ /dev/null @@ -1,489 +0,0 @@ -package config - -var schemaDataV1 = `{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v1.json", - - "type": "object", - - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - - "additionalProperties": false, - - "definitions": { - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "build": {"type": "string"}, - "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"}, - "cpu_shares": {"type": ["number", "string"]}, - "cpu_quota": {"type": ["number", "string"]}, - "cpuset": {"type": "string"}, - "devices": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "dns": {"$ref": "#/definitions/string_or_list"}, - "dns_search": {"$ref": "#/definitions/string_or_list"}, - "dockerfile": {"type": "string"}, - "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 - }, - - "extends": { - "oneOf": [ - { - "type": "string" - }, - { - "type": "object", - - "properties": { - "service": {"type": "string"}, - "file": {"type": "string"} - }, - "required": ["service"], - "additionalProperties": false - } - ] - }, - - "extra_hosts": {"$ref": "#/definitions/list_or_dict"}, - "external_links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "hostname": {"type": "string"}, - "image": {"type": "string"}, - "ipc": {"type": "string"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "links": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "log_driver": {"type": "string"}, - "log_opt": {"type": "object"}, - "mac_address": {"type": "string"}, - "mem_limit": {"type": ["number", "string"]}, - "mem_reservation": {"type": ["number", "string"]}, - "memswap_limit": {"type": ["number", "string"]}, - "mem_swappiness": {"type": "integer"}, - "net": {"type": "string"}, - "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"]}, - "stdin_open": {"type": "boolean"}, - "stop_signal": {"type": "string"}, - "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"}, - "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "volume_driver": {"type": "string"}, - "volumes_from": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "working_dir": {"type": "string"} - }, - - "dependencies": { - "memswap_limit": ["mem_limit"] - }, - "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"], - "not": {"required": ["image"]} - }, - { - "required": ["image"], - "not": {"anyOf": [ - {"required": ["build"]}, - {"required": ["dockerfile"]} - ]} - } - ] - } - } - } -} -` - -var servicesSchemaDataV2 = `{ - "$schema": "http://json-schema.org/draft-04/schema#", - "id": "config_schema_v2.0.json", - "type": "object", - - "patternProperties": { - "^[a-zA-Z0-9._-]+$": { - "$ref": "#/definitions/service" - } - }, - - "additionalProperties": false, - - "definitions": { - - "service": { - "id": "#/definitions/service", - "type": "object", - - "properties": { - "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"}, - "labels": {"$ref": "#/definitions/list_or_dict"}, - "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"}} - ] - }, - "container_name": {"type": "string"}, - "cpu_shares": {"type": ["number", "string"]}, - "cpu_quota": {"type": ["number", "string"]}, - "cpuset": {"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 - }, - - "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"}, "uniqueItems": true}, - "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"} - }, - "additionalProperties": false - }, - - "mac_address": {"type": "string"}, - "mem_limit": {"type": ["number", "string"]}, - "mem_reservation": {"type": ["number", "string"]}, - "memswap_limit": {"type": ["number", "string"]}, - "mem_swappiness": {"type": "integer"}, - "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 - } - ] - }, - "oom_score_adj": {"type": "integer", "minimum": -1000, "maximum": 1000}, - "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"]}, - "stdin_open": {"type": "boolean"}, - "stop_grace_period": {"type": "string"}, - "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"}, - "volumes": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "volume_driver": {"type": "string"}, - "volumes_from": {"type": "array", "items": {"type": "string"}, "uniqueItems": true}, - "working_dir": {"type": "string"} - }, - - "dependencies": { - "memswap_limit": ["mem_limit"] - }, - "additionalProperties": false - }, - - "network": { - "id": "#/definitions/network", - "type": "object", - "properties": { - "driver": {"type": "string"}, - "driver_opts": { - "type": "object", - "patternProperties": { - "^.+$": {"type": ["string", "number"]} - } - }, - "ipam": { - "type": "object", - "properties": { - "driver": {"type": "string"}, - "config": { - "type": "array" - } - }, - "additionalProperties": false - }, - "external": { - "type": ["boolean", "object"], - "properties": { - "name": {"type": "string"} - }, - "additionalProperties": false - }, - "internal": {"type": "boolean"} - }, - "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 - }, - - "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/libcompose/config/schema_helpers.go b/vendor/github.com/docker/libcompose/config/schema_helpers.go deleted file mode 100644 index 881a96a04..000000000 --- a/vendor/github.com/docker/libcompose/config/schema_helpers.go +++ /dev/null @@ -1,109 +0,0 @@ -package config - -import ( - "encoding/json" - "strings" - - "github.com/docker/go-connections/nat" - "github.com/xeipuuv/gojsonschema" -) - -var ( - schemaLoaderV1 gojsonschema.JSONLoader - constraintSchemaLoaderV1 gojsonschema.JSONLoader - schemaLoaderV2 gojsonschema.JSONLoader - constraintSchemaLoaderV2 gojsonschema.JSONLoader - schemaV1 map[string]interface{} - schemaV2 map[string]interface{} -) - -func init() { - if err := setupSchemaLoaders(schemaDataV1, &schemaV1, &schemaLoaderV1, &constraintSchemaLoaderV1); err != nil { - panic(err) - } - - if err := setupSchemaLoaders(servicesSchemaDataV2, &schemaV2, &schemaLoaderV2, &constraintSchemaLoaderV2); err != nil { - panic(err) - } -} - -type ( - environmentFormatChecker struct{} - portsFormatChecker struct{} -) - -func (checker environmentFormatChecker) IsFormat(input interface{}) bool { - // If the value is a boolean, a warning should be given - // However, we can't determine type since gojsonschema converts the value to a string - // Adding a function with an interface{} parameter to gojsonschema is probably the best way to handle this - return true -} - -func (checker portsFormatChecker) IsFormat(input interface{}) bool { - in, ok := input.(string) - if !ok { - return true - } - _, _, err := nat.ParsePortSpecs([]string{in}) - return err == nil -} - -func setupSchemaLoaders(schemaData string, schema *map[string]interface{}, schemaLoader, constraintSchemaLoader *gojsonschema.JSONLoader) error { - if *schema != nil { - return nil - } - - var schemaRaw interface{} - err := json.Unmarshal([]byte(schemaData), &schemaRaw) - if err != nil { - return err - } - - *schema = schemaRaw.(map[string]interface{}) - - gojsonschema.FormatCheckers.Add("environment", environmentFormatChecker{}) - gojsonschema.FormatCheckers.Add("ports", portsFormatChecker{}) - gojsonschema.FormatCheckers.Add("expose", portsFormatChecker{}) - *schemaLoader = gojsonschema.NewGoLoader(schemaRaw) - - definitions := (*schema)["definitions"].(map[string]interface{}) - constraints := definitions["constraints"].(map[string]interface{}) - service := constraints["service"].(map[string]interface{}) - *constraintSchemaLoader = gojsonschema.NewGoLoader(service) - - return nil -} - -// gojsonschema doesn't provide a list of valid types for a property -// This parses the schema manually to find all valid types -func parseValidTypesFromSchema(schema map[string]interface{}, context string) []string { - contextSplit := strings.Split(context, ".") - key := contextSplit[len(contextSplit)-1] - - definitions := schema["definitions"].(map[string]interface{}) - service := definitions["service"].(map[string]interface{}) - properties := service["properties"].(map[string]interface{}) - property := properties[key].(map[string]interface{}) - - var validTypes []string - - if val, ok := property["oneOf"]; ok { - validConditions := val.([]interface{}) - - for _, validCondition := range validConditions { - condition := validCondition.(map[string]interface{}) - validTypes = append(validTypes, condition["type"].(string)) - } - } else if val, ok := property["$ref"]; ok { - reference := val.(string) - if reference == "#/definitions/string_or_list" { - return []string{"string", "array"} - } else if reference == "#/definitions/list_of_strings" { - return []string{"array"} - } else if reference == "#/definitions/list_or_dict" { - return []string{"array", "object"} - } - } - - return validTypes -} diff --git a/vendor/github.com/docker/libcompose/config/types.go b/vendor/github.com/docker/libcompose/config/types.go deleted file mode 100644 index 9e4c9dfca..000000000 --- a/vendor/github.com/docker/libcompose/config/types.go +++ /dev/null @@ -1,265 +0,0 @@ -package config - -import ( - "sync" - - "github.com/docker/libcompose/yaml" -) - -// EnvironmentLookup defines methods to provides environment variable loading. -type EnvironmentLookup interface { - Lookup(key string, config *ServiceConfig) []string -} - -// ResourceLookup defines methods to provides file loading. -type ResourceLookup interface { - Lookup(file, relativeTo string) ([]byte, string, error) - ResolvePath(path, inFile string) string -} - -// ServiceConfigV1 holds version 1 of libcompose service configuration -type ServiceConfigV1 struct { - Build string `yaml:"build,omitempty"` - CapAdd []string `yaml:"cap_add,omitempty"` - CapDrop []string `yaml:"cap_drop,omitempty"` - CgroupParent string `yaml:"cgroup_parent,omitempty"` - CPUQuota yaml.StringorInt `yaml:"cpu_quota,omitempty"` - CPUSet string `yaml:"cpuset,omitempty"` - CPUShares yaml.StringorInt `yaml:"cpu_shares,omitempty"` - Command yaml.Command `yaml:"command,flow,omitempty"` - ContainerName string `yaml:"container_name,omitempty"` - Devices []string `yaml:"devices,omitempty"` - DNS yaml.Stringorslice `yaml:"dns,omitempty"` - DNSOpts []string `yaml:"dns_opt,omitempty"` - DNSSearch yaml.Stringorslice `yaml:"dns_search,omitempty"` - Dockerfile string `yaml:"dockerfile,omitempty"` - DomainName string `yaml:"domainname,omitempty"` - Entrypoint yaml.Command `yaml:"entrypoint,flow,omitempty"` - EnvFile yaml.Stringorslice `yaml:"env_file,omitempty"` - Environment yaml.MaporEqualSlice `yaml:"environment,omitempty"` - GroupAdd []string `yaml:"group_add,omitempty"` - Hostname string `yaml:"hostname,omitempty"` - Image string `yaml:"image,omitempty"` - Isolation string `yaml:"isolation,omitempty"` - Labels yaml.SliceorMap `yaml:"labels,omitempty"` - Links yaml.MaporColonSlice `yaml:"links,omitempty"` - LogDriver string `yaml:"log_driver,omitempty"` - MacAddress string `yaml:"mac_address,omitempty"` - MemLimit yaml.MemStringorInt `yaml:"mem_limit,omitempty"` - MemSwapLimit yaml.MemStringorInt `yaml:"memswap_limit,omitempty"` - MemSwappiness yaml.MemStringorInt `yaml:"mem_swappiness,omitempty"` - Name string `yaml:"name,omitempty"` - Net string `yaml:"net,omitempty"` - OomKillDisable bool `yaml:"oom_kill_disable,omitempty"` - OomScoreAdj yaml.StringorInt `yaml:"oom_score_adj,omitempty"` - Pid string `yaml:"pid,omitempty"` - Uts string `yaml:"uts,omitempty"` - Ipc string `yaml:"ipc,omitempty"` - Ports []string `yaml:"ports,omitempty"` - Privileged bool `yaml:"privileged,omitempty"` - Restart string `yaml:"restart,omitempty"` - ReadOnly bool `yaml:"read_only,omitempty"` - ShmSize yaml.MemStringorInt `yaml:"shm_size,omitempty"` - StdinOpen bool `yaml:"stdin_open,omitempty"` - SecurityOpt []string `yaml:"security_opt,omitempty"` - StopSignal string `yaml:"stop_signal,omitempty"` - Tmpfs yaml.Stringorslice `yaml:"tmpfs,omitempty"` - Tty bool `yaml:"tty,omitempty"` - User string `yaml:"user,omitempty"` - VolumeDriver string `yaml:"volume_driver,omitempty"` - Volumes []string `yaml:"volumes,omitempty"` - VolumesFrom []string `yaml:"volumes_from,omitempty"` - WorkingDir string `yaml:"working_dir,omitempty"` - Expose []string `yaml:"expose,omitempty"` - ExternalLinks []string `yaml:"external_links,omitempty"` - LogOpt map[string]string `yaml:"log_opt,omitempty"` - ExtraHosts []string `yaml:"extra_hosts,omitempty"` - Ulimits yaml.Ulimits `yaml:"ulimits,omitempty"` -} - -// Log holds v2 logging information -type Log struct { - Driver string `yaml:"driver,omitempty"` - Options map[string]string `yaml:"options,omitempty"` -} - -// ServiceConfig holds version 2 of libcompose service configuration -type ServiceConfig struct { - Build yaml.Build `yaml:"build,omitempty"` - CapAdd []string `yaml:"cap_add,omitempty"` - CapDrop []string `yaml:"cap_drop,omitempty"` - CPUSet string `yaml:"cpuset,omitempty"` - CPUShares yaml.StringorInt `yaml:"cpu_shares,omitempty"` - CPUQuota yaml.StringorInt `yaml:"cpu_quota,omitempty"` - Command yaml.Command `yaml:"command,flow,omitempty"` - CgroupParent string `yaml:"cgroup_parent,omitempty"` - ContainerName string `yaml:"container_name,omitempty"` - Devices []string `yaml:"devices,omitempty"` - DependsOn []string `yaml:"depends_on,omitempty"` - DNS yaml.Stringorslice `yaml:"dns,omitempty"` - DNSOpts []string `yaml:"dns_opt,omitempty"` - DNSSearch yaml.Stringorslice `yaml:"dns_search,omitempty"` - DomainName string `yaml:"domainname,omitempty"` - Entrypoint yaml.Command `yaml:"entrypoint,flow,omitempty"` - EnvFile yaml.Stringorslice `yaml:"env_file,omitempty"` - Environment yaml.MaporEqualSlice `yaml:"environment,omitempty"` - Expose []string `yaml:"expose,omitempty"` - Extends yaml.MaporEqualSlice `yaml:"extends,omitempty"` - ExternalLinks []string `yaml:"external_links,omitempty"` - ExtraHosts []string `yaml:"extra_hosts,omitempty"` - GroupAdd []string `yaml:"group_add,omitempty"` - Image string `yaml:"image,omitempty"` - Isolation string `yaml:"isolation,omitempty"` - Hostname string `yaml:"hostname,omitempty"` - Ipc string `yaml:"ipc,omitempty"` - Labels yaml.SliceorMap `yaml:"labels,omitempty"` - Links yaml.MaporColonSlice `yaml:"links,omitempty"` - Logging Log `yaml:"logging,omitempty"` - MacAddress string `yaml:"mac_address,omitempty"` - MemLimit yaml.MemStringorInt `yaml:"mem_limit,omitempty"` - MemReservation yaml.MemStringorInt `yaml:"mem_reservation,omitempty"` - MemSwapLimit yaml.MemStringorInt `yaml:"memswap_limit,omitempty"` - MemSwappiness yaml.MemStringorInt `yaml:"mem_swappiness,omitempty"` - NetworkMode string `yaml:"network_mode,omitempty"` - Networks *yaml.Networks `yaml:"networks,omitempty"` - OomKillDisable bool `yaml:"oom_kill_disable,omitempty"` - OomScoreAdj yaml.StringorInt `yaml:"oom_score_adj,omitempty"` - Pid string `yaml:"pid,omitempty"` - Ports []string `yaml:"ports,omitempty"` - Privileged bool `yaml:"privileged,omitempty"` - SecurityOpt []string `yaml:"security_opt,omitempty"` - ShmSize yaml.MemStringorInt `yaml:"shm_size,omitempty"` - StopGracePeriod string `yaml:"stop_grace_period,omitempty"` - StopSignal string `yaml:"stop_signal,omitempty"` - Tmpfs yaml.Stringorslice `yaml:"tmpfs,omitempty"` - VolumeDriver string `yaml:"volume_driver,omitempty"` - Volumes *yaml.Volumes `yaml:"volumes,omitempty"` - VolumesFrom []string `yaml:"volumes_from,omitempty"` - Uts string `yaml:"uts,omitempty"` - Restart string `yaml:"restart,omitempty"` - ReadOnly bool `yaml:"read_only,omitempty"` - StdinOpen bool `yaml:"stdin_open,omitempty"` - Tty bool `yaml:"tty,omitempty"` - User string `yaml:"user,omitempty"` - WorkingDir string `yaml:"working_dir,omitempty"` - Ulimits yaml.Ulimits `yaml:"ulimits,omitempty"` -} - -// VolumeConfig holds v2 volume configuration -type VolumeConfig struct { - Driver string `yaml:"driver,omitempty"` - DriverOpts map[string]string `yaml:"driver_opts,omitempty"` - External yaml.External `yaml:"external,omitempty"` -} - -// Ipam holds v2 network IPAM information -type Ipam struct { - Driver string `yaml:"driver,omitempty"` - Config []IpamConfig `yaml:"config,omitempty"` -} - -// IpamConfig holds v2 network IPAM configuration information -type IpamConfig struct { - Subnet string `yaml:"subnet,omitempty"` - IPRange string `yaml:"ip_range,omitempty"` - Gateway string `yaml:"gateway,omitempty"` - AuxAddress map[string]string `yaml:"aux_addresses,omitempty"` -} - -// NetworkConfig holds v2 network configuration -type NetworkConfig struct { - Driver string `yaml:"driver,omitempty"` - DriverOpts map[string]string `yaml:"driver_opts,omitempty"` - External yaml.External `yaml:"external,omitempty"` - Ipam Ipam `yaml:"ipam,omitempty"` -} - -// Config holds libcompose top level configuration -type Config struct { - Version string `yaml:"version,omitempty"` - Services RawServiceMap `yaml:"services,omitempty"` - Volumes map[string]interface{} `yaml:"volumes,omitempty"` - Networks map[string]interface{} `yaml:"networks,omitempty"` -} - -// NewServiceConfigs initializes a new Configs struct -func NewServiceConfigs() *ServiceConfigs { - return &ServiceConfigs{ - m: make(map[string]*ServiceConfig), - } -} - -// ServiceConfigs holds a concurrent safe map of ServiceConfig -type ServiceConfigs struct { - m map[string]*ServiceConfig - mu sync.RWMutex -} - -// Has checks if the config map has the specified name -func (c *ServiceConfigs) Has(name string) bool { - c.mu.RLock() - defer c.mu.RUnlock() - _, ok := c.m[name] - return ok -} - -// Get returns the config and the presence of the specified name -func (c *ServiceConfigs) Get(name string) (*ServiceConfig, bool) { - c.mu.RLock() - defer c.mu.RUnlock() - service, ok := c.m[name] - return service, ok -} - -// Add add the specifed config with the specified name -func (c *ServiceConfigs) Add(name string, service *ServiceConfig) { - c.mu.Lock() - c.m[name] = service - c.mu.Unlock() -} - -// Remove removes the config with the specified name -func (c *ServiceConfigs) Remove(name string) { - c.mu.Lock() - delete(c.m, name) - c.mu.Unlock() -} - -// Len returns the len of the configs -func (c *ServiceConfigs) Len() int { - c.mu.RLock() - defer c.mu.RUnlock() - return len(c.m) -} - -// Keys returns the names of the config -func (c *ServiceConfigs) Keys() []string { - keys := []string{} - c.mu.RLock() - defer c.mu.RUnlock() - for name := range c.m { - keys = append(keys, name) - } - return keys -} - -// All returns all the config at once -func (c *ServiceConfigs) All() map[string]*ServiceConfig { - c.mu.RLock() - defer c.mu.RUnlock() - return c.m -} - -// RawService is represent a Service in map form unparsed -type RawService map[string]interface{} - -// RawServiceMap is a collection of RawServices -type RawServiceMap map[string]RawService - -// ParseOptions are a set of options to customize the parsing process -type ParseOptions struct { - Interpolate bool - Validate bool - Preprocess func(RawServiceMap) (RawServiceMap, error) - Postprocess func(map[string]*ServiceConfig) (map[string]*ServiceConfig, error) -} diff --git a/vendor/github.com/docker/libcompose/config/utils.go b/vendor/github.com/docker/libcompose/config/utils.go deleted file mode 100644 index ae9b86cf9..000000000 --- a/vendor/github.com/docker/libcompose/config/utils.go +++ /dev/null @@ -1,42 +0,0 @@ -package config - -func merge(existing, value interface{}) interface{} { - // append strings - if left, lok := existing.([]interface{}); lok { - if right, rok := value.([]interface{}); rok { - return append(left, right...) - } - } - - //merge maps - if left, lok := existing.(map[interface{}]interface{}); lok { - if right, rok := value.(map[interface{}]interface{}); rok { - newLeft := make(map[interface{}]interface{}) - for k, v := range left { - newLeft[k] = v - } - for k, v := range right { - newLeft[k] = v - } - return newLeft - } - } - - return value -} - -func clone(in RawService) RawService { - result := RawService{} - for k, v := range in { - result[k] = v - } - - return result -} - -func asString(obj interface{}) string { - if v, ok := obj.(string); ok { - return v - } - return "" -} diff --git a/vendor/github.com/docker/libcompose/config/validation.go b/vendor/github.com/docker/libcompose/config/validation.go deleted file mode 100644 index c3a41df1f..000000000 --- a/vendor/github.com/docker/libcompose/config/validation.go +++ /dev/null @@ -1,306 +0,0 @@ -package config - -import ( - "fmt" - "strconv" - "strings" - - "github.com/docker/libcompose/utils" - "github.com/xeipuuv/gojsonschema" -) - -func serviceNameFromErrorField(field string) string { - splitKeys := strings.Split(field, ".") - return splitKeys[0] -} - -func keyNameFromErrorField(field string) string { - splitKeys := strings.Split(field, ".") - - if len(splitKeys) > 0 { - return splitKeys[len(splitKeys)-1] - } - - return "" -} - -func containsTypeError(resultError gojsonschema.ResultError) bool { - contextSplit := strings.Split(resultError.Context().String(), ".") - _, err := strconv.Atoi(contextSplit[len(contextSplit)-1]) - return err == nil -} - -func addArticle(s string) string { - switch s[0] { - case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U': - return "an " + s - default: - return "a " + s - } -} - -// Gets the value in a service map at a given error context -func getValue(val interface{}, context string) string { - keys := strings.Split(context, ".") - - if keys[0] == "(root)" { - keys = keys[1:] - } - - for i, k := range keys { - switch typedVal := (val).(type) { - case string: - return typedVal - case []interface{}: - if index, err := strconv.Atoi(k); err == nil { - val = typedVal[index] - } - case RawServiceMap: - val = typedVal[k] - case RawService: - val = typedVal[k] - case map[interface{}]interface{}: - val = typedVal[k] - } - - if i == len(keys)-1 { - return fmt.Sprint(val) - } - } - - return "" -} - -func convertServiceMapKeysToStrings(serviceMap RawServiceMap) RawServiceMap { - newServiceMap := make(RawServiceMap) - for k, v := range serviceMap { - newServiceMap[k] = convertServiceKeysToStrings(v) - } - return newServiceMap -} - -func convertServiceKeysToStrings(service RawService) RawService { - newService := make(RawService) - for k, v := range service { - newService[k] = utils.ConvertKeysToStrings(v) - } - return newService -} - -var dockerConfigHints = map[string]string{ - "cpu_share": "cpu_shares", - "add_host": "extra_hosts", - "hosts": "extra_hosts", - "extra_host": "extra_hosts", - "device": "devices", - "link": "links", - "memory_swap": "memswap_limit", - "port": "ports", - "privilege": "privileged", - "priviliged": "privileged", - "privilige": "privileged", - "volume": "volumes", - "workdir": "working_dir", -} - -func unsupportedConfigMessage(key string, nextErr gojsonschema.ResultError) string { - service := serviceNameFromErrorField(nextErr.Field()) - - message := fmt.Sprintf("Unsupported config option for %s service: '%s'", service, key) - if val, ok := dockerConfigHints[key]; ok { - message += fmt.Sprintf(" (did you mean '%s'?)", val) - } - - return message -} - -func oneOfMessage(serviceMap RawServiceMap, schema map[string]interface{}, err, nextErr gojsonschema.ResultError) string { - switch nextErr.Type() { - case "additional_property_not_allowed": - property := nextErr.Details()["property"] - - return fmt.Sprintf("contains unsupported option: '%s'", property) - case "invalid_type": - if containsTypeError(nextErr) { - expectedType := addArticle(nextErr.Details()["expected"].(string)) - - return fmt.Sprintf("contains %s, which is an invalid type, it should be %s", getValue(serviceMap, nextErr.Context().String()), expectedType) - } - - validTypes := parseValidTypesFromSchema(schema, err.Context().String()) - - validTypesMsg := addArticle(strings.Join(validTypes, " or ")) - - return fmt.Sprintf("contains an invalid type, it should be %s", validTypesMsg) - case "unique": - contextWithDuplicates := getValue(serviceMap, nextErr.Context().String()) - - return fmt.Sprintf("contains non unique items, please remove duplicates from %s", contextWithDuplicates) - } - - return "" -} - -func invalidTypeMessage(service, key string, err gojsonschema.ResultError) string { - expectedTypesString := err.Details()["expected"].(string) - var expectedTypes []string - - if strings.Contains(expectedTypesString, ",") { - expectedTypes = strings.Split(expectedTypesString[1:len(expectedTypesString)-1], ",") - } else { - expectedTypes = []string{expectedTypesString} - } - - validTypesMsg := addArticle(strings.Join(expectedTypes, " or ")) - - return fmt.Sprintf("Service '%s' configuration key '%s' contains an invalid type, it should be %s.", service, key, validTypesMsg) -} - -func validate(serviceMap RawServiceMap) error { - serviceMap = convertServiceMapKeysToStrings(serviceMap) - - dataLoader := gojsonschema.NewGoLoader(serviceMap) - - result, err := gojsonschema.Validate(schemaLoaderV1, dataLoader) - if err != nil { - return err - } - - return generateErrorMessages(serviceMap, schemaV1, result) -} - -func validateV2(serviceMap RawServiceMap) error { - serviceMap = convertServiceMapKeysToStrings(serviceMap) - - dataLoader := gojsonschema.NewGoLoader(serviceMap) - - result, err := gojsonschema.Validate(schemaLoaderV2, dataLoader) - if err != nil { - return err - } - - return generateErrorMessages(serviceMap, schemaV2, result) -} - -func generateErrorMessages(serviceMap RawServiceMap, schema map[string]interface{}, result *gojsonschema.Result) error { - var validationErrors []string - - // gojsonschema can create extraneous "additional_property_not_allowed" errors in some cases - // If this is set, and the error is at root level, skip over that error - skipRootAdditionalPropertyError := false - - if !result.Valid() { - for i := 0; i < len(result.Errors()); i++ { - err := result.Errors()[i] - - if skipRootAdditionalPropertyError && err.Type() == "additional_property_not_allowed" && err.Context().String() == "(root)" { - skipRootAdditionalPropertyError = false - continue - } - - if err.Context().String() == "(root)" { - switch err.Type() { - case "additional_property_not_allowed": - validationErrors = append(validationErrors, fmt.Sprintf("Invalid service name '%s' - only [a-zA-Z0-9\\._\\-] characters are allowed", err.Details()["property"])) - default: - validationErrors = append(validationErrors, err.Description()) - } - } else { - skipRootAdditionalPropertyError = true - - serviceName := serviceNameFromErrorField(err.Field()) - key := keyNameFromErrorField(err.Field()) - - switch err.Type() { - case "additional_property_not_allowed": - validationErrors = append(validationErrors, unsupportedConfigMessage(result.Errors()[i].Details()["property"].(string), result.Errors()[i])) - case "number_one_of": - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' configuration key '%s' %s", serviceName, key, oneOfMessage(serviceMap, schema, err, result.Errors()[i+1]))) - - // Next error handled in oneOfMessage, skip over it - i++ - case "invalid_type": - validationErrors = append(validationErrors, invalidTypeMessage(serviceName, key, err)) - case "required": - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' option '%s' is invalid, %s", serviceName, key, err.Description())) - case "missing_dependency": - dependency := err.Details()["dependency"].(string) - validationErrors = append(validationErrors, fmt.Sprintf("Invalid configuration for '%s' service: dependency '%s' is not satisfied", serviceName, dependency)) - case "unique": - contextWithDuplicates := getValue(serviceMap, err.Context().String()) - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' configuration key '%s' value %s has non-unique elements", serviceName, key, contextWithDuplicates)) - default: - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' configuration key %s value %s", serviceName, key, err.Description())) - } - } - } - - return fmt.Errorf(strings.Join(validationErrors, "\n")) - } - - return nil -} - -func validateServiceConstraints(service RawService, serviceName string) error { - service = convertServiceKeysToStrings(service) - - var validationErrors []string - - dataLoader := gojsonschema.NewGoLoader(service) - - result, err := gojsonschema.Validate(constraintSchemaLoaderV1, dataLoader) - if err != nil { - return err - } - - if !result.Valid() { - for _, err := range result.Errors() { - if err.Type() == "number_any_of" { - _, containsImage := service["image"] - _, containsBuild := service["build"] - _, containsDockerfile := service["dockerfile"] - - if containsImage && containsBuild { - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has both an image and build path specified. A service can either be built to image or use an existing image, not both.", serviceName)) - } else if !containsImage && !containsBuild { - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build path specified. Exactly one must be provided.", serviceName)) - } else if containsImage && containsDockerfile { - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has both an image and alternate Dockerfile. A service can either be built to image or use an existing image, not both.", serviceName)) - } - } - } - - return fmt.Errorf(strings.Join(validationErrors, "\n")) - } - - return nil -} - -func validateServiceConstraintsv2(service RawService, serviceName string) error { - service = convertServiceKeysToStrings(service) - - var validationErrors []string - - dataLoader := gojsonschema.NewGoLoader(service) - - result, err := gojsonschema.Validate(constraintSchemaLoaderV2, dataLoader) - if err != nil { - return err - } - - if !result.Valid() { - for _, err := range result.Errors() { - if err.Type() == "required" { - _, containsImage := service["image"] - _, containsBuild := service["build"] - - if containsBuild || !containsImage && !containsBuild { - validationErrors = append(validationErrors, fmt.Sprintf("Service '%s' has neither an image nor a build context specified. At least one must be provided.", serviceName)) - } - } - } - return fmt.Errorf(strings.Join(validationErrors, "\n")) - } - - return nil -} diff --git a/vendor/github.com/docker/libcompose/docker/auth/auth.go b/vendor/github.com/docker/libcompose/docker/auth/auth.go deleted file mode 100644 index 2321f6afa..000000000 --- a/vendor/github.com/docker/libcompose/docker/auth/auth.go +++ /dev/null @@ -1,62 +0,0 @@ -package auth - -import ( - "github.com/docker/cli/cli/config/configfile" - clitypes "github.com/docker/cli/cli/config/types" - "github.com/docker/docker/api/types" - "github.com/docker/docker/registry" -) - -// Lookup defines a method for looking up authentication information -type Lookup interface { - All() map[string]types.AuthConfig - Lookup(repoInfo *registry.RepositoryInfo) types.AuthConfig -} - -// ConfigLookup implements AuthLookup by reading a Docker config file -type ConfigLookup struct { - *configfile.ConfigFile -} - -// NewConfigLookup creates a new ConfigLookup for a given context -func NewConfigLookup(configfile *configfile.ConfigFile) *ConfigLookup { - return &ConfigLookup{ - ConfigFile: configfile, - } -} - -// Lookup uses a Docker config file to lookup authentication information -func (c *ConfigLookup) Lookup(repoInfo *registry.RepositoryInfo) types.AuthConfig { - if c.ConfigFile == nil || repoInfo == nil || repoInfo.Index == nil { - return types.AuthConfig{} - } - return registry.ResolveAuthConfig(convert(c.ConfigFile.AuthConfigs), repoInfo.Index) -} - -// All uses a Docker config file to get all authentication information -func (c *ConfigLookup) All() map[string]types.AuthConfig { - if c.ConfigFile == nil { - return map[string]types.AuthConfig{} - } - return convert(c.ConfigFile.AuthConfigs) -} - -func convert(acs map[string]clitypes.AuthConfig) map[string]types.AuthConfig { - if acs == nil { - return nil - } - - result := map[string]types.AuthConfig{} - for k, v := range acs { - result[k] = types.AuthConfig{ - Username: v.Username, - Password: v.Password, - Auth: v.Auth, - Email: v.Email, - ServerAddress: v.ServerAddress, - IdentityToken: v.IdentityToken, - RegistryToken: v.RegistryToken, - } - } - return result -} diff --git a/vendor/github.com/docker/libcompose/docker/builder/builder.go b/vendor/github.com/docker/libcompose/docker/builder/builder.go deleted file mode 100644 index 25b59395f..000000000 --- a/vendor/github.com/docker/libcompose/docker/builder/builder.go +++ /dev/null @@ -1,218 +0,0 @@ -package builder - -import ( - "fmt" - "io" - "os" - "path" - "path/filepath" - "strings" - - "github.com/docker/cli/cli/command/image/build" - "github.com/docker/docker/api/types" - "github.com/docker/docker/builder/dockerignore" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/archive" - "github.com/docker/docker/pkg/fileutils" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/progress" - "github.com/docker/docker/pkg/streamformatter" - "github.com/docker/docker/pkg/term" - "github.com/docker/libcompose/logger" - "github.com/sirupsen/logrus" - "golang.org/x/net/context" -) - -// DefaultDockerfileName is the default name of a Dockerfile -const DefaultDockerfileName = "Dockerfile" - -// Builder defines methods to provide a docker builder. This makes libcompose -// not tied up to the docker daemon builder. -type Builder interface { - Build(imageName string) error -} - -// DaemonBuilder is the daemon "docker build" Builder implementation. -type DaemonBuilder struct { - Client client.ImageAPIClient - ContextDirectory string - Dockerfile string - AuthConfigs map[string]types.AuthConfig - NoCache bool - ForceRemove bool - Pull bool - BuildArgs map[string]*string - CacheFrom []string - Labels map[string]*string - Network string - Target string - LoggerFactory logger.Factory -} - -// Build implements Builder. It consumes the docker build API endpoint and sends -// a tar of the specified service build context. -func (d *DaemonBuilder) Build(ctx context.Context, imageName string) error { - buildCtx, err := CreateTar(d.ContextDirectory, d.Dockerfile) - if err != nil { - return err - } - defer buildCtx.Close() - if d.LoggerFactory == nil { - d.LoggerFactory = &logger.NullLogger{} - } - - l := d.LoggerFactory.CreateBuildLogger(imageName) - - progBuff := &logger.Wrapper{ - Err: false, - Logger: l, - } - - buildBuff := &logger.Wrapper{ - Err: false, - Logger: l, - } - - errBuff := &logger.Wrapper{ - Err: true, - Logger: l, - } - - // Setup an upload progress bar - progressOutput := streamformatter.NewProgressOutput(progBuff) - - var body io.Reader = progress.NewProgressReader(buildCtx, progressOutput, 0, "", "Sending build context to Docker daemon") - - logrus.Infof("Building %s...", imageName) - - outFd, isTerminalOut := term.GetFdInfo(os.Stdout) - w := l.OutWriter() - if w != nil { - outFd, isTerminalOut = term.GetFdInfo(w) - } - - // Convert map[string]*string to map[string]string - labels := make(map[string]string) - for lk, lv := range d.Labels { - labels[lk] = *lv - } - - response, err := d.Client.ImageBuild(ctx, body, types.ImageBuildOptions{ - Tags: []string{imageName}, - NoCache: d.NoCache, - Remove: true, - ForceRemove: d.ForceRemove, - PullParent: d.Pull, - Dockerfile: d.Dockerfile, - AuthConfigs: d.AuthConfigs, - BuildArgs: d.BuildArgs, - CacheFrom: d.CacheFrom, - Labels: labels, - NetworkMode: d.Network, - Target: d.Target, - }) - if err != nil { - return err - } - - err = jsonmessage.DisplayJSONMessagesStream(response.Body, buildBuff, outFd, isTerminalOut, nil) - 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 - } - errBuff.Write([]byte(jerr.Error())) - return fmt.Errorf("Status: %s, Code: %d", jerr.Message, jerr.Code) - } - } - return err -} - -// CreateTar create a build context tar for the specified project and service name. -func CreateTar(contextDirectory, dockerfile string) (io.ReadCloser, error) { - // This code was ripped off from docker/api/client/build.go - dockerfileName := filepath.Join(contextDirectory, dockerfile) - - absContextDirectory, err := filepath.Abs(contextDirectory) - if err != nil { - return nil, err - } - - filename := dockerfileName - - if dockerfile == "" { - // No -f/--file was specified so use the default - dockerfileName = DefaultDockerfileName - filename = filepath.Join(absContextDirectory, dockerfileName) - - // Just to be nice ;-) look for 'dockerfile' too but only - // use it if we found it, otherwise ignore this check - if _, err = os.Lstat(filename); os.IsNotExist(err) { - tmpFN := path.Join(absContextDirectory, strings.ToLower(dockerfileName)) - if _, err = os.Lstat(tmpFN); err == nil { - dockerfileName = strings.ToLower(dockerfileName) - filename = tmpFN - } - } - } - - origDockerfile := dockerfileName // used for error msg - if filename, err = filepath.Abs(filename); err != nil { - return nil, err - } - - // Now reset the dockerfileName to be relative to the build context - dockerfileName, err = filepath.Rel(absContextDirectory, filename) - if err != nil { - return nil, err - } - - // And canonicalize dockerfile name to a platform-independent one - dockerfileName = archive.CanonicalTarNameForPath(dockerfileName) - - if _, err = os.Lstat(filename); os.IsNotExist(err) { - return nil, fmt.Errorf("Cannot locate Dockerfile: %s", origDockerfile) - } - var includes = []string{"."} - var excludes []string - - dockerIgnorePath := path.Join(contextDirectory, ".dockerignore") - dockerIgnore, err := os.Open(dockerIgnorePath) - if err != nil { - if !os.IsNotExist(err) { - return nil, err - } - logrus.Warnf("Error while reading .dockerignore (%s) : %s", dockerIgnorePath, err.Error()) - excludes = make([]string, 0) - } else { - excludes, err = dockerignore.ReadAll(dockerIgnore) - if err != nil { - return nil, err - } - } - - // If .dockerignore mentions .dockerignore or the Dockerfile - // then make sure we send both files over to the daemon - // because Dockerfile is, obviously, needed no matter what, and - // .dockerignore is needed to know if either one needs to be - // removed. The deamon will remove them for us, if needed, after it - // parses the Dockerfile. - keepThem1, _ := fileutils.Matches(".dockerignore", excludes) - keepThem2, _ := fileutils.Matches(dockerfileName, excludes) - if keepThem1 || keepThem2 { - includes = append(includes, ".dockerignore", dockerfileName) - } - - if err := build.ValidateContextDirectory(contextDirectory, excludes); err != nil { - return nil, fmt.Errorf("error checking context is accessible: '%s', please check permissions and try again", err) - } - - options := &archive.TarOptions{ - Compression: archive.Uncompressed, - ExcludePatterns: excludes, - IncludeFiles: includes, - } - - return archive.TarWithOptions(contextDirectory, options) -} diff --git a/vendor/github.com/docker/libcompose/docker/client/client.go b/vendor/github.com/docker/libcompose/docker/client/client.go deleted file mode 100644 index 70b825fe0..000000000 --- a/vendor/github.com/docker/libcompose/docker/client/client.go +++ /dev/null @@ -1,110 +0,0 @@ -package client - -import ( - "fmt" - "net/http" - "os" - "path/filepath" - "runtime" - - cliconfig "github.com/docker/cli/cli/config" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/homedir" - "github.com/docker/go-connections/tlsconfig" - "github.com/docker/libcompose/version" -) - -const ( - // DefaultAPIVersion is the default docker API version set by libcompose - DefaultAPIVersion = "v1.20" - defaultTrustKeyFile = "key.json" - defaultCaFile = "ca.pem" - defaultKeyFile = "key.pem" - defaultCertFile = "cert.pem" -) - -var ( - dockerCertPath = os.Getenv("DOCKER_CERT_PATH") -) - -func init() { - if dockerCertPath == "" { - dockerCertPath = cliconfig.Dir() - } -} - -// Options holds docker client options (host, tls, ..) -type Options struct { - TLS bool - TLSVerify bool - TLSOptions tlsconfig.Options - TrustKey string - Host string - APIVersion string -} - -// Create creates a docker client based on the specified options. -func Create(c Options) (client.APIClient, error) { - if c.Host == "" { - if os.Getenv("DOCKER_API_VERSION") == "" { - os.Setenv("DOCKER_API_VERSION", DefaultAPIVersion) - } - client, err := client.NewEnvClient() - if err != nil { - return nil, err - } - return client, nil - } - - apiVersion := c.APIVersion - if apiVersion == "" { - apiVersion = DefaultAPIVersion - } - - if c.TLSOptions.CAFile == "" { - c.TLSOptions.CAFile = filepath.Join(dockerCertPath, defaultCaFile) - } - if c.TLSOptions.CertFile == "" { - c.TLSOptions.CertFile = filepath.Join(dockerCertPath, defaultCertFile) - } - if c.TLSOptions.KeyFile == "" { - c.TLSOptions.KeyFile = filepath.Join(dockerCertPath, defaultKeyFile) - } - if c.TrustKey == "" { - c.TrustKey = filepath.Join(homedir.Get(), ".docker", defaultTrustKeyFile) - } - if c.TLSVerify { - c.TLS = true - } - if c.TLS { - c.TLSOptions.InsecureSkipVerify = !c.TLSVerify - } - - var httpClient *http.Client - if c.TLS { - config, err := tlsconfig.Client(c.TLSOptions) - if err != nil { - return nil, err - } - - httpClient = &http.Client{ - Transport: &http.Transport{ - TLSClientConfig: config, - }, - } - } - - customHeaders := map[string]string{} - customHeaders["User-Agent"] = fmt.Sprintf("Libcompose-Client/%s (%s)", version.VERSION, runtime.GOOS) - - client, err := client.NewClientWithOpts( - client.WithHTTPClient(httpClient), - client.WithHost(c.Host), - client.WithVersion(apiVersion), - client.WithHTTPHeaders(customHeaders), - ) - if err != nil { - return nil, err - } - return client, nil -} diff --git a/vendor/github.com/docker/libcompose/docker/client/client_factory.go b/vendor/github.com/docker/libcompose/docker/client/client_factory.go deleted file mode 100644 index 26d88d70b..000000000 --- a/vendor/github.com/docker/libcompose/docker/client/client_factory.go +++ /dev/null @@ -1,35 +0,0 @@ -package client - -import ( - "github.com/docker/docker/client" - "github.com/docker/libcompose/project" -) - -// Factory is a factory to create docker clients. -type Factory interface { - // Create constructs a Docker client for the given service. The passed in - // config may be nil in which case a generic client for the project should - // be returned. - Create(service project.Service) client.APIClient -} - -type defaultFactory struct { - client client.APIClient -} - -// NewDefaultFactory creates and returns the default client factory that uses -// github.com/docker/docker client. -func NewDefaultFactory(opts Options) (Factory, error) { - client, err := Create(opts) - if err != nil { - return nil, err - } - - return &defaultFactory{ - client: client, - }, nil -} - -func (s *defaultFactory) Create(service project.Service) client.APIClient { - return s.client -} diff --git a/vendor/github.com/docker/libcompose/docker/container/container.go b/vendor/github.com/docker/libcompose/docker/container/container.go deleted file mode 100644 index d26458537..000000000 --- a/vendor/github.com/docker/libcompose/docker/container/container.go +++ /dev/null @@ -1,401 +0,0 @@ -package container - -import ( - "fmt" - "io" - "math" - "os" - "strconv" - "strings" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/stdcopy" - "github.com/docker/docker/pkg/term" - "github.com/docker/go-connections/nat" - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/labels" - "github.com/docker/libcompose/logger" - "github.com/docker/libcompose/project" - "github.com/sirupsen/logrus" -) - -// Container holds information about a docker container and the service it is tied on. -type Container struct { - client client.ContainerAPIClient - id string - container *types.ContainerJSON -} - -// Create creates a container and return a Container struct (and an error if any) -func Create(ctx context.Context, client client.ContainerAPIClient, name string, config *container.Config, hostConfig *container.HostConfig, networkingConfig *network.NetworkingConfig) (*Container, error) { - container, err := client.ContainerCreate(ctx, config, hostConfig, networkingConfig, name) - if err != nil { - return nil, err - } - return New(ctx, client, container.ID) -} - -// New creates a container struct with the specified client, id and name -func New(ctx context.Context, client client.ContainerAPIClient, id string) (*Container, error) { - container, err := Get(ctx, client, id) - if err != nil { - return nil, err - } - return &Container{ - client: client, - id: id, - container: container, - }, nil -} - -// NewInspected creates a container struct from an inspected container -func NewInspected(client client.ContainerAPIClient, container *types.ContainerJSON) *Container { - return &Container{ - client: client, - id: container.ID, - container: container, - } -} - -// Info returns info about the container, like name, command, state or ports. -func (c *Container) Info(ctx context.Context) (project.Info, error) { - infos, err := ListByFilter(ctx, c.client, map[string][]string{ - "name": {c.container.Name}, - }) - if err != nil || len(infos) == 0 { - return nil, err - } - info := infos[0] - - result := project.Info{} - result["Id"] = c.container.ID - result["Name"] = name(info.Names) - result["Command"] = info.Command - result["State"] = info.Status - result["Ports"] = portString(info.Ports) - - return result, nil -} - -func portString(ports []types.Port) string { - result := []string{} - - for _, port := range ports { - if port.PublicPort > 0 { - result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.IP, port.PublicPort, port.PrivatePort, port.Type)) - } else { - result = append(result, fmt.Sprintf("%d/%s", port.PrivatePort, port.Type)) - } - } - - return strings.Join(result, ", ") -} - -func name(names []string) string { - max := math.MaxInt32 - var current string - - for _, v := range names { - if len(v) < max { - max = len(v) - current = v - } - } - - return current[1:] -} - -// Rename rename the container. -func (c *Container) Rename(ctx context.Context, newName string) error { - return c.client.ContainerRename(ctx, c.container.ID, newName) -} - -// Remove removes the container. -func (c *Container) Remove(ctx context.Context, removeVolume bool) error { - return c.client.ContainerRemove(ctx, c.container.ID, types.ContainerRemoveOptions{ - Force: true, - RemoveVolumes: removeVolume, - }) -} - -// Stop stops the container. -func (c *Container) Stop(ctx context.Context, timeout int) error { - timeoutDuration := time.Duration(timeout) * time.Second - return c.client.ContainerStop(ctx, c.container.ID, &timeoutDuration) -} - -// Pause pauses the container. If the containers are already paused, don't fail. -func (c *Container) Pause(ctx context.Context) error { - if !c.container.State.Paused { - if err := c.client.ContainerPause(ctx, c.container.ID); err != nil { - return err - } - return c.updateInnerContainer(ctx) - } - return nil -} - -// Unpause unpauses the container. If the containers are not paused, don't fail. -func (c *Container) Unpause(ctx context.Context) error { - if c.container.State.Paused { - if err := c.client.ContainerUnpause(ctx, c.container.ID); err != nil { - return err - } - return c.updateInnerContainer(ctx) - } - return nil -} - -func (c *Container) updateInnerContainer(ctx context.Context) error { - container, err := Get(ctx, c.client, c.container.ID) - if err != nil { - return err - } - c.container = container - return nil -} - -// Kill kill the container. -func (c *Container) Kill(ctx context.Context, signal string) error { - return c.client.ContainerKill(ctx, c.container.ID, signal) -} - -// IsRunning returns the running state of the container. -func (c *Container) IsRunning(ctx context.Context) bool { - return c.container.State.Running -} - -// Run creates, start and attach to the container based on the image name, -// the specified configuration. -// It will always create a new container. -func (c *Container) Run(ctx context.Context, configOverride *config.ServiceConfig) (int, error) { - var ( - errCh chan error - out, stderr io.Writer - in io.ReadCloser - inFd uintptr - ) - - if configOverride.StdinOpen { - in = os.Stdin - } - if configOverride.Tty { - out = os.Stdout - stderr = os.Stderr - } - - options := types.ContainerAttachOptions{ - Stream: true, - Stdin: configOverride.StdinOpen, - Stdout: configOverride.Tty, - Stderr: configOverride.Tty, - } - - resp, err := c.client.ContainerAttach(ctx, c.container.ID, options) - if err != nil { - return -1, err - } - - if configOverride.StdinOpen { - // set raw terminal - inFd, _ = term.GetFdInfo(in) - state, err := term.SetRawTerminal(inFd) - if err != nil { - return -1, err - } - // restore raw terminal - defer term.RestoreTerminal(inFd, state) - } - - // holdHijackedConnection (in goroutine) - errCh = make(chan error, 1) - go func() { - errCh <- holdHijackedConnection(configOverride.Tty, in, out, stderr, resp) - }() - - if err := c.client.ContainerStart(ctx, c.container.ID, types.ContainerStartOptions{}); err != nil { - return -1, err - } - - if configOverride.Tty { - ws, err := term.GetWinsize(inFd) - if err != nil { - return -1, err - } - - resizeOpts := types.ResizeOptions{ - Height: uint(ws.Height), - Width: uint(ws.Width), - } - - if err := c.client.ContainerResize(ctx, c.container.ID, resizeOpts); err != nil { - return -1, err - } - } - - if err := <-errCh; err != nil { - logrus.Debugf("Error hijack: %s", err) - return -1, err - } - - exitedContainer, err := c.client.ContainerInspect(ctx, c.container.ID) - if err != nil { - return -1, err - } - - return exitedContainer.State.ExitCode, nil -} - -func holdHijackedConnection(tty bool, inputStream io.ReadCloser, outputStream, errorStream io.Writer, resp types.HijackedResponse) error { - var err error - receiveStdout := make(chan error, 1) - if outputStream != nil || errorStream != nil { - go func() { - // When TTY is ON, use regular copy - if tty && outputStream != nil { - _, err = io.Copy(outputStream, resp.Reader) - } else { - _, err = stdcopy.StdCopy(outputStream, errorStream, resp.Reader) - } - logrus.Debugf("[hijack] End of stdout") - receiveStdout <- err - }() - } - - stdinDone := make(chan struct{}) - go func() { - if inputStream != nil { - io.Copy(resp.Conn, inputStream) - logrus.Debugf("[hijack] End of stdin") - } - - if err := resp.CloseWrite(); err != nil { - logrus.Debugf("Couldn't send EOF: %s", err) - } - close(stdinDone) - }() - - select { - case err := <-receiveStdout: - if err != nil { - logrus.Debugf("Error receiveStdout: %s", err) - return err - } - case <-stdinDone: - if outputStream != nil || errorStream != nil { - if err := <-receiveStdout; err != nil { - logrus.Debugf("Error receiveStdout: %s", err) - return err - } - } - } - - return nil -} - -// Start the specified container with the specified host config -func (c *Container) Start(ctx context.Context) error { - logrus.WithFields(logrus.Fields{"container.ID": c.container.ID, "container.Name": c.container.Name}).Debug("Starting container") - if err := c.client.ContainerStart(ctx, c.container.ID, types.ContainerStartOptions{}); err != nil { - logrus.WithFields(logrus.Fields{"container.ID": c.container.ID, "container.Name": c.container.Name}).Debug("Failed to start container") - return err - } - return nil -} - -// Restart restarts the container if existing, does nothing otherwise. -func (c *Container) Restart(ctx context.Context, timeout int) error { - timeoutDuration := time.Duration(timeout) * time.Second - return c.client.ContainerRestart(ctx, c.container.ID, &timeoutDuration) -} - -// Log forwards container logs to the project configured logger. -func (c *Container) Log(ctx context.Context, l logger.Logger, follow bool) error { - info, err := c.client.ContainerInspect(ctx, c.container.ID) - if err != nil { - return err - } - - options := types.ContainerLogsOptions{ - ShowStdout: true, - ShowStderr: true, - Follow: follow, - Tail: "all", - } - responseBody, err := c.client.ContainerLogs(ctx, c.container.ID, options) - if err != nil { - return err - } - defer responseBody.Close() - - if info.Config.Tty { - _, err = io.Copy(&logger.Wrapper{Logger: l}, responseBody) - } else { - _, err = stdcopy.StdCopy(&logger.Wrapper{Logger: l}, &logger.Wrapper{Logger: l, Err: true}, responseBody) - } - logrus.WithFields(logrus.Fields{"Logger": l, "err": err}).Debug("c.client.Logs() returned error") - - return err -} - -// Port returns the host port the specified port is mapped on. -func (c *Container) Port(ctx context.Context, port string) (string, error) { - if bindings, ok := c.container.NetworkSettings.Ports[nat.Port(port)]; ok { - result := []string{} - for _, binding := range bindings { - result = append(result, binding.HostIP+":"+binding.HostPort) - } - - return strings.Join(result, "\n"), nil - } - return "", nil -} - -// Networks returns the containers network -func (c *Container) Networks() (map[string]*network.EndpointSettings, error) { - return c.container.NetworkSettings.Networks, nil -} - -// ID returns the container Id. -func (c *Container) ID() string { - return c.container.ID -} - -// ShortID return the container Id in its short form -func (c *Container) ShortID() string { - return c.container.ID[:12] -} - -// Name returns the container name. -func (c *Container) Name() string { - return c.container.Name -} - -// Image returns the container image. Depending on the engine version its either -// the complete id or the digest reference the image. -func (c *Container) Image() string { - return c.container.Image -} - -// ImageConfig returns the container image stored in the config. It's the -// human-readable name of the image. -func (c *Container) ImageConfig() string { - return c.container.Config.Image -} - -// Hash returns the container hash stored as label. -func (c *Container) Hash() string { - return c.container.Config.Labels[labels.HASH.Str()] -} - -// Number returns the container number stored as label. -func (c *Container) Number() (int, error) { - numberStr := c.container.Config.Labels[labels.NUMBER.Str()] - return strconv.Atoi(numberStr) -} diff --git a/vendor/github.com/docker/libcompose/docker/container/functions.go b/vendor/github.com/docker/libcompose/docker/container/functions.go deleted file mode 100644 index d97d66692..000000000 --- a/vendor/github.com/docker/libcompose/docker/container/functions.go +++ /dev/null @@ -1,41 +0,0 @@ -package container - -import ( - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/client" - "golang.org/x/net/context" -) - -// ListByFilter looks up the hosts containers with the specified filters and -// returns a list of container matching it, or an error. -func ListByFilter(ctx context.Context, clientInstance client.ContainerAPIClient, containerFilters ...map[string][]string) ([]types.Container, error) { - filterArgs := filters.NewArgs() - - // FIXME(vdemeester) I don't like 3 for loops >_< - for _, filter := range containerFilters { - for key, filterValue := range filter { - for _, value := range filterValue { - filterArgs.Add(key, value) - } - } - } - - return clientInstance.ContainerList(ctx, types.ContainerListOptions{ - All: true, - Filters: filterArgs, - }) -} - -// Get looks up the hosts containers with the specified ID -// or name and returns it, or an error. -func Get(ctx context.Context, clientInstance client.ContainerAPIClient, id string) (*types.ContainerJSON, error) { - container, err := clientInstance.ContainerInspect(ctx, id) - if err != nil { - if client.IsErrNotFound(err) { - return nil, nil - } - return nil, err - } - return &container, nil -} diff --git a/vendor/github.com/docker/libcompose/docker/ctx/context.go b/vendor/github.com/docker/libcompose/docker/ctx/context.go deleted file mode 100644 index 35ee42a8d..000000000 --- a/vendor/github.com/docker/libcompose/docker/ctx/context.go +++ /dev/null @@ -1,35 +0,0 @@ -package ctx - -import ( - cliconfig "github.com/docker/cli/cli/config" - "github.com/docker/cli/cli/config/configfile" - "github.com/docker/libcompose/docker/auth" - "github.com/docker/libcompose/docker/client" - "github.com/docker/libcompose/project" -) - -// Context holds context meta information about a libcompose project and docker -// client information (like configuration file, builder to use, …) -type Context struct { - project.Context - ClientFactory client.Factory - ConfigDir string - ConfigFile *configfile.ConfigFile - AuthLookup auth.Lookup -} - -// LookupConfig tries to load the docker configuration files, if any. -func (c *Context) LookupConfig() error { - if c.ConfigFile != nil { - return nil - } - - config, err := cliconfig.Load(c.ConfigDir) - if err != nil { - return err - } - - c.ConfigFile = config - - return nil -} diff --git a/vendor/github.com/docker/libcompose/docker/image/image.go b/vendor/github.com/docker/libcompose/docker/image/image.go deleted file mode 100644 index f4bc25145..000000000 --- a/vendor/github.com/docker/libcompose/docker/image/image.go +++ /dev/null @@ -1,104 +0,0 @@ -package image - -import ( - "encoding/base64" - "encoding/json" - "fmt" - "io" - "os" - - "github.com/docker/distribution/reference" - "github.com/docker/docker/api/types" - "github.com/docker/docker/client" - "github.com/docker/docker/pkg/jsonmessage" - "github.com/docker/docker/pkg/term" - "github.com/docker/docker/registry" - "github.com/docker/libcompose/docker/auth" - "github.com/sirupsen/logrus" - "golang.org/x/net/context" -) - -// Exists return whether or not the service image already exists -func Exists(ctx context.Context, clt client.ImageAPIClient, image string) (bool, error) { - _, err := InspectImage(ctx, clt, image) - if err != nil { - if client.IsErrNotFound(err) { - return false, nil - } - return false, err - } - return true, nil -} - -// InspectImage inspect the specified image (can be a name, an id or a digest) -// with the specified client. -func InspectImage(ctx context.Context, client client.ImageAPIClient, image string) (types.ImageInspect, error) { - imageInspect, _, err := client.ImageInspectWithRaw(ctx, image) - return imageInspect, err -} - -// RemoveImage removes the specified image (can be a name, an id or a digest) -// from the daemon store with the specified client. -func RemoveImage(ctx context.Context, client client.ImageAPIClient, image string) error { - _, err := client.ImageRemove(ctx, image, types.ImageRemoveOptions{}) - return err -} - -// PullImage pulls the specified image (can be a name, an id or a digest) -// to the daemon store with the specified client. -func PullImage(ctx context.Context, client client.ImageAPIClient, serviceName string, authLookup auth.Lookup, image string) error { - fmt.Fprintf(os.Stderr, "Pulling %s (%s)...\n", serviceName, image) - distributionRef, err := reference.ParseNormalizedNamed(image) - if err != nil { - return err - } - - repoInfo, err := registry.ParseRepositoryInfo(distributionRef) - if err != nil { - return err - } - - authConfig := authLookup.Lookup(repoInfo) - - // Use ConfigFile.SaveToWriter to not re-define encodeAuthToBase64 - encodedAuth, err := encodeAuthToBase64(authConfig) - if err != nil { - return err - } - - options := types.ImagePullOptions{ - RegistryAuth: encodedAuth, - } - responseBody, err := client.ImagePull(ctx, distributionRef.String(), options) - if err != nil { - logrus.Errorf("Failed to pull image %s: %v", image, err) - return err - } - defer responseBody.Close() - - var writeBuff io.Writer = os.Stderr - - outFd, isTerminalOut := term.GetFdInfo(os.Stderr) - - err = jsonmessage.DisplayJSONMessagesStream(responseBody, writeBuff, outFd, isTerminalOut, nil) - 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 - } - fmt.Fprintf(os.Stderr, "%s", writeBuff) - return fmt.Errorf("Status: %s, Code: %d", jerr.Message, jerr.Code) - } - } - return err -} - -// encodeAuthToBase64 serializes the auth configuration as JSON base64 payload -func encodeAuthToBase64(authConfig types.AuthConfig) (string, error) { - buf, err := json.Marshal(authConfig) - if err != nil { - return "", err - } - return base64.URLEncoding.EncodeToString(buf), nil -} diff --git a/vendor/github.com/docker/libcompose/docker/network/factory.go b/vendor/github.com/docker/libcompose/docker/network/factory.go deleted file mode 100644 index 158131f07..000000000 --- a/vendor/github.com/docker/libcompose/docker/network/factory.go +++ /dev/null @@ -1,19 +0,0 @@ -package network - -import ( - "github.com/docker/libcompose/config" - composeclient "github.com/docker/libcompose/docker/client" - "github.com/docker/libcompose/project" -) - -// DockerFactory implements project.NetworksFactory -type DockerFactory struct { - ClientFactory composeclient.Factory -} - -// Create implements project.NetworksFactory Create method. -// It creates a Networks (that implements project.Networks) from specified configurations. -func (f *DockerFactory) Create(projectName string, networkConfigs map[string]*config.NetworkConfig, serviceConfigs *config.ServiceConfigs, networkEnabled bool) (project.Networks, error) { - cli := f.ClientFactory.Create(nil) - return NetworksFromServices(cli, projectName, networkConfigs, serviceConfigs, networkEnabled) -} diff --git a/vendor/github.com/docker/libcompose/docker/network/network.go b/vendor/github.com/docker/libcompose/docker/network/network.go deleted file mode 100644 index 632a18fd0..000000000 --- a/vendor/github.com/docker/libcompose/docker/network/network.go +++ /dev/null @@ -1,202 +0,0 @@ -package network - -import ( - "fmt" - "reflect" - "strings" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/client" - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/yaml" -) - -// Network holds attributes and method for a network definition in compose -type Network struct { - client client.NetworkAPIClient - name string - projectName string - driver string - driverOptions map[string]string - ipam config.Ipam - external bool -} - -func (n *Network) fullName() string { - name := n.projectName + "_" + n.name - if n.external { - name = n.name - } - return name -} - -// Inspect inspect the current network -func (n *Network) Inspect(ctx context.Context) (types.NetworkResource, error) { - return n.client.NetworkInspect(ctx, n.fullName(), types.NetworkInspectOptions{ - Verbose: true, - }) -} - -// Remove removes the current network (from docker engine) -func (n *Network) Remove(ctx context.Context) error { - if n.external { - fmt.Printf("Network %s is external, skipping", n.fullName()) - return nil - } - fmt.Printf("Removing network %q\n", n.fullName()) - return n.client.NetworkRemove(ctx, n.fullName()) -} - -// EnsureItExists make sure the network exists and return an error if it does not exists -// and cannot be created. -func (n *Network) EnsureItExists(ctx context.Context) error { - networkResource, err := n.Inspect(ctx) - if n.external { - if client.IsErrNotFound(err) { - // FIXME(vdemeester) introduce some libcompose error type - return fmt.Errorf("Network %s declared as external, but could not be found. Please create the network manually using docker network create %s and try again", n.fullName(), n.fullName()) - } - return err - } - if err != nil && client.IsErrNotFound(err) { - return n.create(ctx) - } - if n.driver != "" && networkResource.Driver != n.driver { - return fmt.Errorf("Network %q needs to be recreated - driver has changed", n.fullName()) - } - if len(n.driverOptions) != 0 && !reflect.DeepEqual(networkResource.Options, n.driverOptions) { - return fmt.Errorf("Network %q needs to be recreated - options have changed", n.fullName()) - } - return err -} - -func (n *Network) create(ctx context.Context) error { - fmt.Printf("Creating network %q with driver %q\n", n.fullName(), n.driver) - _, err := n.client.NetworkCreate(ctx, n.fullName(), types.NetworkCreate{ - Driver: n.driver, - Options: n.driverOptions, - IPAM: convertToAPIIpam(n.ipam), - }) - return err -} - -func convertToAPIIpam(ipam config.Ipam) *network.IPAM { - ipamConfigs := []network.IPAMConfig{} - for _, config := range ipam.Config { - ipamConfigs = append(ipamConfigs, network.IPAMConfig{ - Subnet: config.Subnet, - IPRange: config.IPRange, - Gateway: config.Gateway, - AuxAddress: config.AuxAddress, - }) - } - return &network.IPAM{ - Driver: ipam.Driver, - Config: ipamConfigs, - } -} - -// NewNetwork creates a new network from the specified name and config. -func NewNetwork(projectName, name string, config *config.NetworkConfig, client client.NetworkAPIClient) *Network { - networkName := name - if config.External.External { - networkName = config.External.Name - } - return &Network{ - client: client, - name: networkName, - projectName: projectName, - driver: config.Driver, - driverOptions: config.DriverOpts, - external: config.External.External, - ipam: config.Ipam, - } -} - -// Networks holds a list of network -type Networks struct { - networks []*Network - networkEnabled bool -} - -// Initialize make sure network exists if network is enabled -func (n *Networks) Initialize(ctx context.Context) error { - if !n.networkEnabled { - return nil - } - for _, network := range n.networks { - err := network.EnsureItExists(ctx) - if err != nil { - return err - } - } - return nil -} - -// Remove removes networks (clean-up) -func (n *Networks) Remove(ctx context.Context) error { - if !n.networkEnabled { - return nil - } - for _, network := range n.networks { - err := network.Remove(ctx) - if err != nil { - return err - } - } - return nil -} - -// NetworksFromServices creates a new Networks struct based on networks configurations and -// services configuration. If a network is defined but not used by any service, it will return -// an error along the Networks. -func NetworksFromServices(cli client.NetworkAPIClient, projectName string, networkConfigs map[string]*config.NetworkConfig, services *config.ServiceConfigs, networkEnabled bool) (*Networks, error) { - var err error - networks := make([]*Network, 0, len(networkConfigs)) - networkNames := map[string]*yaml.Network{} - for _, serviceName := range services.Keys() { - serviceConfig, _ := services.Get(serviceName) - if serviceConfig.NetworkMode != "" || serviceConfig.Networks == nil || len(serviceConfig.Networks.Networks) == 0 { - continue - } - for _, network := range serviceConfig.Networks.Networks { - if network.Name != "default" { - if _, ok := networkConfigs[network.Name]; !ok { - return nil, fmt.Errorf(`Service "%s" uses an undefined network "%s"`, serviceName, network.Name) - } - } - networkNames[network.Name] = network - } - } - if len(networkConfigs) == 0 { - network := NewNetwork(projectName, "default", &config.NetworkConfig{ - Driver: "bridge", - }, cli) - networks = append(networks, network) - } - for name, config := range networkConfigs { - network := NewNetwork(projectName, name, config, cli) - networks = append(networks, network) - } - if len(networkNames) != len(networks) { - unused := []string{} - for name := range networkConfigs { - if name == "default" { - continue - } - if _, ok := networkNames[name]; !ok { - unused = append(unused, name) - } - } - if len(unused) != 0 { - err = fmt.Errorf("Some networks were defined but are not used by any service: %v", strings.Join(unused, " ")) - } - } - return &Networks{ - networks: networks, - networkEnabled: networkEnabled, - }, err -} diff --git a/vendor/github.com/docker/libcompose/docker/project.go b/vendor/github.com/docker/libcompose/docker/project.go deleted file mode 100644 index 4713d0f2d..000000000 --- a/vendor/github.com/docker/libcompose/docker/project.go +++ /dev/null @@ -1,106 +0,0 @@ -package docker - -import ( - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/docker/auth" - "github.com/docker/libcompose/docker/client" - "github.com/docker/libcompose/docker/ctx" - "github.com/docker/libcompose/docker/network" - "github.com/docker/libcompose/docker/service" - "github.com/docker/libcompose/docker/volume" - "github.com/docker/libcompose/labels" - "github.com/docker/libcompose/project" - "github.com/sirupsen/logrus" -) - -// NewProject creates a Project with the specified context. -func NewProject(context *ctx.Context, parseOptions *config.ParseOptions) (project.APIProject, error) { - - if err := context.LookupConfig(); err != nil { - logrus.Errorf("Failed to load docker config: %v", err) - } - - if context.AuthLookup == nil { - context.AuthLookup = auth.NewConfigLookup(context.ConfigFile) - } - - if context.ServiceFactory == nil { - context.ServiceFactory = service.NewFactory(context) - } - - if context.ClientFactory == nil { - factory, err := client.NewDefaultFactory(client.Options{}) - if err != nil { - return nil, err - } - context.ClientFactory = factory - } - - if context.NetworksFactory == nil { - networksFactory := &network.DockerFactory{ - ClientFactory: context.ClientFactory, - } - context.NetworksFactory = networksFactory - } - - if context.VolumesFactory == nil { - volumesFactory := &volume.DockerFactory{ - ClientFactory: context.ClientFactory, - } - context.VolumesFactory = volumesFactory - } - - // FIXME(vdemeester) Remove the context duplication ? - runtime := &Project{ - clientFactory: context.ClientFactory, - } - p := project.NewProject(&context.Context, runtime, parseOptions) - - err := p.Parse() - if err != nil { - return nil, err - } - - return p, err -} - -// Project implements project.RuntimeProject and define docker runtime specific methods. -type Project struct { - clientFactory client.Factory -} - -// RemoveOrphans implements project.RuntimeProject.RemoveOrphans. -// It will remove orphan containers that are part of the project but not to any services. -func (p *Project) RemoveOrphans(ctx context.Context, projectName string, serviceConfigs *config.ServiceConfigs) error { - client := p.clientFactory.Create(nil) - filter := filters.NewArgs() - filter.Add("label", labels.PROJECT.EqString(projectName)) - containers, err := client.ContainerList(ctx, types.ContainerListOptions{ - Filters: filter, - }) - if err != nil { - return err - } - currentServices := map[string]struct{}{} - for _, serviceName := range serviceConfigs.Keys() { - currentServices[serviceName] = struct{}{} - } - for _, container := range containers { - serviceLabel := container.Labels[labels.SERVICE.Str()] - if _, ok := currentServices[serviceLabel]; !ok { - if err := client.ContainerKill(ctx, container.ID, "SIGKILL"); err != nil { - return err - } - if err := client.ContainerRemove(ctx, container.ID, types.ContainerRemoveOptions{ - Force: true, - }); err != nil { - return err - } - } - } - return nil -} diff --git a/vendor/github.com/docker/libcompose/docker/service/convert.go b/vendor/github.com/docker/libcompose/docker/service/convert.go deleted file mode 100644 index fbce036f2..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/convert.go +++ /dev/null @@ -1,376 +0,0 @@ -package service - -import ( - "fmt" - "strings" - - "github.com/docker/cli/opts" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-connections/nat" - "github.com/docker/go-units" - "github.com/docker/libcompose/config" - composeclient "github.com/docker/libcompose/docker/client" - composecontainer "github.com/docker/libcompose/docker/container" - "github.com/docker/libcompose/project" - "github.com/docker/libcompose/utils" - "golang.org/x/net/context" -) - -// ConfigWrapper wraps Config, HostConfig and NetworkingConfig for a container. -type ConfigWrapper struct { - Config *container.Config - HostConfig *container.HostConfig - NetworkingConfig *network.NetworkingConfig -} - -// Filter filters the specified string slice with the specified function. -func Filter(vs []string, f func(string) bool) []string { - r := make([]string, 0, len(vs)) - for _, v := range vs { - if f(v) { - r = append(r, v) - } - } - return r -} - -func toMap(vs []string) map[string]struct{} { - m := map[string]struct{}{} - for _, v := range vs { - if v != "" { - m[v] = struct{}{} - } - } - return m -} - -func isBind(s string) bool { - return strings.ContainsRune(s, ':') -} - -func isVolume(s string) bool { - return !isBind(s) -} - -// ConvertToAPI converts a service configuration to a docker API container configuration. -func ConvertToAPI(serviceConfig *config.ServiceConfig, ctx project.Context, clientFactory composeclient.Factory) (*ConfigWrapper, error) { - config, hostConfig, err := Convert(serviceConfig, ctx, clientFactory) - if err != nil { - return nil, err - } - - result := ConfigWrapper{ - Config: config, - HostConfig: hostConfig, - } - return &result, nil -} - -func volumes(c *config.ServiceConfig, ctx project.Context) []string { - if c.Volumes == nil { - return []string{} - } - volumes := make([]string, len(c.Volumes.Volumes)) - for _, v := range c.Volumes.Volumes { - vol := v - if len(ctx.ComposeFiles) > 0 && !project.IsNamedVolume(v.Source) { - sourceVol := ctx.ResourceLookup.ResolvePath(v.String(), ctx.ComposeFiles[0]) - vol.Source = strings.SplitN(sourceVol, ":", 2)[0] - } - volumes = append(volumes, vol.String()) - } - return volumes -} - -func restartPolicy(c *config.ServiceConfig) (*container.RestartPolicy, error) { - restart, err := opts.ParseRestartPolicy(c.Restart) - if err != nil { - return nil, err - } - return &container.RestartPolicy{Name: restart.Name, MaximumRetryCount: restart.MaximumRetryCount}, nil -} - -func ports(c *config.ServiceConfig) (map[nat.Port]struct{}, nat.PortMap, error) { - ports, binding, err := nat.ParsePortSpecs(c.Ports) - if err != nil { - return nil, nil, err - } - - exPorts, _, err := nat.ParsePortSpecs(c.Expose) - if err != nil { - return nil, nil, err - } - - for k, v := range exPorts { - ports[k] = v - } - - exposedPorts := map[nat.Port]struct{}{} - for k, v := range ports { - exposedPorts[nat.Port(k)] = v - } - - portBindings := nat.PortMap{} - for k, bv := range binding { - dcbs := make([]nat.PortBinding, len(bv)) - for k, v := range bv { - dcbs[k] = nat.PortBinding{HostIP: v.HostIP, HostPort: v.HostPort} - } - portBindings[nat.Port(k)] = dcbs - } - return exposedPorts, portBindings, nil -} - -// Convert converts a service configuration to an docker API structures (Config and HostConfig) -func Convert(c *config.ServiceConfig, ctx project.Context, clientFactory composeclient.Factory) (*container.Config, *container.HostConfig, error) { - restartPolicy, err := restartPolicy(c) - if err != nil { - return nil, nil, err - } - - exposedPorts, portBindings, err := ports(c) - if err != nil { - return nil, nil, err - } - - deviceMappings, err := parseDevices(c.Devices) - if err != nil { - return nil, nil, err - } - - var volumesFrom []string - if c.VolumesFrom != nil { - volumesFrom, err = getVolumesFrom(c.VolumesFrom, ctx.Project.ServiceConfigs, ctx.ProjectName) - if err != nil { - return nil, nil, err - } - } - - vols := volumes(c, ctx) - - config := &container.Config{ - Entrypoint: strslice.StrSlice(utils.CopySlice(c.Entrypoint)), - Hostname: c.Hostname, - Domainname: c.DomainName, - User: c.User, - Env: utils.CopySlice(c.Environment), - Cmd: strslice.StrSlice(utils.CopySlice(c.Command)), - Image: c.Image, - Labels: utils.CopyMap(c.Labels), - ExposedPorts: exposedPorts, - Tty: c.Tty, - OpenStdin: c.StdinOpen, - WorkingDir: c.WorkingDir, - Volumes: toMap(Filter(vols, isVolume)), - MacAddress: c.MacAddress, - StopSignal: c.StopSignal, - StopTimeout: utils.DurationStrToSecondsInt(c.StopGracePeriod), - } - - ulimits := []*units.Ulimit{} - if c.Ulimits.Elements != nil { - for _, ulimit := range c.Ulimits.Elements { - ulimits = append(ulimits, &units.Ulimit{ - Name: ulimit.Name, - Soft: ulimit.Soft, - Hard: ulimit.Hard, - }) - } - } - - memorySwappiness := int64(c.MemSwappiness) - - resources := container.Resources{ - CgroupParent: c.CgroupParent, - Memory: int64(c.MemLimit), - MemoryReservation: int64(c.MemReservation), - MemorySwap: int64(c.MemSwapLimit), - MemorySwappiness: &memorySwappiness, - CPUShares: int64(c.CPUShares), - CPUQuota: int64(c.CPUQuota), - CpusetCpus: c.CPUSet, - Ulimits: ulimits, - Devices: deviceMappings, - OomKillDisable: &c.OomKillDisable, - } - - networkMode := c.NetworkMode - if c.NetworkMode == "" { - if c.Networks != nil && len(c.Networks.Networks) > 0 { - networkMode = c.Networks.Networks[0].RealName - } - } else { - switch { - case strings.HasPrefix(c.NetworkMode, "service:"): - serviceName := c.NetworkMode[8:] - if serviceConfig, ok := ctx.Project.ServiceConfigs.Get(serviceName); ok { - // FIXME(vdemeester) this is actually not right, should be fixed but not there - service, err := ctx.ServiceFactory.Create(ctx.Project, serviceName, serviceConfig) - if err != nil { - return nil, nil, err - } - containers, err := service.Containers(context.Background()) - if err != nil { - return nil, nil, err - } - if len(containers) != 0 { - container := containers[0] - containerID := container.ID() - networkMode = "container:" + containerID - } - // FIXME(vdemeester) log/warn in case of len(containers) == 0 - } - case strings.HasPrefix(c.NetworkMode, "container:"): - containerName := c.NetworkMode[10:] - client := clientFactory.Create(nil) - container, err := composecontainer.Get(context.Background(), client, containerName) - if err != nil { - return nil, nil, err - } - networkMode = "container:" + container.ID - default: - // do nothing :) - } - } - - tmpfs := map[string]string{} - for _, path := range c.Tmpfs { - split := strings.SplitN(path, ":", 2) - if len(split) == 1 { - tmpfs[split[0]] = "" - } else if len(split) == 2 { - tmpfs[split[0]] = split[1] - } - } - - hostConfig := &container.HostConfig{ - VolumesFrom: volumesFrom, - CapAdd: strslice.StrSlice(utils.CopySlice(c.CapAdd)), - CapDrop: strslice.StrSlice(utils.CopySlice(c.CapDrop)), - GroupAdd: c.GroupAdd, - ExtraHosts: utils.CopySlice(c.ExtraHosts), - Privileged: c.Privileged, - Binds: Filter(vols, isBind), - DNS: utils.CopySlice(c.DNS), - DNSOptions: utils.CopySlice(c.DNSOpts), - DNSSearch: utils.CopySlice(c.DNSSearch), - Isolation: container.Isolation(c.Isolation), - LogConfig: container.LogConfig{ - Type: c.Logging.Driver, - Config: utils.CopyMap(c.Logging.Options), - }, - NetworkMode: container.NetworkMode(networkMode), - ReadonlyRootfs: c.ReadOnly, - OomScoreAdj: int(c.OomScoreAdj), - PidMode: container.PidMode(c.Pid), - UTSMode: container.UTSMode(c.Uts), - IpcMode: container.IpcMode(c.Ipc), - PortBindings: portBindings, - RestartPolicy: *restartPolicy, - ShmSize: int64(c.ShmSize), - SecurityOpt: utils.CopySlice(c.SecurityOpt), - Tmpfs: tmpfs, - VolumeDriver: c.VolumeDriver, - Resources: resources, - } - - if config.Labels == nil { - config.Labels = map[string]string{} - } - - return config, hostConfig, nil -} - -func getVolumesFrom(volumesFrom []string, serviceConfigs *config.ServiceConfigs, projectName string) ([]string, error) { - volumes := []string{} - for _, volumeFrom := range volumesFrom { - if serviceConfig, ok := serviceConfigs.Get(volumeFrom); ok { - // It's a service - Use the first one - name := fmt.Sprintf("%s_%s_1", projectName, volumeFrom) - // If a container name is specified, use that instead - if serviceConfig.ContainerName != "" { - name = serviceConfig.ContainerName - } - volumes = append(volumes, name) - } else { - volumes = append(volumes, volumeFrom) - } - } - return volumes, nil -} - -func parseDevices(devices []string) ([]container.DeviceMapping, error) { - // parse device mappings - deviceMappings := []container.DeviceMapping{} - for _, device := range devices { - v, err := parseDevice(device) - if err != nil { - return nil, err - } - deviceMappings = append(deviceMappings, container.DeviceMapping{ - PathOnHost: v.PathOnHost, - PathInContainer: v.PathInContainer, - CgroupPermissions: v.CgroupPermissions, - }) - } - - return deviceMappings, nil -} - -// parseDevice parses a device mapping string to a container.DeviceMapping struct -// FIXME(vdemeester) de-duplicate this by re-exporting it in docker/docker -func parseDevice(device string) (container.DeviceMapping, error) { - src := "" - dst := "" - permissions := "rwm" - arr := strings.Split(device, ":") - 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{}, fmt.Errorf("invalid device specification: %s", device) - } - - if dst == "" { - dst = src - } - - deviceMapping := container.DeviceMapping{ - PathOnHost: src, - PathInContainer: dst, - CgroupPermissions: permissions, - } - return deviceMapping, nil -} - -// 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 { - var 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 -} diff --git a/vendor/github.com/docker/libcompose/docker/service/name.go b/vendor/github.com/docker/libcompose/docker/service/name.go deleted file mode 100644 index faa9e3d44..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/name.go +++ /dev/null @@ -1,92 +0,0 @@ -package service - -import ( - "fmt" - "strconv" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/client" - "github.com/docker/libcompose/labels" -) - -const format = "%s_%s_%d" - -// Namer defines method to provide container name. -type Namer interface { - Next() (string, int) -} - -type defaultNamer struct { - project string - service string - oneOff bool - currentNumber int -} - -type singleNamer struct { - name string -} - -// NewSingleNamer returns a namer that only allows a single name. -func NewSingleNamer(name string) Namer { - return &singleNamer{name} -} - -// NewNamer returns a namer that returns names based on the specified project and -// service name and an inner counter, e.g. project_service_1, project_service_2… -func NewNamer(ctx context.Context, client client.ContainerAPIClient, project, service string, oneOff bool) (Namer, error) { - namer := &defaultNamer{ - project: project, - service: service, - oneOff: oneOff, - } - - filter := filters.NewArgs() - filter.Add("label", fmt.Sprintf("%s=%s", labels.PROJECT.Str(), project)) - filter.Add("label", fmt.Sprintf("%s=%s", labels.SERVICE.Str(), service)) - if oneOff { - filter.Add("label", fmt.Sprintf("%s=%s", labels.ONEOFF.Str(), "True")) - } else { - filter.Add("label", fmt.Sprintf("%s=%s", labels.ONEOFF.Str(), "False")) - } - - containers, err := client.ContainerList(ctx, types.ContainerListOptions{ - All: true, - Filters: filter, - }) - if err != nil { - return nil, err - } - - maxNumber := 0 - for _, container := range containers { - number, err := strconv.Atoi(container.Labels[labels.NUMBER.Str()]) - if err != nil { - return nil, err - } - if number > maxNumber { - maxNumber = number - } - } - namer.currentNumber = maxNumber + 1 - - return namer, nil -} - -func (i *defaultNamer) Next() (string, int) { - service := i.service - if i.oneOff { - service = i.service + "_run" - } - name := fmt.Sprintf(format, i.project, service, i.currentNumber) - number := i.currentNumber - i.currentNumber = i.currentNumber + 1 - return name, number -} - -func (s *singleNamer) Next() (string, int) { - return s.name, 1 -} diff --git a/vendor/github.com/docker/libcompose/docker/service/service.go b/vendor/github.com/docker/libcompose/docker/service/service.go deleted file mode 100644 index d33e19296..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/service.go +++ /dev/null @@ -1,763 +0,0 @@ -package service - -import ( - "fmt" - "strings" - "time" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/api/types/network" - "github.com/docker/docker/client" - "github.com/docker/go-connections/nat" - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/docker/auth" - "github.com/docker/libcompose/docker/builder" - composeclient "github.com/docker/libcompose/docker/client" - "github.com/docker/libcompose/docker/container" - "github.com/docker/libcompose/docker/ctx" - "github.com/docker/libcompose/docker/image" - "github.com/docker/libcompose/labels" - "github.com/docker/libcompose/project" - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" - "github.com/docker/libcompose/utils" - "github.com/docker/libcompose/yaml" - "github.com/sirupsen/logrus" -) - -// Service is a project.Service implementations. -type Service struct { - name string - project *project.Project - serviceConfig *config.ServiceConfig - clientFactory composeclient.Factory - authLookup auth.Lookup - - // FIXME(vdemeester) remove this at some point - context *ctx.Context -} - -// NewService creates a service -func NewService(name string, serviceConfig *config.ServiceConfig, context *ctx.Context) *Service { - return &Service{ - name: name, - project: context.Project, - serviceConfig: serviceConfig, - clientFactory: context.ClientFactory, - authLookup: context.AuthLookup, - context: context, - } -} - -// Name returns the service name. -func (s *Service) Name() string { - return s.name -} - -// Config returns the configuration of the service (config.ServiceConfig). -func (s *Service) Config() *config.ServiceConfig { - return s.serviceConfig -} - -// DependentServices returns the dependent services (as an array of ServiceRelationship) of the service. -func (s *Service) DependentServices() []project.ServiceRelationship { - return DefaultDependentServices(s.project, s) -} - -// Create implements Service.Create. It ensures the image exists or build it -// if it can and then create a container. -func (s *Service) Create(ctx context.Context, options options.Create) error { - containers, err := s.collectContainers(ctx) - if err != nil { - return err - } - - if err := s.ensureImageExists(ctx, options.NoBuild, options.ForceBuild); err != nil { - return err - } - - if len(containers) != 0 { - return s.eachContainer(ctx, containers, func(c *container.Container) error { - _, err := s.recreateIfNeeded(ctx, c, options.NoRecreate, options.ForceRecreate) - return err - }) - } - - namer, err := s.namer(ctx, 1) - if err != nil { - return err - } - - _, err = s.createContainer(ctx, namer, "", nil, false) - return err -} - -func (s *Service) namer(ctx context.Context, count int) (Namer, error) { - var namer Namer - var err error - - if s.serviceConfig.ContainerName != "" { - if count > 1 { - logrus.Warnf(`The "%s" service is using the custom container name "%s". Docker requires each container to have a unique name. Remove the custom name to scale the service.`, s.name, s.serviceConfig.ContainerName) - } - namer = NewSingleNamer(s.serviceConfig.ContainerName) - } else { - client := s.clientFactory.Create(s) - namer, err = NewNamer(ctx, client, s.project.Name, s.name, false) - if err != nil { - return nil, err - } - } - return namer, nil -} - -func (s *Service) collectContainers(ctx context.Context) ([]*container.Container, error) { - client := s.clientFactory.Create(s) - containers, err := container.ListByFilter(ctx, client, labels.SERVICE.Eq(s.name), labels.PROJECT.Eq(s.project.Name)) - if err != nil { - return nil, err - } - - result := []*container.Container{} - - for _, cont := range containers { - c, err := container.New(ctx, client, cont.ID) - if err != nil { - return nil, err - } - result = append(result, c) - } - - return result, nil -} - -func (s *Service) ensureImageExists(ctx context.Context, noBuild bool, forceBuild bool) error { - if forceBuild { - return s.build(ctx, options.Build{}) - } - - exists, err := image.Exists(ctx, s.clientFactory.Create(s), s.imageName()) - if err != nil { - return err - } - if exists { - return nil - } - - if s.Config().Build.Context != "" { - if noBuild { - return fmt.Errorf("Service %q needs to be built, but no-build was specified", s.name) - } - return s.build(ctx, options.Build{}) - } - - return s.Pull(ctx) -} - -func (s *Service) imageName() string { - if s.Config().Image != "" { - return s.Config().Image - } - return fmt.Sprintf("%s_%s", s.project.Name, s.Name()) -} - -// Build implements Service.Build. It will try to build the image and returns an error if any. -func (s *Service) Build(ctx context.Context, buildOptions options.Build) error { - return s.build(ctx, buildOptions) -} - -func (s *Service) build(ctx context.Context, buildOptions options.Build) error { - if s.Config().Build.Context == "" { - return fmt.Errorf("Specified service does not have a build section") - } - builder := &builder.DaemonBuilder{ - Client: s.clientFactory.Create(s), - ContextDirectory: s.Config().Build.Context, - Dockerfile: s.Config().Build.Dockerfile, - BuildArgs: s.Config().Build.Args, - AuthConfigs: s.authLookup.All(), - NoCache: buildOptions.NoCache, - ForceRemove: buildOptions.ForceRemove, - Pull: buildOptions.Pull, - LoggerFactory: s.context.LoggerFactory, - } - return builder.Build(ctx, s.imageName()) -} - -func (s *Service) constructContainers(ctx context.Context, count int) ([]*container.Container, error) { - result, err := s.collectContainers(ctx) - if err != nil { - return nil, err - } - - client := s.clientFactory.Create(s) - - var namer Namer - - if s.serviceConfig.ContainerName != "" { - if count > 1 { - logrus.Warnf(`The "%s" service is using the custom container name "%s". Docker requires each container to have a unique name. Remove the custom name to scale the service.`, s.name, s.serviceConfig.ContainerName) - } - namer = NewSingleNamer(s.serviceConfig.ContainerName) - } else { - namer, err = NewNamer(ctx, client, s.project.Name, s.name, false) - if err != nil { - return nil, err - } - } - - for i := len(result); i < count; i++ { - c, err := s.createContainer(ctx, namer, "", nil, false) - if err != nil { - return nil, err - } - - id := c.ID() - logrus.Debugf("Created container %s: %v", id, c.Name()) - - result = append(result, c) - } - - return result, nil -} - -// Up implements Service.Up. It builds the image if needed, creates a container -// and start it. -func (s *Service) Up(ctx context.Context, options options.Up) error { - containers, err := s.collectContainers(ctx) - if err != nil { - return err - } - - var imageName = s.imageName() - if len(containers) == 0 || !options.NoRecreate { - if err = s.ensureImageExists(ctx, options.NoBuild, options.ForceBuild); err != nil { - return err - } - } - - return s.up(ctx, imageName, true, options) -} - -// Run implements Service.Run. It runs a one of command within the service container. -// It always create a new container. -func (s *Service) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) { - err := s.ensureImageExists(ctx, false, false) - if err != nil { - return -1, err - } - - client := s.clientFactory.Create(s) - - namer, err := NewNamer(ctx, client, s.project.Name, s.name, true) - if err != nil { - return -1, err - } - - configOverride := &config.ServiceConfig{Command: commandParts, Tty: !options.DisableTty, StdinOpen: !options.DisableTty} - - c, err := s.createContainer(ctx, namer, "", configOverride, true) - if err != nil { - return -1, err - } - - if err := s.connectContainerToNetworks(ctx, c, true); err != nil { - return -1, err - } - - if options.Detached { - logrus.Infof("%s", c.Name()) - return 0, c.Start(ctx) - } - return c.Run(ctx, configOverride) -} - -// Info implements Service.Info. It returns an project.InfoSet with the containers -// related to this service (can be multiple if using the scale command). -func (s *Service) Info(ctx context.Context) (project.InfoSet, error) { - result := project.InfoSet{} - containers, err := s.collectContainers(ctx) - if err != nil { - return nil, err - } - - for _, c := range containers { - info, err := c.Info(ctx) - if err != nil { - return nil, err - } - result = append(result, info) - } - - return result, nil -} - -// Start implements Service.Start. It tries to start a container without creating it. -func (s *Service) Start(ctx context.Context) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - if err := s.connectContainerToNetworks(ctx, c, false); err != nil { - return err - } - return c.Start(ctx) - }) -} - -func (s *Service) up(ctx context.Context, imageName string, create bool, options options.Up) error { - containers, err := s.collectContainers(ctx) - if err != nil { - return err - } - - logrus.Debugf("Found %d existing containers for service %s", len(containers), s.name) - - if len(containers) == 0 && create { - namer, err := s.namer(ctx, 1) - if err != nil { - return err - } - c, err := s.createContainer(ctx, namer, "", nil, false) - if err != nil { - return err - } - containers = []*container.Container{c} - } - - return s.eachContainer(ctx, containers, func(c *container.Container) error { - var err error - if create { - c, err = s.recreateIfNeeded(ctx, c, options.NoRecreate, options.ForceRecreate) - if err != nil { - return err - } - } - - if err := s.connectContainerToNetworks(ctx, c, false); err != nil { - return err - } - - err = c.Start(ctx) - - if err == nil { - s.project.Notify(events.ContainerStarted, s.name, map[string]string{ - "name": c.Name(), - }) - } - - return err - }) -} - -func (s *Service) connectContainerToNetworks(ctx context.Context, c *container.Container, oneOff bool) error { - connectedNetworks, err := c.Networks() - if err != nil { - return nil - } - if s.serviceConfig.Networks != nil { - for _, network := range s.serviceConfig.Networks.Networks { - existingNetwork, ok := connectedNetworks[network.RealName] - if ok { - // FIXME(vdemeester) implement alias checking (to not disconnect/reconnect for nothing) - aliasPresent := false - for _, alias := range existingNetwork.Aliases { - ID := c.ShortID() - if alias == ID { - aliasPresent = true - } - } - if aliasPresent { - continue - } - if err := s.NetworkDisconnect(ctx, c, network, oneOff); err != nil { - return err - } - } - if err := s.NetworkConnect(ctx, c, network, oneOff); err != nil { - return err - } - } - } - return nil -} - -// NetworkDisconnect disconnects the container from the specified network -func (s *Service) NetworkDisconnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error { - containerID := c.ID() - client := s.clientFactory.Create(s) - return client.NetworkDisconnect(ctx, net.RealName, containerID, true) -} - -// NetworkConnect connects the container to the specified network -// FIXME(vdemeester) will be refactor with Container refactoring -func (s *Service) NetworkConnect(ctx context.Context, c *container.Container, net *yaml.Network, oneOff bool) error { - containerID := c.ID() - client := s.clientFactory.Create(s) - internalLinks, err := s.getLinks() - if err != nil { - return err - } - links := []string{} - // TODO(vdemeester) handle link to self (?) - for k, v := range internalLinks { - links = append(links, strings.Join([]string{v, k}, ":")) - } - for _, v := range s.serviceConfig.ExternalLinks { - links = append(links, v) - } - aliases := []string{} - if !oneOff { - aliases = []string{s.Name()} - } - aliases = append(aliases, net.Aliases...) - if len(net.Aliases) >= 1 { - logrus.Infof("connect") - client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{ - Aliases: aliases, - Links: links, - IPAddress: net.IPv4Address, - IPAMConfig: &network.EndpointIPAMConfig{ - IPv4Address: net.IPv4Address, - IPv6Address: net.IPv6Address, - }, - }) - logrus.Infof("disconnect") - client.NetworkDisconnect(ctx, net.RealName, containerID, true) - } - return client.NetworkConnect(ctx, net.RealName, containerID, &network.EndpointSettings{ - Aliases: aliases, - Links: links, - IPAddress: net.IPv4Address, - IPAMConfig: &network.EndpointIPAMConfig{ - IPv4Address: net.IPv4Address, - IPv6Address: net.IPv6Address, - }, - }) -} - -func (s *Service) recreateIfNeeded(ctx context.Context, c *container.Container, noRecreate, forceRecreate bool) (*container.Container, error) { - if noRecreate { - return c, nil - } - outOfSync, err := s.OutOfSync(ctx, c) - if err != nil { - return c, err - } - - logrus.WithFields(logrus.Fields{ - "outOfSync": outOfSync, - "ForceRecreate": forceRecreate, - "NoRecreate": noRecreate}).Debug("Going to decide if recreate is needed") - - if forceRecreate || outOfSync { - logrus.Infof("Recreating %s", s.name) - newContainer, err := s.recreate(ctx, c) - if err != nil { - return c, err - } - return newContainer, nil - } - - return c, err -} - -func (s *Service) recreate(ctx context.Context, c *container.Container) (*container.Container, error) { - name := c.Name() - id := c.ID() - newName := fmt.Sprintf("%s_%s", name, id[:12]) - logrus.Debugf("Renaming %s => %s", name, newName) - if err := c.Rename(ctx, newName); err != nil { - logrus.Errorf("Failed to rename old container %s", c.Name()) - return nil, err - } - namer := NewSingleNamer(name) - newContainer, err := s.createContainer(ctx, namer, id, nil, false) - if err != nil { - return nil, err - } - newID := newContainer.ID() - logrus.Debugf("Created replacement container %s", newID) - if err := c.Remove(ctx, false); err != nil { - logrus.Errorf("Failed to remove old container %s", c.Name()) - return nil, err - } - logrus.Debugf("Removed old container %s %s", c.Name(), id) - return newContainer, nil -} - -// OutOfSync checks if the container is out of sync with the service definition. -// It looks if the the service hash container label is the same as the computed one. -func (s *Service) OutOfSync(ctx context.Context, c *container.Container) (bool, error) { - if c.ImageConfig() != s.serviceConfig.Image { - logrus.Debugf("Images for %s do not match %s!=%s", c.Name(), c.ImageConfig(), s.serviceConfig.Image) - return true, nil - } - - expectedHash := config.GetServiceHash(s.name, s.Config()) - if c.Hash() != expectedHash { - logrus.Debugf("Hashes for %s do not match %s!=%s", c.Name(), c.Hash(), expectedHash) - return true, nil - } - - image, err := image.InspectImage(ctx, s.clientFactory.Create(s), c.ImageConfig()) - if err != nil { - if client.IsErrNotFound(err) { - logrus.Debugf("Image %s do not exist, do not know if it's out of sync", c.Image()) - return false, nil - } - return false, err - } - - logrus.Debugf("Checking existing image name vs id: %s == %s", image.ID, c.Image()) - return image.ID != c.Image(), err -} - -func (s *Service) collectContainersAndDo(ctx context.Context, action func(*container.Container) error) error { - containers, err := s.collectContainers(ctx) - if err != nil { - return err - } - return s.eachContainer(ctx, containers, action) -} - -func (s *Service) eachContainer(ctx context.Context, containers []*container.Container, action func(*container.Container) error) error { - - tasks := utils.InParallel{} - for _, cont := range containers { - task := func(cont *container.Container) func() error { - return func() error { - return action(cont) - } - }(cont) - - tasks.Add(task) - } - - return tasks.Wait() -} - -// Stop implements Service.Stop. It stops any containers related to the service. -func (s *Service) Stop(ctx context.Context, timeout int) error { - timeout = s.stopTimeout(timeout) - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - return c.Stop(ctx, timeout) - }) -} - -// Restart implements Service.Restart. It restarts any containers related to the service. -func (s *Service) Restart(ctx context.Context, timeout int) error { - timeout = s.stopTimeout(timeout) - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - return c.Restart(ctx, timeout) - }) -} - -// Kill implements Service.Kill. It kills any containers related to the service. -func (s *Service) Kill(ctx context.Context, signal string) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - return c.Kill(ctx, signal) - }) -} - -// Delete implements Service.Delete. It removes any containers related to the service. -func (s *Service) Delete(ctx context.Context, options options.Delete) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - running := c.IsRunning(ctx) - if !running || options.RemoveRunning { - return c.Remove(ctx, options.RemoveVolume) - } - return nil - }) -} - -// Log implements Service.Log. It returns the docker logs for each container related to the service. -func (s *Service) Log(ctx context.Context, follow bool) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - containerNumber, err := c.Number() - if err != nil { - return err - } - name := fmt.Sprintf("%s_%d", s.name, containerNumber) - if s.Config().ContainerName != "" { - name = s.Config().ContainerName - } - l := s.context.LoggerFactory.CreateContainerLogger(name) - return c.Log(ctx, l, follow) - }) -} - -// Scale implements Service.Scale. It creates or removes containers to have the specified number -// of related container to the service to run. -func (s *Service) Scale(ctx context.Context, scale int, timeout int) error { - if s.specificiesHostPort() { - logrus.Warnf("The \"%s\" service specifies a port on the host. If multiple containers for this service are created on a single host, the port will clash.", s.Name()) - } - - containers, err := s.collectContainers(ctx) - if err != nil { - return err - } - if len(containers) > scale { - foundCount := 0 - for _, c := range containers { - foundCount++ - if foundCount > scale { - timeout = s.stopTimeout(timeout) - if err := c.Stop(ctx, timeout); err != nil { - return err - } - // FIXME(vdemeester) remove volume in scale by default ? - if err := c.Remove(ctx, false); err != nil { - return err - } - } - } - } - - if err != nil { - return err - } - - if len(containers) < scale { - err := s.ensureImageExists(ctx, false, false) - if err != nil { - return err - } - - if _, err = s.constructContainers(ctx, scale); err != nil { - return err - } - } - - return s.up(ctx, "", false, options.Up{}) -} - -// Pull implements Service.Pull. It pulls the image of the service and skip the service that -// would need to be built. -func (s *Service) Pull(ctx context.Context) error { - if s.Config().Image == "" { - return nil - } - - return image.PullImage(ctx, s.clientFactory.Create(s), s.name, s.authLookup, s.Config().Image) -} - -// Pause implements Service.Pause. It puts into pause the container(s) related -// to the service. -func (s *Service) Pause(ctx context.Context) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - return c.Pause(ctx) - }) -} - -// Unpause implements Service.Pause. It brings back from pause the container(s) -// related to the service. -func (s *Service) Unpause(ctx context.Context) error { - return s.collectContainersAndDo(ctx, func(c *container.Container) error { - return c.Unpause(ctx) - }) -} - -// RemoveImage implements Service.RemoveImage. It removes images used for the service -// depending on the specified type. -func (s *Service) RemoveImage(ctx context.Context, imageType options.ImageType) error { - switch imageType { - case "local": - if s.Config().Image != "" { - return nil - } - return image.RemoveImage(ctx, s.clientFactory.Create(s), s.imageName()) - case "all": - return image.RemoveImage(ctx, s.clientFactory.Create(s), s.imageName()) - default: - // Don't do a thing, should be validated up-front - return nil - } -} - -var eventAttributes = []string{"image", "name"} - -// Events implements Service.Events. It listen to all real-time events happening -// for the service, and put them into the specified chan. -func (s *Service) Events(ctx context.Context, evts chan events.ContainerEvent) error { - filter := filters.NewArgs() - filter.Add("label", fmt.Sprintf("%s=%s", labels.PROJECT, s.project.Name)) - filter.Add("label", fmt.Sprintf("%s=%s", labels.SERVICE, s.name)) - client := s.clientFactory.Create(s) - eventq, errq := client.Events(ctx, types.EventsOptions{ - Filters: filter, - }) - go func() { - for { - select { - case event := <-eventq: - service := event.Actor.Attributes[labels.SERVICE.Str()] - attributes := map[string]string{} - for _, attr := range eventAttributes { - attributes[attr] = event.Actor.Attributes[attr] - } - e := events.ContainerEvent{ - Service: service, - Event: event.Action, - Type: event.Type, - ID: event.Actor.ID, - Time: time.Unix(event.Time, 0), - Attributes: attributes, - } - evts <- e - } - } - }() - return <-errq -} - -// Containers implements Service.Containers. It returns the list of containers -// that are related to the service. -func (s *Service) Containers(ctx context.Context) ([]project.Container, error) { - result := []project.Container{} - containers, err := s.collectContainers(ctx) - if err != nil { - return nil, err - } - - for _, c := range containers { - result = append(result, c) - } - - return result, nil -} - -func (s *Service) specificiesHostPort() bool { - _, bindings, err := nat.ParsePortSpecs(s.Config().Ports) - - if err != nil { - fmt.Println(err) - } - - for _, portBindings := range bindings { - for _, portBinding := range portBindings { - if portBinding.HostPort != "" { - return true - } - } - } - - return false -} - -//take in timeout flag from cli as parameter -//return timeout if it is set, -//else return stop_grace_period if it is set, -//else return default 10s -func (s *Service) stopTimeout(timeout int) int { - DEFAULTTIMEOUT := 10 - if timeout != 0 { - return timeout - } - configTimeout := utils.DurationStrToSecondsInt(s.Config().StopGracePeriod) - if configTimeout != nil { - return *configTimeout - } - return DEFAULTTIMEOUT -} diff --git a/vendor/github.com/docker/libcompose/docker/service/service_create.go b/vendor/github.com/docker/libcompose/docker/service/service_create.go deleted file mode 100644 index 97a15ef92..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/service_create.go +++ /dev/null @@ -1,201 +0,0 @@ -package service - -import ( - "fmt" - "strconv" - "strings" - - "golang.org/x/net/context" - - "github.com/docker/docker/api/types" - containertypes "github.com/docker/docker/api/types/container" - "github.com/docker/docker/api/types/network" - "github.com/docker/libcompose/config" - composecontainer "github.com/docker/libcompose/docker/container" - "github.com/docker/libcompose/labels" - "github.com/docker/libcompose/project" - "github.com/docker/libcompose/project/events" - util "github.com/docker/libcompose/utils" - "github.com/sirupsen/logrus" -) - -func (s *Service) createContainer(ctx context.Context, namer Namer, oldContainer string, configOverride *config.ServiceConfig, oneOff bool) (*composecontainer.Container, error) { - serviceConfig := s.serviceConfig - if configOverride != nil { - serviceConfig.Command = configOverride.Command - serviceConfig.Tty = configOverride.Tty - serviceConfig.StdinOpen = configOverride.StdinOpen - } - configWrapper, err := ConvertToAPI(serviceConfig, s.context.Context, s.clientFactory) - if err != nil { - return nil, err - } - configWrapper.Config.Image = s.imageName() - - containerName, containerNumber := namer.Next() - - configWrapper.Config.Labels[labels.SERVICE.Str()] = s.name - configWrapper.Config.Labels[labels.PROJECT.Str()] = s.project.Name - configWrapper.Config.Labels[labels.HASH.Str()] = config.GetServiceHash(s.name, serviceConfig) - configWrapper.Config.Labels[labels.ONEOFF.Str()] = strings.Title(strconv.FormatBool(oneOff)) - configWrapper.Config.Labels[labels.NUMBER.Str()] = fmt.Sprintf("%d", containerNumber) - configWrapper.Config.Labels[labels.VERSION.Str()] = project.ComposeVersion - - err = s.populateAdditionalHostConfig(configWrapper.HostConfig) - if err != nil { - return nil, err - } - - // FIXME(vdemeester): oldContainer should be a Container instead of a string - client := s.clientFactory.Create(s) - if oldContainer != "" { - info, err := client.ContainerInspect(ctx, oldContainer) - if err != nil { - return nil, err - } - configWrapper.HostConfig.Binds = util.Merge(configWrapper.HostConfig.Binds, volumeBinds(configWrapper.Config.Volumes, &info)) - } - - networkConfig := configWrapper.NetworkingConfig - if configWrapper.HostConfig.NetworkMode != "" && configWrapper.HostConfig.NetworkMode.IsUserDefined() { - if networkConfig == nil { - networkConfig = &network.NetworkingConfig{ - EndpointsConfig: map[string]*network.EndpointSettings{ - string(configWrapper.HostConfig.NetworkMode): {}, - }, - } - } - for key, value := range networkConfig.EndpointsConfig { - - conf := value - if value.Aliases == nil { - value.Aliases = []string{} - } - value.Aliases = append(value.Aliases, s.name) - networkConfig.EndpointsConfig[key] = conf - } - } - logrus.Debugf("Creating container %s %#v", containerName, configWrapper) - // FIXME(vdemeester): long-term will be container.Create(…) - container, err := composecontainer.Create(ctx, client, containerName, configWrapper.Config, configWrapper.HostConfig, networkConfig) - if err != nil { - return nil, err - } - s.project.Notify(events.ContainerCreated, s.name, map[string]string{ - "name": containerName, - }) - return container, nil -} - -func (s *Service) populateAdditionalHostConfig(hostConfig *containertypes.HostConfig) error { - links, err := s.getLinks() - if err != nil { - return err - } - - for _, link := range s.DependentServices() { - if !s.project.ServiceConfigs.Has(link.Target) { - continue - } - - service, err := s.project.CreateService(link.Target) - if err != nil { - return err - } - - containers, err := service.Containers(context.Background()) - if err != nil { - return err - } - - if link.Type == project.RelTypeIpcNamespace { - hostConfig, err = addIpc(hostConfig, service, containers, s.serviceConfig.Ipc) - } else if link.Type == project.RelTypeNetNamespace { - hostConfig, err = addNetNs(hostConfig, service, containers, s.serviceConfig.NetworkMode) - } - - if err != nil { - return err - } - } - - hostConfig.Links = []string{} - for k, v := range links { - hostConfig.Links = append(hostConfig.Links, strings.Join([]string{v, k}, ":")) - } - for _, v := range s.serviceConfig.ExternalLinks { - hostConfig.Links = append(hostConfig.Links, v) - } - - return nil -} - -// FIXME(vdemeester) this is temporary -func (s *Service) getLinks() (map[string]string, error) { - links := map[string]string{} - for _, link := range s.DependentServices() { - if !s.project.ServiceConfigs.Has(link.Target) { - continue - } - - service, err := s.project.CreateService(link.Target) - if err != nil { - return nil, err - } - - // FIXME(vdemeester) container should not know service - containers, err := service.Containers(context.Background()) - if err != nil { - return nil, err - } - - if link.Type == project.RelTypeLink { - addLinks(links, service, link, containers) - } - - if err != nil { - return nil, err - } - } - return links, nil -} - -func addLinks(links map[string]string, service project.Service, rel project.ServiceRelationship, containers []project.Container) { - for _, container := range containers { - if _, ok := links[rel.Alias]; !ok { - links[rel.Alias] = container.Name() - } - - links[container.Name()] = container.Name() - } -} - -func addIpc(config *containertypes.HostConfig, service project.Service, containers []project.Container, ipc string) (*containertypes.HostConfig, error) { - if len(containers) == 0 { - return nil, fmt.Errorf("Failed to find container for IPC %v", ipc) - } - - id := containers[0].ID() - config.IpcMode = containertypes.IpcMode("container:" + id) - return config, nil -} - -func addNetNs(config *containertypes.HostConfig, service project.Service, containers []project.Container, networkMode string) (*containertypes.HostConfig, error) { - if len(containers) == 0 { - return nil, fmt.Errorf("Failed to find container for networks ns %v", networkMode) - } - - id := containers[0].ID() - config.NetworkMode = containertypes.NetworkMode("container:" + id) - return config, nil -} - -func volumeBinds(volumes map[string]struct{}, container *types.ContainerJSON) []string { - result := make([]string, 0, len(container.Mounts)) - for _, mount := range container.Mounts { - if _, ok := volumes[mount.Destination]; ok { - result = append(result, fmt.Sprint(mount.Source, ":", mount.Destination)) - } - } - return result -} diff --git a/vendor/github.com/docker/libcompose/docker/service/service_factory.go b/vendor/github.com/docker/libcompose/docker/service/service_factory.go deleted file mode 100644 index 2fcaafab1..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/service_factory.go +++ /dev/null @@ -1,24 +0,0 @@ -package service - -import ( - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/docker/ctx" - "github.com/docker/libcompose/project" -) - -// Factory is an implementation of project.ServiceFactory. -type Factory struct { - context *ctx.Context -} - -// NewFactory creates a new service factory for the given context -func NewFactory(context *ctx.Context) *Factory { - return &Factory{ - context: context, - } -} - -// Create creates a Service based on the specified project, name and service configuration. -func (s *Factory) Create(project *project.Project, name string, serviceConfig *config.ServiceConfig) (project.Service, error) { - return NewService(name, serviceConfig, s.context), nil -} diff --git a/vendor/github.com/docker/libcompose/docker/service/utils.go b/vendor/github.com/docker/libcompose/docker/service/utils.go deleted file mode 100644 index 5b28c887f..000000000 --- a/vendor/github.com/docker/libcompose/docker/service/utils.go +++ /dev/null @@ -1,45 +0,0 @@ -package service - -import ( - "github.com/docker/docker/api/types/container" - "github.com/docker/libcompose/project" -) - -// DefaultDependentServices return the dependent services (as an array of ServiceRelationship) -// for the specified project and service. It looks for : links, volumesFrom, net and ipc configuration. -// It uses default project implementation and append some docker specific ones. -func DefaultDependentServices(p *project.Project, s project.Service) []project.ServiceRelationship { - result := project.DefaultDependentServices(p, s) - - result = appendNs(p, result, s.Config().NetworkMode, project.RelTypeNetNamespace) - result = appendNs(p, result, s.Config().Ipc, project.RelTypeIpcNamespace) - - return result -} - -func appendNs(p *project.Project, rels []project.ServiceRelationship, conf string, relType project.ServiceRelationshipType) []project.ServiceRelationship { - service := GetContainerFromIpcLikeConfig(p, conf) - if service != "" { - rels = append(rels, project.NewServiceRelationship(service, relType)) - } - return rels -} - -// GetContainerFromIpcLikeConfig returns name of the service that shares the IPC -// namespace with the specified service. -func GetContainerFromIpcLikeConfig(p *project.Project, conf string) string { - ipc := container.IpcMode(conf) - if !ipc.IsContainer() { - return "" - } - - name := ipc.Container() - if name == "" { - return "" - } - - if p.ServiceConfigs.Has(name) { - return name - } - return "" -} diff --git a/vendor/github.com/docker/libcompose/docker/volume/volume.go b/vendor/github.com/docker/libcompose/docker/volume/volume.go deleted file mode 100644 index fa60e244a..000000000 --- a/vendor/github.com/docker/libcompose/docker/volume/volume.go +++ /dev/null @@ -1,157 +0,0 @@ -package volume - -import ( - "fmt" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/volume" - "github.com/docker/docker/client" - "github.com/docker/libcompose/config" - composeclient "github.com/docker/libcompose/docker/client" - "github.com/docker/libcompose/project" - "golang.org/x/net/context" -) - -// Volume holds attributes and method for a volume definition in compose -type Volume struct { - client client.VolumeAPIClient - projectName string - name string - driver string - driverOptions map[string]string - external bool - // TODO (shouze) missing labels -} - -func (v *Volume) fullName() string { - name := v.projectName + "_" + v.name - if v.external { - name = v.name - } - return name -} - -// Inspect inspect the current volume -func (v *Volume) Inspect(ctx context.Context) (types.Volume, error) { - return v.client.VolumeInspect(ctx, v.fullName()) -} - -// Remove removes the current volume (from docker engine) -func (v *Volume) Remove(ctx context.Context) error { - if v.external { - fmt.Printf("Volume %s is external, skipping", v.fullName()) - return nil - } - fmt.Printf("Removing volume %q\n", v.fullName()) - return v.client.VolumeRemove(ctx, v.fullName(), true) -} - -// EnsureItExists make sure the volume exists and return an error if it does not exists -// and cannot be created. -func (v *Volume) EnsureItExists(ctx context.Context) error { - volumeResource, err := v.Inspect(ctx) - if v.external { - if client.IsErrNotFound(err) { - // FIXME(shouze) introduce some libcompose error type - return fmt.Errorf("Volume %s declared as external, but could not be found. Please create the volume manually using docker volume create %s and try again", v.name, v.name) - } - return err - } - if err != nil && client.IsErrNotFound(err) { - return v.create(ctx) - } - if volumeResource.Driver != v.driver { - return fmt.Errorf("Volume %q needs to be recreated - driver has changed", v.name) - } - return err -} - -func (v *Volume) create(ctx context.Context) error { - fmt.Printf("Creating volume %q with driver %q\n", v.fullName(), v.driver) - _, err := v.client.VolumeCreate(ctx, volume.VolumeCreateBody{ - Name: v.fullName(), - Driver: v.driver, - DriverOpts: v.driverOptions, - // TODO (shouze) missing labels - }) - - return err -} - -// NewVolume creates a new volume from the specified name and config. -func NewVolume(projectName, name string, config *config.VolumeConfig, client client.VolumeAPIClient) *Volume { - vol := &Volume{ - client: client, - projectName: projectName, - name: name, - } - if config != nil { - vol.driver = config.Driver - vol.driverOptions = config.DriverOpts - vol.external = config.External.External - - } - return vol -} - -// Volumes holds a list of volume -type Volumes struct { - volumes []*Volume - volumeEnabled bool -} - -// Initialize make sure volume exists if volume is enabled -func (v *Volumes) Initialize(ctx context.Context) error { - if !v.volumeEnabled { - return nil - } - for _, volume := range v.volumes { - err := volume.EnsureItExists(ctx) - if err != nil { - return err - } - } - return nil -} - -// Remove removes volumes (clean-up) -func (v *Volumes) Remove(ctx context.Context) error { - if !v.volumeEnabled { - return nil - } - for _, volume := range v.volumes { - err := volume.Remove(ctx) - if err != nil { - return err - } - } - return nil -} - -// VolumesFromServices creates a new Volumes struct based on volumes configurations and -// services configuration. If a volume is defined but not used by any service, it will return -// an error along the Volumes. -func VolumesFromServices(cli client.VolumeAPIClient, projectName string, volumeConfigs map[string]*config.VolumeConfig, services *config.ServiceConfigs, volumeEnabled bool) (*Volumes, error) { - var err error - volumes := make([]*Volume, 0, len(volumeConfigs)) - for name, config := range volumeConfigs { - volume := NewVolume(projectName, name, config, cli) - volumes = append(volumes, volume) - } - return &Volumes{ - volumes: volumes, - volumeEnabled: volumeEnabled, - }, err -} - -// DockerFactory implements project.VolumesFactory -type DockerFactory struct { - ClientFactory composeclient.Factory -} - -// Create implements project.VolumesFactory Create method. -// It creates a Volumes (that implements project.Volumes) from specified configurations. -func (f *DockerFactory) Create(projectName string, volumeConfigs map[string]*config.VolumeConfig, serviceConfigs *config.ServiceConfigs, volumeEnabled bool) (project.Volumes, error) { - cli := f.ClientFactory.Create(nil) - return VolumesFromServices(cli, projectName, volumeConfigs, serviceConfigs, volumeEnabled) -} diff --git a/vendor/github.com/docker/libcompose/labels/labels.go b/vendor/github.com/docker/libcompose/labels/labels.go deleted file mode 100644 index c8eefb093..000000000 --- a/vendor/github.com/docker/libcompose/labels/labels.go +++ /dev/null @@ -1,94 +0,0 @@ -package labels - -import ( - "encoding/json" - "fmt" - - "github.com/docker/libcompose/utils" -) - -// Label represents a docker label. -type Label string - -// Libcompose default labels. -const ( - NUMBER = Label("com.docker.compose.container-number") - ONEOFF = Label("com.docker.compose.oneoff") - PROJECT = Label("com.docker.compose.project") - SERVICE = Label("com.docker.compose.service") - HASH = Label("com.docker.compose.config-hash") - VERSION = Label("com.docker.compose.version") -) - -// EqString returns a label json string representation with the specified value. -func (f Label) EqString(value string) string { - return LabelFilterString(string(f), value) -} - -// Eq returns a label map representation with the specified value. -func (f Label) Eq(value string) map[string][]string { - return LabelFilter(string(f), value) -} - -// AndString returns a json list of labels by merging the two specified values (left and right) serialized as string. -func AndString(left, right string) string { - leftMap := map[string][]string{} - rightMap := map[string][]string{} - - // Ignore errors - json.Unmarshal([]byte(left), &leftMap) - json.Unmarshal([]byte(right), &rightMap) - - for k, v := range rightMap { - existing, ok := leftMap[k] - if ok { - leftMap[k] = append(existing, v...) - } else { - leftMap[k] = v - } - } - - result, _ := json.Marshal(leftMap) - - return string(result) -} - -// And returns a map of labels by merging the two specified values (left and right). -func And(left, right map[string][]string) map[string][]string { - result := map[string][]string{} - for k, v := range left { - result[k] = v - } - - for k, v := range right { - existing, ok := result[k] - if ok { - result[k] = append(existing, v...) - } else { - result[k] = v - } - } - - return result -} - -// Str returns the label name. -func (f Label) Str() string { - return string(f) -} - -// LabelFilterString returns a label json string representation of the specifed couple (key,value) -// that is used as filter for docker. -func LabelFilterString(key, value string) string { - return utils.FilterString(map[string][]string{ - "label": {fmt.Sprintf("%s=%s", key, value)}, - }) -} - -// LabelFilter returns a label map representation of the specifed couple (key,value) -// that is used as filter for docker. -func LabelFilter(key, value string) map[string][]string { - return map[string][]string{ - "label": {fmt.Sprintf("%s=%s", key, value)}, - } -} diff --git a/vendor/github.com/docker/libcompose/logger/null.go b/vendor/github.com/docker/libcompose/logger/null.go deleted file mode 100644 index d791bfb0d..000000000 --- a/vendor/github.com/docker/libcompose/logger/null.go +++ /dev/null @@ -1,42 +0,0 @@ -package logger - -import ( - "io" -) - -// NullLogger is a logger.Logger and logger.Factory implementation that does nothing. -type NullLogger struct { -} - -// Out is a no-op function. -func (n *NullLogger) Out(_ []byte) { -} - -// Err is a no-op function. -func (n *NullLogger) Err(_ []byte) { -} - -// CreateContainerLogger allows NullLogger to implement logger.Factory. -func (n *NullLogger) CreateContainerLogger(_ string) Logger { - return &NullLogger{} -} - -// CreateBuildLogger allows NullLogger to implement logger.Factory. -func (n *NullLogger) CreateBuildLogger(_ string) Logger { - return &NullLogger{} -} - -// CreatePullLogger allows NullLogger to implement logger.Factory. -func (n *NullLogger) CreatePullLogger(_ string) Logger { - return &NullLogger{} -} - -// OutWriter returns the base writer -func (n *NullLogger) OutWriter() io.Writer { - return nil -} - -// ErrWriter returns the base writer -func (n *NullLogger) ErrWriter() io.Writer { - return nil -} diff --git a/vendor/github.com/docker/libcompose/logger/raw_logger.go b/vendor/github.com/docker/libcompose/logger/raw_logger.go deleted file mode 100644 index 9aa0a7bc8..000000000 --- a/vendor/github.com/docker/libcompose/logger/raw_logger.go +++ /dev/null @@ -1,48 +0,0 @@ -package logger - -import ( - "fmt" - "io" - "os" -) - -// RawLogger is a logger.Logger and logger.Factory implementation that prints raw data with no formatting. -type RawLogger struct { -} - -// Out is a no-op function. -func (r *RawLogger) Out(message []byte) { - fmt.Print(string(message)) - -} - -// Err is a no-op function. -func (r *RawLogger) Err(message []byte) { - fmt.Fprint(os.Stderr, string(message)) - -} - -// CreateContainerLogger allows RawLogger to implement logger.Factory. -func (r *RawLogger) CreateContainerLogger(_ string) Logger { - return &RawLogger{} -} - -// CreateBuildLogger allows RawLogger to implement logger.Factory. -func (r *RawLogger) CreateBuildLogger(_ string) Logger { - return &RawLogger{} -} - -// CreatePullLogger allows RawLogger to implement logger.Factory. -func (r *RawLogger) CreatePullLogger(_ string) Logger { - return &RawLogger{} -} - -// OutWriter returns the base writer -func (r *RawLogger) OutWriter() io.Writer { - return os.Stdout -} - -// ErrWriter returns the base writer -func (r *RawLogger) ErrWriter() io.Writer { - return os.Stderr -} diff --git a/vendor/github.com/docker/libcompose/logger/types.go b/vendor/github.com/docker/libcompose/logger/types.go deleted file mode 100644 index 7300095aa..000000000 --- a/vendor/github.com/docker/libcompose/logger/types.go +++ /dev/null @@ -1,37 +0,0 @@ -package logger - -import ( - "io" -) - -// Factory defines methods a factory should implement, to create a Logger -// based on the specified container, image or service name. -type Factory interface { - CreateContainerLogger(name string) Logger - CreateBuildLogger(name string) Logger - CreatePullLogger(name string) Logger -} - -// Logger defines methods to implement for being a logger. -type Logger interface { - Out(bytes []byte) - Err(bytes []byte) - OutWriter() io.Writer - ErrWriter() io.Writer -} - -// Wrapper is a wrapper around Logger that implements the Writer interface, -// mainly use by docker/pkg/stdcopy functions. -type Wrapper struct { - Err bool - Logger Logger -} - -func (l *Wrapper) Write(bytes []byte) (int, error) { - if l.Err { - l.Logger.Err(bytes) - } else { - l.Logger.Out(bytes) - } - return len(bytes), nil -} diff --git a/vendor/github.com/docker/libcompose/lookup/composable.go b/vendor/github.com/docker/libcompose/lookup/composable.go deleted file mode 100644 index ff76480b3..000000000 --- a/vendor/github.com/docker/libcompose/lookup/composable.go +++ /dev/null @@ -1,25 +0,0 @@ -package lookup - -import ( - "github.com/docker/libcompose/config" -) - -// ComposableEnvLookup is a structure that implements the project.EnvironmentLookup interface. -// It holds an ordered list of EnvironmentLookup to call to look for the environment value. -type ComposableEnvLookup struct { - Lookups []config.EnvironmentLookup -} - -// Lookup creates a string slice of string containing a "docker-friendly" environment string -// in the form of 'key=value'. It loop through the lookups and returns the latest value if -// more than one lookup return a result. -func (l *ComposableEnvLookup) Lookup(key string, config *config.ServiceConfig) []string { - result := []string{} - for _, lookup := range l.Lookups { - env := lookup.Lookup(key, config) - if len(env) == 1 { - result = env - } - } - return result -} diff --git a/vendor/github.com/docker/libcompose/lookup/envfile.go b/vendor/github.com/docker/libcompose/lookup/envfile.go deleted file mode 100644 index d606d97a4..000000000 --- a/vendor/github.com/docker/libcompose/lookup/envfile.go +++ /dev/null @@ -1,31 +0,0 @@ -package lookup - -import ( - "strings" - - "github.com/docker/cli/opts" - "github.com/docker/libcompose/config" -) - -// EnvfileLookup is a structure that implements the project.EnvironmentLookup interface. -// It holds the path of the file where to lookup environment values. -type EnvfileLookup struct { - Path string -} - -// Lookup creates a string slice of string containing a "docker-friendly" environment string -// in the form of 'key=value'. It gets environment values using a '.env' file in the specified -// path. -func (l *EnvfileLookup) Lookup(key string, config *config.ServiceConfig) []string { - envs, err := opts.ParseEnvFile(l.Path) - if err != nil { - return []string{} - } - for _, env := range envs { - e := strings.Split(env, "=") - if e[0] == key { - return []string{env} - } - } - return []string{} -} diff --git a/vendor/github.com/docker/libcompose/lookup/file.go b/vendor/github.com/docker/libcompose/lookup/file.go deleted file mode 100644 index b2ec2f586..000000000 --- a/vendor/github.com/docker/libcompose/lookup/file.go +++ /dev/null @@ -1,66 +0,0 @@ -package lookup - -import ( - "io/ioutil" - "os" - "path" - "path/filepath" - "strings" - - "github.com/sirupsen/logrus" -) - -// relativePath returns the proper relative path for the given file path. If -// the relativeTo string equals "-", then it means that it's from the stdin, -// and the returned path will be the current working directory. Otherwise, if -// file is really an absolute path, then it will be returned without any -// changes. Otherwise, the returned path will be a combination of relativeTo -// and file. -func relativePath(file, relativeTo string) string { - // stdin: return the current working directory if possible. - if relativeTo == "-" { - if cwd, err := os.Getwd(); err == nil { - return filepath.Join(cwd, file) - } - } - - // If the given file is already an absolute path, just return it. - // Otherwise, the returned path will be relative to the given relativeTo - // path. - if filepath.IsAbs(file) { - return file - } - - abs, err := filepath.Abs(filepath.Join(path.Dir(relativeTo), file)) - if err != nil { - logrus.Errorf("Failed to get absolute directory: %s", err) - return file - } - return abs -} - -// FileResourceLookup is a "bare" structure that implements the project.ResourceLookup interface -type FileResourceLookup struct { -} - -// Lookup returns the content and the actual filename of the file that is "built" using the -// specified file and relativeTo string. file and relativeTo are supposed to be file path. -// If file starts with a slash ('/'), it tries to load it, otherwise it will build a -// filename using the folder part of relativeTo joined with file. -func (f *FileResourceLookup) Lookup(file, relativeTo string) ([]byte, string, error) { - file = relativePath(file, relativeTo) - logrus.Debugf("Reading file %s", file) - bytes, err := ioutil.ReadFile(file) - return bytes, file, err -} - -// ResolvePath returns the path to be used for the given path volume. This -// function already takes care of relative paths. -func (f *FileResourceLookup) ResolvePath(path, relativeTo string) string { - vs := strings.SplitN(path, ":", 2) - if len(vs) != 2 || filepath.IsAbs(vs[0]) { - return path - } - vs[0] = relativePath(vs[0], relativeTo) - return strings.Join(vs, ":") -} diff --git a/vendor/github.com/docker/libcompose/lookup/simple_env.go b/vendor/github.com/docker/libcompose/lookup/simple_env.go deleted file mode 100644 index 40ce12843..000000000 --- a/vendor/github.com/docker/libcompose/lookup/simple_env.go +++ /dev/null @@ -1,24 +0,0 @@ -package lookup - -import ( - "fmt" - "os" - - "github.com/docker/libcompose/config" -) - -// OsEnvLookup is a "bare" structure that implements the project.EnvironmentLookup interface -type OsEnvLookup struct { -} - -// Lookup creates a string slice of string containing a "docker-friendly" environment string -// in the form of 'key=value'. It gets environment values using os.Getenv. -// If the os environment variable does not exists, the slice is empty. serviceName and config -// are not used at all in this implementation. -func (o *OsEnvLookup) Lookup(key string, config *config.ServiceConfig) []string { - ret := os.Getenv(key) - if ret == "" { - return []string{} - } - return []string{fmt.Sprintf("%s=%s", key, ret)} -} diff --git a/vendor/github.com/docker/libcompose/project/container.go b/vendor/github.com/docker/libcompose/project/container.go deleted file mode 100644 index def4dd877..000000000 --- a/vendor/github.com/docker/libcompose/project/container.go +++ /dev/null @@ -1,13 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" -) - -// Container defines what a libcompose container provides. -type Container interface { - ID() string - Name() string - Port(ctx context.Context, port string) (string, error) - IsRunning(ctx context.Context) bool -} diff --git a/vendor/github.com/docker/libcompose/project/context.go b/vendor/github.com/docker/libcompose/project/context.go deleted file mode 100644 index dbf6be68d..000000000 --- a/vendor/github.com/docker/libcompose/project/context.go +++ /dev/null @@ -1,141 +0,0 @@ -package project - -import ( - "fmt" - "io/ioutil" - "os" - "path" - "path/filepath" - "regexp" - "strings" - - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/logger" - "github.com/sirupsen/logrus" -) - -var projectRegexp = regexp.MustCompile("[^a-zA-Z0-9_.-]") - -// Context holds context meta information about a libcompose project, like -// the project name, the compose file, etc. -type Context struct { - ComposeFiles []string - ComposeBytes [][]byte - ProjectName string - isOpen bool - ServiceFactory ServiceFactory - NetworksFactory NetworksFactory - VolumesFactory VolumesFactory - EnvironmentLookup config.EnvironmentLookup - ResourceLookup config.ResourceLookup - LoggerFactory logger.Factory - IgnoreMissingConfig bool - Project *Project -} - -func (c *Context) readComposeFiles() error { - if c.ComposeBytes != nil { - return nil - } - - logrus.Debugf("Opening compose files: %s", strings.Join(c.ComposeFiles, ",")) - - // Handle STDIN (`-f -`) - if len(c.ComposeFiles) == 1 && c.ComposeFiles[0] == "-" { - composeBytes, err := ioutil.ReadAll(os.Stdin) - if err != nil { - logrus.Errorf("Failed to read compose file from stdin: %v", err) - return err - } - c.ComposeBytes = [][]byte{composeBytes} - return nil - } - - for _, composeFile := range c.ComposeFiles { - composeBytes, err := ioutil.ReadFile(composeFile) - if err != nil && !os.IsNotExist(err) { - logrus.Errorf("Failed to open the compose file: %s", composeFile) - return err - } - if err != nil && !c.IgnoreMissingConfig { - logrus.Errorf("Failed to find the compose file: %s", composeFile) - return err - } - c.ComposeBytes = append(c.ComposeBytes, composeBytes) - } - - return nil -} - -func (c *Context) determineProject() error { - name, err := c.lookupProjectName() - if err != nil { - return err - } - - c.ProjectName = normalizeName(name) - - if c.ProjectName == "" { - return fmt.Errorf("Falied to determine project name") - } - - return nil -} - -func (c *Context) lookupProjectName() (string, error) { - if c.ProjectName != "" { - return c.ProjectName, nil - } - - if envProject := os.Getenv("COMPOSE_PROJECT_NAME"); envProject != "" { - return envProject, nil - } - - file := "." - if len(c.ComposeFiles) > 0 { - file = c.ComposeFiles[0] - } - - f, err := filepath.Abs(file) - if err != nil { - logrus.Errorf("Failed to get absolute directory for: %s", file) - return "", err - } - - f = toUnixPath(f) - - parent := path.Base(path.Dir(f)) - if parent != "" && parent != "." { - return parent, nil - } else if wd, err := os.Getwd(); err != nil { - return "", err - } else { - return path.Base(toUnixPath(wd)), nil - } -} - -func normalizeName(name string) string { - r := regexp.MustCompile("[^a-z0-9]+") - return r.ReplaceAllString(strings.ToLower(name), "") -} - -func toUnixPath(p string) string { - return strings.Replace(p, "\\", "/", -1) -} - -func (c *Context) open() error { - if c.isOpen { - return nil - } - - if err := c.readComposeFiles(); err != nil { - return err - } - - if err := c.determineProject(); err != nil { - return err - } - - c.isOpen = true - return nil -} diff --git a/vendor/github.com/docker/libcompose/project/empty.go b/vendor/github.com/docker/libcompose/project/empty.go deleted file mode 100644 index 4b31b1dfe..000000000 --- a/vendor/github.com/docker/libcompose/project/empty.go +++ /dev/null @@ -1,139 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// this ensures EmptyService implements Service -// useful since it's easy to forget adding new functions to EmptyService -var _ Service = (*EmptyService)(nil) - -// EmptyService is a struct that implements Service but does nothing. -type EmptyService struct { -} - -// Create implements Service.Create but does nothing. -func (e *EmptyService) Create(ctx context.Context, options options.Create) error { - return nil -} - -// Build implements Service.Build but does nothing. -func (e *EmptyService) Build(ctx context.Context, buildOptions options.Build) error { - return nil -} - -// Up implements Service.Up but does nothing. -func (e *EmptyService) Up(ctx context.Context, options options.Up) error { - return nil -} - -// Start implements Service.Start but does nothing. -func (e *EmptyService) Start(ctx context.Context) error { - return nil -} - -// Stop implements Service.Stop() but does nothing. -func (e *EmptyService) Stop(ctx context.Context, timeout int) error { - return nil -} - -// Delete implements Service.Delete but does nothing. -func (e *EmptyService) Delete(ctx context.Context, options options.Delete) error { - return nil -} - -// Restart implements Service.Restart but does nothing. -func (e *EmptyService) Restart(ctx context.Context, timeout int) error { - return nil -} - -// Log implements Service.Log but does nothing. -func (e *EmptyService) Log(ctx context.Context, follow bool) error { - return nil -} - -// Pull implements Service.Pull but does nothing. -func (e *EmptyService) Pull(ctx context.Context) error { - return nil -} - -// Kill implements Service.Kill but does nothing. -func (e *EmptyService) Kill(ctx context.Context, signal string) error { - return nil -} - -// Containers implements Service.Containers but does nothing. -func (e *EmptyService) Containers(ctx context.Context) ([]Container, error) { - return []Container{}, nil -} - -// Scale implements Service.Scale but does nothing. -func (e *EmptyService) Scale(ctx context.Context, count int, timeout int) error { - return nil -} - -// Info implements Service.Info but does nothing. -func (e *EmptyService) Info(ctx context.Context) (InfoSet, error) { - return InfoSet{}, nil -} - -// Pause implements Service.Pause but does nothing. -func (e *EmptyService) Pause(ctx context.Context) error { - return nil -} - -// Unpause implements Service.Pause but does nothing. -func (e *EmptyService) Unpause(ctx context.Context) error { - return nil -} - -// Run implements Service.Run but does nothing. -func (e *EmptyService) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) { - return 0, nil -} - -// RemoveImage implements Service.RemoveImage but does nothing. -func (e *EmptyService) RemoveImage(ctx context.Context, imageType options.ImageType) error { - return nil -} - -// Events implements Service.Events but does nothing. -func (e *EmptyService) Events(ctx context.Context, events chan events.ContainerEvent) error { - return nil -} - -// DependentServices implements Service.DependentServices with empty slice. -func (e *EmptyService) DependentServices() []ServiceRelationship { - return []ServiceRelationship{} -} - -// Config implements Service.Config with empty config. -func (e *EmptyService) Config() *config.ServiceConfig { - return &config.ServiceConfig{} -} - -// Name implements Service.Name with empty name. -func (e *EmptyService) Name() string { - return "" -} - -// this ensures EmptyNetworks implements Networks -var _ Networks = (*EmptyNetworks)(nil) - -// EmptyNetworks is a struct that implements Networks but does nothing. -type EmptyNetworks struct { -} - -// Initialize implements Networks.Initialize but does nothing. -func (e *EmptyNetworks) Initialize(ctx context.Context) error { - return nil -} - -// Remove implements Networks.Remove but does nothing. -func (e *EmptyNetworks) Remove(ctx context.Context) error { - return nil -} diff --git a/vendor/github.com/docker/libcompose/project/events/events.go b/vendor/github.com/docker/libcompose/project/events/events.go deleted file mode 100644 index 816a1b04f..000000000 --- a/vendor/github.com/docker/libcompose/project/events/events.go +++ /dev/null @@ -1,224 +0,0 @@ -// Package events holds event structures, methods and functions. -package events - -import ( - "fmt" - "time" -) - -// Notifier defines the methods an event notifier should have. -type Notifier interface { - Notify(eventType EventType, serviceName string, data map[string]string) -} - -// Emitter defines the methods an event emitter should have. -type Emitter interface { - AddListener(c chan<- Event) -} - -// Event holds project-wide event informations. -type Event struct { - EventType EventType - ServiceName string - Data map[string]string -} - -// ContainerEvent holds attributes of container events. -type ContainerEvent struct { - Service string `json:"service"` - Event string `json:"event"` - ID string `json:"id"` - Time time.Time `json:"time"` - Attributes map[string]string `json:"attributes"` - Type string `json:"type"` -} - -// EventType defines a type of libcompose event. -type EventType int - -// Definitions of libcompose events -const ( - NoEvent = EventType(iota) - - ContainerCreated = EventType(iota) - ContainerStarted = EventType(iota) - - ServiceAdd = EventType(iota) - ServiceUpStart = EventType(iota) - ServiceUpIgnored = EventType(iota) - ServiceUp = EventType(iota) - ServiceCreateStart = EventType(iota) - ServiceCreate = EventType(iota) - ServiceDeleteStart = EventType(iota) - ServiceDelete = EventType(iota) - ServiceDownStart = EventType(iota) - ServiceDown = EventType(iota) - ServiceRestartStart = EventType(iota) - ServiceRestart = EventType(iota) - ServicePullStart = EventType(iota) - ServicePull = EventType(iota) - ServiceKillStart = EventType(iota) - ServiceKill = EventType(iota) - ServiceStartStart = EventType(iota) - ServiceStart = EventType(iota) - ServiceBuildStart = EventType(iota) - ServiceBuild = EventType(iota) - ServicePauseStart = EventType(iota) - ServicePause = EventType(iota) - ServiceUnpauseStart = EventType(iota) - ServiceUnpause = EventType(iota) - ServiceStopStart = EventType(iota) - ServiceStop = EventType(iota) - ServiceRunStart = EventType(iota) - ServiceRun = EventType(iota) - - VolumeAdd = EventType(iota) - NetworkAdd = EventType(iota) - - ProjectDownStart = EventType(iota) - ProjectDownDone = EventType(iota) - ProjectCreateStart = EventType(iota) - ProjectCreateDone = EventType(iota) - ProjectUpStart = EventType(iota) - ProjectUpDone = EventType(iota) - ProjectDeleteStart = EventType(iota) - ProjectDeleteDone = EventType(iota) - ProjectRestartStart = EventType(iota) - ProjectRestartDone = EventType(iota) - ProjectReload = EventType(iota) - ProjectReloadTrigger = EventType(iota) - ProjectKillStart = EventType(iota) - ProjectKillDone = EventType(iota) - ProjectStartStart = EventType(iota) - ProjectStartDone = EventType(iota) - ProjectBuildStart = EventType(iota) - ProjectBuildDone = EventType(iota) - ProjectPauseStart = EventType(iota) - ProjectPauseDone = EventType(iota) - ProjectUnpauseStart = EventType(iota) - ProjectUnpauseDone = EventType(iota) - ProjectStopStart = EventType(iota) - ProjectStopDone = EventType(iota) -) - -func (e EventType) String() string { - var m string - switch e { - case ContainerCreated: - m = "Created container" - case ContainerStarted: - m = "Started container" - - case ServiceAdd: - m = "Adding" - case ServiceUpStart: - m = "Starting" - case ServiceUpIgnored: - m = "Ignoring" - case ServiceUp: - m = "Started" - case ServiceCreateStart: - m = "Creating" - case ServiceCreate: - m = "Created" - case ServiceDeleteStart: - m = "Deleting" - case ServiceDelete: - m = "Deleted" - case ServiceStopStart: - m = "Stopping" - case ServiceStop: - m = "Stopped" - case ServiceDownStart: - m = "Stopping" - case ServiceDown: - m = "Stopped" - case ServiceRestartStart: - m = "Restarting" - case ServiceRestart: - m = "Restarted" - case ServicePullStart: - m = "Pulling" - case ServicePull: - m = "Pulled" - case ServiceKillStart: - m = "Killing" - case ServiceKill: - m = "Killed" - case ServiceStartStart: - m = "Starting" - case ServiceStart: - m = "Started" - case ServiceBuildStart: - m = "Building" - case ServiceBuild: - m = "Built" - case ServiceRunStart: - m = "Executing" - case ServiceRun: - m = "Executed" - case ServicePauseStart: - m = "Pausing" - case ServicePause: - m = "Paused" - case ServiceUnpauseStart: - m = "Unpausing" - case ServiceUnpause: - m = "Unpaused" - - case ProjectDownStart: - m = "Stopping project" - case ProjectDownDone: - m = "Project stopped" - case ProjectStopStart: - m = "Stopping project" - case ProjectStopDone: - m = "Project stopped" - case ProjectCreateStart: - m = "Creating project" - case ProjectCreateDone: - m = "Project created" - case ProjectUpStart: - m = "Starting project" - case ProjectUpDone: - m = "Project started" - case ProjectDeleteStart: - m = "Deleting project" - case ProjectDeleteDone: - m = "Project deleted" - case ProjectRestartStart: - m = "Restarting project" - case ProjectRestartDone: - m = "Project restarted" - case ProjectReload: - m = "Reloading project" - case ProjectReloadTrigger: - m = "Triggering project reload" - case ProjectKillStart: - m = "Killing project" - case ProjectKillDone: - m = "Project killed" - case ProjectStartStart: - m = "Starting project" - case ProjectStartDone: - m = "Project started" - case ProjectBuildStart: - m = "Building project" - case ProjectBuildDone: - m = "Project built" - case ProjectPauseStart: - m = "Pausing project" - case ProjectPauseDone: - m = "Project paused" - case ProjectUnpauseStart: - m = "Unpausing project" - case ProjectUnpauseDone: - m = "Project unpaused" - } - - if m == "" { - m = fmt.Sprintf("EventType: %d", int(e)) - } - - return m -} diff --git a/vendor/github.com/docker/libcompose/project/info.go b/vendor/github.com/docker/libcompose/project/info.go deleted file mode 100644 index c12b04c7d..000000000 --- a/vendor/github.com/docker/libcompose/project/info.go +++ /dev/null @@ -1,48 +0,0 @@ -package project - -import ( - "bytes" - "io" - "text/tabwriter" -) - -// InfoSet holds a list of Info. -type InfoSet []Info - -// Info holds a list of InfoPart. -type Info map[string]string - -func (infos InfoSet) String(columns []string, titleFlag bool) string { - //no error checking, none of this should fail - buffer := bytes.NewBuffer(make([]byte, 0, 1024)) - tabwriter := tabwriter.NewWriter(buffer, 4, 4, 2, ' ', 0) - - first := true - for _, info := range infos { - if first && titleFlag { - writeLine(tabwriter, columns, true, info) - } - first = false - writeLine(tabwriter, columns, false, info) - } - - tabwriter.Flush() - return buffer.String() -} - -func writeLine(writer io.Writer, columns []string, key bool, info Info) { - first := true - for _, column := range columns { - if !first { - writer.Write([]byte{'\t'}) - } - first = false - if key { - writer.Write([]byte(column)) - } else { - writer.Write([]byte(info[column])) - } - } - - writer.Write([]byte{'\n'}) -} diff --git a/vendor/github.com/docker/libcompose/project/interface.go b/vendor/github.com/docker/libcompose/project/interface.go deleted file mode 100644 index 3356407c2..000000000 --- a/vendor/github.com/docker/libcompose/project/interface.go +++ /dev/null @@ -1,64 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// APIProject defines the methods a libcompose project should implement. -type APIProject interface { - events.Notifier - events.Emitter - - Build(ctx context.Context, options options.Build, sevice ...string) error - Config() (string, error) - Create(ctx context.Context, options options.Create, services ...string) error - Delete(ctx context.Context, options options.Delete, services ...string) error - Down(ctx context.Context, options options.Down, services ...string) error - Events(ctx context.Context, services ...string) (chan events.ContainerEvent, error) - Kill(ctx context.Context, signal string, services ...string) error - Log(ctx context.Context, follow bool, services ...string) error - Pause(ctx context.Context, services ...string) error - Ps(ctx context.Context, services ...string) (InfoSet, error) - // FIXME(vdemeester) we could use nat.Port instead ? - Port(ctx context.Context, index int, protocol, serviceName, privatePort string) (string, error) - Pull(ctx context.Context, services ...string) error - Restart(ctx context.Context, timeout int, services ...string) error - Run(ctx context.Context, serviceName string, commandParts []string, options options.Run) (int, error) - Scale(ctx context.Context, timeout int, servicesScale map[string]int) error - Start(ctx context.Context, services ...string) error - Stop(ctx context.Context, timeout int, services ...string) error - Unpause(ctx context.Context, services ...string) error - Up(ctx context.Context, options options.Up, services ...string) error - - Parse() error - CreateService(name string) (Service, error) - AddConfig(name string, config *config.ServiceConfig) error - Load(bytes []byte) error - Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) - - GetServiceConfig(service string) (*config.ServiceConfig, bool) -} - -// Filter holds filter element to filter containers -type Filter struct { - State State -} - -// State defines the supported state you can filter on -type State string - -// Definitions of filter states -const ( - AnyState = State("") - Running = State("running") - Stopped = State("stopped") -) - -// RuntimeProject defines runtime-specific methods for a libcompose implementation. -type RuntimeProject interface { - RemoveOrphans(ctx context.Context, projectName string, serviceConfigs *config.ServiceConfigs) error -} diff --git a/vendor/github.com/docker/libcompose/project/listener.go b/vendor/github.com/docker/libcompose/project/listener.go deleted file mode 100644 index 446144c47..000000000 --- a/vendor/github.com/docker/libcompose/project/listener.go +++ /dev/null @@ -1,81 +0,0 @@ -package project - -import ( - "bytes" - - "github.com/docker/libcompose/project/events" - "github.com/sirupsen/logrus" -) - -var ( - infoEvents = map[events.EventType]bool{ - events.ServiceDeleteStart: true, - events.ServiceDelete: true, - events.ServiceDownStart: true, - events.ServiceDown: true, - events.ServiceStopStart: true, - events.ServiceStop: true, - events.ServiceKillStart: true, - events.ServiceKill: true, - events.ServiceCreateStart: true, - events.ServiceCreate: true, - events.ServiceStartStart: true, - events.ServiceStart: true, - events.ServiceRestartStart: true, - events.ServiceRestart: true, - events.ServiceUpStart: true, - events.ServiceUp: true, - events.ServicePauseStart: true, - events.ServicePause: true, - events.ServiceUnpauseStart: true, - events.ServiceUnpause: true, - } -) - -type defaultListener struct { - project *Project - listenChan chan events.Event - upCount int -} - -// NewDefaultListener create a default listener for the specified project. -func NewDefaultListener(p *Project) chan<- events.Event { - l := defaultListener{ - listenChan: make(chan events.Event), - project: p, - } - go l.start() - return l.listenChan -} - -func (d *defaultListener) start() { - for event := range d.listenChan { - buffer := bytes.NewBuffer(nil) - if event.Data != nil { - for k, v := range event.Data { - if buffer.Len() > 0 { - buffer.WriteString(", ") - } - buffer.WriteString(k) - buffer.WriteString("=") - buffer.WriteString(v) - } - } - - if event.EventType == events.ServiceUp { - d.upCount++ - } - - logf := logrus.Debugf - - if infoEvents[event.EventType] { - logf = logrus.Infof - } - - if event.ServiceName == "" { - logf("Project [%s]: %s %s", d.project.Name, event.EventType, buffer.Bytes()) - } else { - logf("[%d/%d] [%s]: %s %s", d.upCount, d.project.ServiceConfigs.Len(), event.ServiceName, event.EventType, buffer.Bytes()) - } - } -} diff --git a/vendor/github.com/docker/libcompose/project/network.go b/vendor/github.com/docker/libcompose/project/network.go deleted file mode 100644 index af0aa5671..000000000 --- a/vendor/github.com/docker/libcompose/project/network.go +++ /dev/null @@ -1,19 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" -) - -// Networks defines the methods a libcompose network aggregate should define. -type Networks interface { - Initialize(ctx context.Context) error - Remove(ctx context.Context) error -} - -// NetworksFactory is an interface factory to create Networks object for the specified -// configurations (service, networks, …) -type NetworksFactory interface { - Create(projectName string, networkConfigs map[string]*config.NetworkConfig, serviceConfigs *config.ServiceConfigs, networkEnabled bool) (Networks, error) -} diff --git a/vendor/github.com/docker/libcompose/project/options/types.go b/vendor/github.com/docker/libcompose/project/options/types.go deleted file mode 100644 index 3d8d54a0b..000000000 --- a/vendor/github.com/docker/libcompose/project/options/types.go +++ /dev/null @@ -1,53 +0,0 @@ -package options - -// Build holds options of compose build. -type Build struct { - NoCache bool - ForceRemove bool - Pull bool -} - -// Delete holds options of compose rm. -type Delete struct { - RemoveVolume bool - RemoveRunning bool -} - -// Down holds options of compose down. -type Down struct { - RemoveVolume bool - RemoveImages ImageType - RemoveOrphans bool -} - -// Create holds options of compose create. -type Create struct { - NoRecreate bool - ForceRecreate bool - NoBuild bool - ForceBuild bool -} - -// Run holds options of compose run. -type Run struct { - Detached bool - DisableTty bool -} - -// Up holds options of compose up. -type Up struct { - Create -} - -// ImageType defines the type of image (local, all) -type ImageType string - -// Valid indicates whether the image type is valid. -func (i ImageType) Valid() bool { - switch string(i) { - case "", "local", "all": - return true - default: - return false - } -} diff --git a/vendor/github.com/docker/libcompose/project/project.go b/vendor/github.com/docker/libcompose/project/project.go deleted file mode 100644 index 5bf2c17e8..000000000 --- a/vendor/github.com/docker/libcompose/project/project.go +++ /dev/null @@ -1,559 +0,0 @@ -package project - -import ( - "errors" - "fmt" - "os" - "path" - "path/filepath" - "strings" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/logger" - "github.com/docker/libcompose/lookup" - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/utils" - "github.com/docker/libcompose/yaml" - log "github.com/sirupsen/logrus" -) - -// ComposeVersion is name of docker-compose.yml file syntax supported version -const ComposeVersion = "1.5.0" - -type wrapperAction func(*serviceWrapper, map[string]*serviceWrapper) -type serviceAction func(service Service) error - -// Project holds libcompose project information. -type Project struct { - Name string - ServiceConfigs *config.ServiceConfigs - VolumeConfigs map[string]*config.VolumeConfig - NetworkConfigs map[string]*config.NetworkConfig - Files []string - ReloadCallback func() error - ParseOptions *config.ParseOptions - - runtime RuntimeProject - networks Networks - volumes Volumes - configVersion string - context *Context - reload []string - upCount int - listeners []chan<- events.Event - hasListeners bool -} - -// NewProject creates a new project with the specified context. -func NewProject(context *Context, runtime RuntimeProject, parseOptions *config.ParseOptions) *Project { - p := &Project{ - context: context, - runtime: runtime, - ParseOptions: parseOptions, - ServiceConfigs: config.NewServiceConfigs(), - VolumeConfigs: make(map[string]*config.VolumeConfig), - NetworkConfigs: make(map[string]*config.NetworkConfig), - } - - if context.LoggerFactory == nil { - context.LoggerFactory = &logger.NullLogger{} - } - - if context.ResourceLookup == nil { - context.ResourceLookup = &lookup.FileResourceLookup{} - } - - if context.EnvironmentLookup == nil { - var envPath, absPath, cwd string - var err error - if len(context.ComposeFiles) > 0 { - absPath, err = filepath.Abs(context.ComposeFiles[0]) - dir, _ := path.Split(absPath) - envPath = filepath.Join(dir, ".env") - } else { - cwd, err = os.Getwd() - envPath = filepath.Join(cwd, ".env") - } - - if err != nil { - log.Errorf("Could not get the rooted path name to the current directory: %v", err) - return nil - } - context.EnvironmentLookup = &lookup.ComposableEnvLookup{ - Lookups: []config.EnvironmentLookup{ - &lookup.EnvfileLookup{ - Path: envPath, - }, - &lookup.OsEnvLookup{}, - }, - } - } - - context.Project = p - - p.listeners = []chan<- events.Event{NewDefaultListener(p)} - - return p -} - -// Parse populates project information based on its context. It sets up the name, -// the composefile and the composebytes (the composefile content). -func (p *Project) Parse() error { - err := p.context.open() - if err != nil { - return err - } - - p.Name = p.context.ProjectName - - p.Files = p.context.ComposeFiles - - if len(p.Files) == 1 && p.Files[0] == "-" { - p.Files = []string{"."} - } - - if p.context.ComposeBytes != nil { - for i, composeBytes := range p.context.ComposeBytes { - file := "" - if i < len(p.context.ComposeFiles) { - file = p.Files[i] - } - if err := p.load(file, composeBytes); err != nil { - return err - } - } - } - - return nil -} - -// CreateService creates a service with the specified name based. If there -// is no config in the project for this service, it will return an error. -func (p *Project) CreateService(name string) (Service, error) { - existing, ok := p.GetServiceConfig(name) - if !ok { - return nil, fmt.Errorf("Failed to find service: %s", name) - } - - // Copy because we are about to modify the environment - config := *existing - - if p.context.EnvironmentLookup != nil { - parsedEnv := make([]string, 0, len(config.Environment)) - - for _, env := range config.Environment { - parts := strings.SplitN(env, "=", 2) - if len(parts) > 1 { - parsedEnv = append(parsedEnv, env) - continue - } else { - env = parts[0] - } - - for _, value := range p.context.EnvironmentLookup.Lookup(env, &config) { - parsedEnv = append(parsedEnv, value) - } - } - - config.Environment = parsedEnv - - // check the environment for extra build Args that are set but not given a value in the compose file - for arg, value := range config.Build.Args { - if *value == "\x00" { - envValue := p.context.EnvironmentLookup.Lookup(arg, &config) - // depending on what we get back we do different things - switch l := len(envValue); l { - case 0: - delete(config.Build.Args, arg) - case 1: - parts := strings.SplitN(envValue[0], "=", 2) - config.Build.Args[parts[0]] = &parts[1] - default: - return nil, fmt.Errorf("tried to set Build Arg %#v to multi-value %#v", arg, envValue) - } - } - } - } - - return p.context.ServiceFactory.Create(p, name, &config) -} - -// AddConfig adds the specified service config for the specified name. -func (p *Project) AddConfig(name string, config *config.ServiceConfig) error { - p.Notify(events.ServiceAdd, name, nil) - - p.ServiceConfigs.Add(name, config) - p.reload = append(p.reload, name) - - return nil -} - -// AddVolumeConfig adds the specified volume config for the specified name. -func (p *Project) AddVolumeConfig(name string, config *config.VolumeConfig) error { - p.Notify(events.VolumeAdd, name, nil) - p.VolumeConfigs[name] = config - return nil -} - -// AddNetworkConfig adds the specified network config for the specified name. -func (p *Project) AddNetworkConfig(name string, config *config.NetworkConfig) error { - p.Notify(events.NetworkAdd, name, nil) - p.NetworkConfigs[name] = config - return nil -} - -// Load loads the specified byte array (the composefile content) and adds the -// service configuration to the project. -// FIXME is it needed ? -func (p *Project) Load(bytes []byte) error { - return p.load("", bytes) -} - -func (p *Project) load(file string, bytes []byte) error { - version, serviceConfigs, volumeConfigs, networkConfigs, err := config.Merge(p.ServiceConfigs, p.context.EnvironmentLookup, p.context.ResourceLookup, file, bytes, p.ParseOptions) - if err != nil { - log.Errorf("Could not parse config for project %s : %v", p.Name, err) - return err - } - - p.configVersion = version - - for name, config := range volumeConfigs { - err := p.AddVolumeConfig(name, config) - if err != nil { - return err - } - } - - for name, config := range networkConfigs { - err := p.AddNetworkConfig(name, config) - if err != nil { - return err - } - } - - for name, config := range serviceConfigs { - err := p.AddConfig(name, config) - if err != nil { - return err - } - } - - // Update network configuration a little bit - p.handleNetworkConfig() - p.handleVolumeConfig() - - if p.context.NetworksFactory != nil { - networks, err := p.context.NetworksFactory.Create(p.Name, p.NetworkConfigs, p.ServiceConfigs, p.isNetworkEnabled()) - if err != nil { - return err - } - - p.networks = networks - } - - if p.context.VolumesFactory != nil { - volumes, err := p.context.VolumesFactory.Create(p.Name, p.VolumeConfigs, p.ServiceConfigs, p.isVolumeEnabled()) - if err != nil { - return err - } - - p.volumes = volumes - } - - return nil -} - -func (p *Project) handleNetworkConfig() { - if p.isNetworkEnabled() { - for _, serviceName := range p.ServiceConfigs.Keys() { - serviceConfig, _ := p.ServiceConfigs.Get(serviceName) - if serviceConfig.NetworkMode != "" { - continue - } - if serviceConfig.Networks == nil || len(serviceConfig.Networks.Networks) == 0 { - // Add default as network - serviceConfig.Networks = &yaml.Networks{ - Networks: []*yaml.Network{ - { - Name: "default", - RealName: fmt.Sprintf("%s_%s", p.Name, "default"), - }, - }, - } - p.AddNetworkConfig("default", &config.NetworkConfig{}) - } - // Consolidate the name of the network - // FIXME(vdemeester) probably shouldn't be there, maybe move that to interface/factory - for _, network := range serviceConfig.Networks.Networks { - net, ok := p.NetworkConfigs[network.Name] - if ok && net != nil { - if net.External.External { - network.RealName = network.Name - if net.External.Name != "" { - network.RealName = net.External.Name - } - } else { - network.RealName = p.Name + "_" + network.Name - } - } else { - network.RealName = p.Name + "_" + network.Name - - p.NetworkConfigs[network.Name] = &config.NetworkConfig{ - External: yaml.External{External: false}, - } - } - // Ignoring if we don't find the network, it will be catched later - } - } - } -} - -func (p *Project) isNetworkEnabled() bool { - return p.configVersion == "2" -} - -func (p *Project) handleVolumeConfig() { - if p.isVolumeEnabled() { - for _, serviceName := range p.ServiceConfigs.Keys() { - serviceConfig, _ := p.ServiceConfigs.Get(serviceName) - // Consolidate the name of the volume - // FIXME(vdemeester) probably shouldn't be there, maybe move that to interface/factory - if serviceConfig.Volumes == nil { - continue - } - for _, volume := range serviceConfig.Volumes.Volumes { - if !IsNamedVolume(volume.Source) { - continue - } - - vol, ok := p.VolumeConfigs[volume.Source] - if !ok || vol == nil { - continue - } - - if vol.External.External { - if vol.External.Name != "" { - volume.Source = vol.External.Name - } - } else { - volume.Source = p.Name + "_" + volume.Source - } - } - } - } -} - -func (p *Project) isVolumeEnabled() bool { - return p.configVersion == "2" -} - -// initialize sets up required element for project before any action (on project and service). -// This means it's not needed to be called on Config for example. -func (p *Project) initialize(ctx context.Context) error { - if p.networks != nil { - if err := p.networks.Initialize(ctx); err != nil { - return err - } - } - if p.volumes != nil { - if err := p.volumes.Initialize(ctx); err != nil { - return err - } - } - return nil -} - -func (p *Project) loadWrappers(wrappers map[string]*serviceWrapper, servicesToConstruct []string) error { - for _, name := range servicesToConstruct { - wrapper, err := newServiceWrapper(name, p) - if err != nil { - return err - } - wrappers[name] = wrapper - } - - return nil -} - -func (p *Project) perform(start, done events.EventType, services []string, action wrapperAction, cycleAction serviceAction) error { - p.Notify(start, "", nil) - - err := p.forEach(services, action, cycleAction) - - p.Notify(done, "", nil) - return err -} - -func isSelected(wrapper *serviceWrapper, selected map[string]bool) bool { - return len(selected) == 0 || selected[wrapper.name] -} - -func (p *Project) forEach(services []string, action wrapperAction, cycleAction serviceAction) error { - selected := make(map[string]bool) - wrappers := make(map[string]*serviceWrapper) - - for _, s := range services { - selected[s] = true - } - - return p.traverse(true, selected, wrappers, action, cycleAction) -} - -func (p *Project) startService(wrappers map[string]*serviceWrapper, history []string, selected, launched map[string]bool, wrapper *serviceWrapper, action wrapperAction, cycleAction serviceAction) error { - if launched[wrapper.name] { - return nil - } - - launched[wrapper.name] = true - history = append(history, wrapper.name) - - for _, dep := range wrapper.service.DependentServices() { - target := wrappers[dep.Target] - if target == nil { - log.Debugf("Failed to find %s", dep.Target) - return fmt.Errorf("Service '%s' has a link to service '%s' which is undefined", wrapper.name, dep.Target) - } - - if utils.Contains(history, dep.Target) { - cycle := strings.Join(append(history, dep.Target), "->") - if dep.Optional { - log.Debugf("Ignoring cycle for %s", cycle) - wrapper.IgnoreDep(dep.Target) - if cycleAction != nil { - var err error - log.Debugf("Running cycle action for %s", cycle) - err = cycleAction(target.service) - if err != nil { - return err - } - } - } else { - return fmt.Errorf("Cycle detected in path %s", cycle) - } - - continue - } - - err := p.startService(wrappers, history, selected, launched, target, action, cycleAction) - if err != nil { - return err - } - } - - if isSelected(wrapper, selected) { - log.Debugf("Launching action for %s", wrapper.name) - go action(wrapper, wrappers) - } else { - wrapper.Ignore() - } - - return nil -} - -func (p *Project) traverse(start bool, selected map[string]bool, wrappers map[string]*serviceWrapper, action wrapperAction, cycleAction serviceAction) error { - restart := false - wrapperList := []string{} - - if start { - for _, name := range p.ServiceConfigs.Keys() { - wrapperList = append(wrapperList, name) - } - } else { - for _, wrapper := range wrappers { - if err := wrapper.Reset(); err != nil { - return err - } - } - wrapperList = p.reload - } - - p.loadWrappers(wrappers, wrapperList) - p.reload = []string{} - - // check service name - for s := range selected { - if wrappers[s] == nil { - return errors.New("No such service: " + s) - } - } - - launched := map[string]bool{} - - for _, wrapper := range wrappers { - if err := p.startService(wrappers, []string{}, selected, launched, wrapper, action, cycleAction); err != nil { - return err - } - } - - var firstError error - - for _, wrapper := range wrappers { - if !isSelected(wrapper, selected) { - continue - } - if err := wrapper.Wait(); err == ErrRestart { - restart = true - } else if err != nil { - log.Errorf("Failed to start: %s : %v", wrapper.name, err) - if firstError == nil { - firstError = err - } - } - } - - if restart { - if p.ReloadCallback != nil { - if err := p.ReloadCallback(); err != nil { - log.Errorf("Failed calling callback: %v", err) - } - } - return p.traverse(false, selected, wrappers, action, cycleAction) - } - return firstError -} - -// AddListener adds the specified listener to the project. -// This implements implicitly events.Emitter. -func (p *Project) AddListener(c chan<- events.Event) { - if !p.hasListeners { - for _, l := range p.listeners { - close(l) - } - p.hasListeners = true - p.listeners = []chan<- events.Event{c} - } else { - p.listeners = append(p.listeners, c) - } -} - -// Notify notifies all project listener with the specified eventType, service name and datas. -// This implements implicitly events.Notifier interface. -func (p *Project) Notify(eventType events.EventType, serviceName string, data map[string]string) { - if eventType == events.NoEvent { - return - } - - event := events.Event{ - EventType: eventType, - ServiceName: serviceName, - Data: data, - } - - for _, l := range p.listeners { - l <- event - } -} - -// GetServiceConfig looks up a service config for a given service name, returning the ServiceConfig -// object and a bool flag indicating whether it was found -func (p *Project) GetServiceConfig(name string) (*config.ServiceConfig, bool) { - return p.ServiceConfigs.Get(name) -} - -// IsNamedVolume returns whether the specified volume (string) is a named volume or not. -func IsNamedVolume(volume string) bool { - return !strings.HasPrefix(volume, ".") && !strings.HasPrefix(volume, "/") && !strings.HasPrefix(volume, "~") -} diff --git a/vendor/github.com/docker/libcompose/project/project_build.go b/vendor/github.com/docker/libcompose/project/project_build.go deleted file mode 100644 index 506a5c8fe..000000000 --- a/vendor/github.com/docker/libcompose/project/project_build.go +++ /dev/null @@ -1,17 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Build builds the specified services (like docker build). -func (p *Project) Build(ctx context.Context, buildOptions options.Build, services ...string) error { - return p.perform(events.ProjectBuildStart, events.ProjectBuildDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceBuildStart, events.ServiceBuild, func(service Service) error { - return service.Build(ctx, buildOptions) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_config.go b/vendor/github.com/docker/libcompose/project/project_config.go deleted file mode 100644 index c4ca1a31d..000000000 --- a/vendor/github.com/docker/libcompose/project/project_config.go +++ /dev/null @@ -1,27 +0,0 @@ -package project - -import ( - "github.com/docker/libcompose/config" - "gopkg.in/yaml.v2" -) - -// ExportedConfig holds config attribute that will be exported -type ExportedConfig struct { - Version string `yaml:"version,omitempty"` - Services map[string]*config.ServiceConfig `yaml:"services"` - Volumes map[string]*config.VolumeConfig `yaml:"volumes"` - Networks map[string]*config.NetworkConfig `yaml:"networks"` -} - -// Config validates and print the compose file. -func (p *Project) Config() (string, error) { - cfg := ExportedConfig{ - Version: "2.0", - Services: p.ServiceConfigs.All(), - Volumes: p.VolumeConfigs, - Networks: p.NetworkConfigs, - } - - bytes, err := yaml.Marshal(cfg) - return string(bytes), err -} diff --git a/vendor/github.com/docker/libcompose/project/project_containers.go b/vendor/github.com/docker/libcompose/project/project_containers.go deleted file mode 100644 index a8fed9942..000000000 --- a/vendor/github.com/docker/libcompose/project/project_containers.go +++ /dev/null @@ -1,54 +0,0 @@ -package project - -import ( - "fmt" - "sync" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Containers lists the containers for the specified services. Can be filter using -// the Filter struct. -func (p *Project) Containers(ctx context.Context, filter Filter, services ...string) ([]string, error) { - containers := []string{} - var lock sync.Mutex - - err := p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error { - serviceContainers, innerErr := service.Containers(ctx) - if innerErr != nil { - return innerErr - } - - for _, container := range serviceContainers { - running := container.IsRunning(ctx) - switch filter.State { - case Running: - if !running { - continue - } - case Stopped: - if running { - continue - } - case AnyState: - // Don't do a thing - default: - // Invalid state filter - return fmt.Errorf("Invalid container filter: %s", filter.State) - } - containerID := container.ID() - lock.Lock() - containers = append(containers, containerID) - lock.Unlock() - } - return nil - }) - }), nil) - if err != nil { - return nil, err - } - return containers, nil -} diff --git a/vendor/github.com/docker/libcompose/project/project_create.go b/vendor/github.com/docker/libcompose/project/project_create.go deleted file mode 100644 index 9141b719c..000000000 --- a/vendor/github.com/docker/libcompose/project/project_create.go +++ /dev/null @@ -1,25 +0,0 @@ -package project - -import ( - "fmt" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Create creates the specified services (like docker create). -func (p *Project) Create(ctx context.Context, options options.Create, services ...string) error { - if options.NoRecreate && options.ForceRecreate { - return fmt.Errorf("no-recreate and force-recreate cannot be combined") - } - if err := p.initialize(ctx); err != nil { - return err - } - return p.perform(events.ProjectCreateStart, events.ProjectCreateDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceCreateStart, events.ServiceCreate, func(service Service) error { - return service.Create(ctx, options) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_delete.go b/vendor/github.com/docker/libcompose/project/project_delete.go deleted file mode 100644 index ab1d35017..000000000 --- a/vendor/github.com/docker/libcompose/project/project_delete.go +++ /dev/null @@ -1,17 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Delete removes the specified services (like docker rm). -func (p *Project) Delete(ctx context.Context, options options.Delete, services ...string) error { - return p.perform(events.ProjectDeleteStart, events.ProjectDeleteDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServiceDeleteStart, events.ServiceDelete, func(service Service) error { - return service.Delete(ctx, options) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_down.go b/vendor/github.com/docker/libcompose/project/project_down.go deleted file mode 100644 index 288ce53dd..000000000 --- a/vendor/github.com/docker/libcompose/project/project_down.go +++ /dev/null @@ -1,56 +0,0 @@ -package project - -import ( - "fmt" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Down stops the specified services and clean related containers (like docker stop + docker rm). -func (p *Project) Down(ctx context.Context, opts options.Down, services ...string) error { - if !opts.RemoveImages.Valid() { - return fmt.Errorf("--rmi flag must be local, all or empty") - } - if err := p.Stop(ctx, 10, services...); err != nil { - return err - } - if opts.RemoveOrphans { - if err := p.runtime.RemoveOrphans(ctx, p.Name, p.ServiceConfigs); err != nil { - return err - } - } - if err := p.Delete(ctx, options.Delete{ - RemoveVolume: opts.RemoveVolume, - }, services...); err != nil { - return err - } - - networks, err := p.context.NetworksFactory.Create(p.Name, p.NetworkConfigs, p.ServiceConfigs, p.isNetworkEnabled()) - if err != nil { - return err - } - if err := networks.Remove(ctx); err != nil { - return err - } - - if opts.RemoveVolume { - volumes, err := p.context.VolumesFactory.Create(p.Name, p.VolumeConfigs, p.ServiceConfigs, p.isVolumeEnabled()) - if err != nil { - return err - } - if err := volumes.Remove(ctx); err != nil { - return err - } - } - - return p.forEach([]string{}, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.NoEvent, events.NoEvent, func(service Service) error { - return service.RemoveImage(ctx, opts.RemoveImages) - }) - }), func(service Service) error { - return service.Create(ctx, options.Create{}) - }) -} diff --git a/vendor/github.com/docker/libcompose/project/project_events.go b/vendor/github.com/docker/libcompose/project/project_events.go deleted file mode 100644 index 0b296f30e..000000000 --- a/vendor/github.com/docker/libcompose/project/project_events.go +++ /dev/null @@ -1,24 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Events listen for real time events from containers (of the project). -func (p *Project) Events(ctx context.Context, services ...string) (chan events.ContainerEvent, error) { - events := make(chan events.ContainerEvent) - if len(services) == 0 { - services = p.ServiceConfigs.Keys() - } - // FIXME(vdemeester) handle errors (chan) here - for _, service := range services { - s, err := p.CreateService(service) - if err != nil { - return nil, err - } - go s.Events(ctx, events) - } - return events, nil -} diff --git a/vendor/github.com/docker/libcompose/project/project_kill.go b/vendor/github.com/docker/libcompose/project/project_kill.go deleted file mode 100644 index ac3c87d71..000000000 --- a/vendor/github.com/docker/libcompose/project/project_kill.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Kill kills the specified services (like docker kill). -func (p *Project) Kill(ctx context.Context, signal string, services ...string) error { - return p.perform(events.ProjectKillStart, events.ProjectKillDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServiceKillStart, events.ServiceKill, func(service Service) error { - return service.Kill(ctx, signal) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_log.go b/vendor/github.com/docker/libcompose/project/project_log.go deleted file mode 100644 index 7e576d586..000000000 --- a/vendor/github.com/docker/libcompose/project/project_log.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Log aggregates and prints out the logs for the specified services. -func (p *Project) Log(ctx context.Context, follow bool, services ...string) error { - return p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.NoEvent, events.NoEvent, func(service Service) error { - return service.Log(ctx, follow) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_pause.go b/vendor/github.com/docker/libcompose/project/project_pause.go deleted file mode 100644 index c5c4c39b3..000000000 --- a/vendor/github.com/docker/libcompose/project/project_pause.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Pause pauses the specified services containers (like docker pause). -func (p *Project) Pause(ctx context.Context, services ...string) error { - return p.perform(events.ProjectPauseStart, events.ProjectPauseDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServicePauseStart, events.ServicePause, func(service Service) error { - return service.Pause(ctx) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_port.go b/vendor/github.com/docker/libcompose/project/project_port.go deleted file mode 100644 index 85fa6d8a5..000000000 --- a/vendor/github.com/docker/libcompose/project/project_port.go +++ /dev/null @@ -1,26 +0,0 @@ -package project - -import ( - "fmt" - - "golang.org/x/net/context" -) - -// Port returns the public port for a port binding of the specified service. -func (p *Project) Port(ctx context.Context, index int, protocol, serviceName, privatePort string) (string, error) { - service, err := p.CreateService(serviceName) - if err != nil { - return "", err - } - - containers, err := service.Containers(ctx) - if err != nil { - return "", err - } - - if index < 1 || index > len(containers) { - return "", fmt.Errorf("Invalid index %d", index) - } - - return containers[index-1].Port(ctx, fmt.Sprintf("%s/%s", privatePort, protocol)) -} diff --git a/vendor/github.com/docker/libcompose/project/project_ps.go b/vendor/github.com/docker/libcompose/project/project_ps.go deleted file mode 100644 index 2c69018bc..000000000 --- a/vendor/github.com/docker/libcompose/project/project_ps.go +++ /dev/null @@ -1,28 +0,0 @@ -package project - -import "golang.org/x/net/context" - -// Ps list containers for the specified services. -func (p *Project) Ps(ctx context.Context, services ...string) (InfoSet, error) { - allInfo := InfoSet{} - - if len(services) == 0 { - services = p.ServiceConfigs.Keys() - } - - for _, name := range services { - - service, err := p.CreateService(name) - if err != nil { - return nil, err - } - - info, err := service.Info(ctx) - if err != nil { - return nil, err - } - - allInfo = append(allInfo, info...) - } - return allInfo, nil -} diff --git a/vendor/github.com/docker/libcompose/project/project_pull.go b/vendor/github.com/docker/libcompose/project/project_pull.go deleted file mode 100644 index 5a7b0eedd..000000000 --- a/vendor/github.com/docker/libcompose/project/project_pull.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Pull pulls the specified services (like docker pull). -func (p *Project) Pull(ctx context.Context, services ...string) error { - return p.forEach(services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServicePullStart, events.ServicePull, func(service Service) error { - return service.Pull(ctx) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_restart.go b/vendor/github.com/docker/libcompose/project/project_restart.go deleted file mode 100644 index 0cb326523..000000000 --- a/vendor/github.com/docker/libcompose/project/project_restart.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Restart restarts the specified services (like docker restart). -func (p *Project) Restart(ctx context.Context, timeout int, services ...string) error { - return p.perform(events.ProjectRestartStart, events.ProjectRestartDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceRestartStart, events.ServiceRestart, func(service Service) error { - return service.Restart(ctx, timeout) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_run.go b/vendor/github.com/docker/libcompose/project/project_run.go deleted file mode 100644 index c5f223fcc..000000000 --- a/vendor/github.com/docker/libcompose/project/project_run.go +++ /dev/null @@ -1,35 +0,0 @@ -package project - -import ( - "fmt" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Run executes a one off command (like `docker run image command`). -func (p *Project) Run(ctx context.Context, serviceName string, commandParts []string, opts options.Run) (int, error) { - if !p.ServiceConfigs.Has(serviceName) { - return 1, fmt.Errorf("%s is not defined in the template", serviceName) - } - - if err := p.initialize(ctx); err != nil { - return 1, err - } - var exitCode int - err := p.forEach([]string{}, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceRunStart, events.ServiceRun, func(service Service) error { - if service.Name() == serviceName { - code, err := service.Run(ctx, commandParts, opts) - exitCode = code - return err - } - return nil - }) - }), func(service Service) error { - return service.Create(ctx, options.Create{}) - }) - return exitCode, err -} diff --git a/vendor/github.com/docker/libcompose/project/project_scale.go b/vendor/github.com/docker/libcompose/project/project_scale.go deleted file mode 100644 index 4ce26402a..000000000 --- a/vendor/github.com/docker/libcompose/project/project_scale.go +++ /dev/null @@ -1,40 +0,0 @@ -package project - -import ( - "fmt" - - "golang.org/x/net/context" - - log "github.com/sirupsen/logrus" -) - -// Scale scales the specified services. -func (p *Project) Scale(ctx context.Context, timeout int, servicesScale map[string]int) error { - // This code is a bit verbose but I wanted to parse everything up front - order := make([]string, 0, 0) - services := make(map[string]Service) - - for name := range servicesScale { - if !p.ServiceConfigs.Has(name) { - return fmt.Errorf("%s is not defined in the template", name) - } - - service, err := p.CreateService(name) - if err != nil { - return fmt.Errorf("Failed to lookup service: %s: %v", service, err) - } - - order = append(order, name) - services[name] = service - } - - for _, name := range order { - scale := servicesScale[name] - log.Infof("Setting scale %s=%d...", name, scale) - err := services[name].Scale(ctx, scale, timeout) - if err != nil { - return fmt.Errorf("Failed to set the scale %s=%d: %v", name, scale, err) - } - } - return nil -} diff --git a/vendor/github.com/docker/libcompose/project/project_start.go b/vendor/github.com/docker/libcompose/project/project_start.go deleted file mode 100644 index 8ffebdd3c..000000000 --- a/vendor/github.com/docker/libcompose/project/project_start.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Start starts the specified services (like docker start). -func (p *Project) Start(ctx context.Context, services ...string) error { - return p.perform(events.ProjectStartStart, events.ProjectStartDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceStartStart, events.ServiceStart, func(service Service) error { - return service.Start(ctx) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_stop.go b/vendor/github.com/docker/libcompose/project/project_stop.go deleted file mode 100644 index 16887f5b7..000000000 --- a/vendor/github.com/docker/libcompose/project/project_stop.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Stop stops the specified services (like docker stop). -func (p *Project) Stop(ctx context.Context, timeout int, services ...string) error { - return p.perform(events.ProjectStopStart, events.ProjectStopDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServiceStopStart, events.ServiceStop, func(service Service) error { - return service.Stop(ctx, timeout) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_unpause.go b/vendor/github.com/docker/libcompose/project/project_unpause.go deleted file mode 100644 index 625129d8b..000000000 --- a/vendor/github.com/docker/libcompose/project/project_unpause.go +++ /dev/null @@ -1,16 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" -) - -// Unpause pauses the specified services containers (like docker pause). -func (p *Project) Unpause(ctx context.Context, services ...string) error { - return p.perform(events.ProjectUnpauseStart, events.ProjectUnpauseDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(nil, events.ServiceUnpauseStart, events.ServiceUnpause, func(service Service) error { - return service.Unpause(ctx) - }) - }), nil) -} diff --git a/vendor/github.com/docker/libcompose/project/project_up.go b/vendor/github.com/docker/libcompose/project/project_up.go deleted file mode 100644 index f5954cd7b..000000000 --- a/vendor/github.com/docker/libcompose/project/project_up.go +++ /dev/null @@ -1,22 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Up creates and starts the specified services (kinda like docker run). -func (p *Project) Up(ctx context.Context, options options.Up, services ...string) error { - if err := p.initialize(ctx); err != nil { - return err - } - return p.perform(events.ProjectUpStart, events.ProjectUpDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) { - wrapper.Do(wrappers, events.ServiceUpStart, events.ServiceUp, func(service Service) error { - return service.Up(ctx, options) - }) - }), func(service Service) error { - return service.Create(ctx, options.Create) - }) -} diff --git a/vendor/github.com/docker/libcompose/project/service-wrapper.go b/vendor/github.com/docker/libcompose/project/service-wrapper.go deleted file mode 100644 index 75dc1e868..000000000 --- a/vendor/github.com/docker/libcompose/project/service-wrapper.go +++ /dev/null @@ -1,115 +0,0 @@ -package project - -import ( - "sync" - - "github.com/docker/libcompose/project/events" - log "github.com/sirupsen/logrus" -) - -type serviceWrapper struct { - name string - service Service - done sync.WaitGroup - state ServiceState - err error - project *Project - noWait bool - ignored map[string]bool -} - -func newServiceWrapper(name string, p *Project) (*serviceWrapper, error) { - wrapper := &serviceWrapper{ - name: name, - state: StateUnknown, - project: p, - ignored: map[string]bool{}, - } - - return wrapper, wrapper.Reset() -} - -func (s *serviceWrapper) IgnoreDep(name string) { - s.ignored[name] = true -} - -func (s *serviceWrapper) Reset() error { - if s.state != StateExecuted { - service, err := s.project.CreateService(s.name) - if err != nil { - log.Errorf("Failed to create service for %s : %v", s.name, err) - return err - } - - s.service = service - } - - if s.err == ErrRestart { - s.err = nil - } - s.done.Add(1) - - return nil -} - -func (s *serviceWrapper) Ignore() { - defer s.done.Done() - - s.state = StateExecuted - s.project.Notify(events.ServiceUpIgnored, s.service.Name(), nil) -} - -func (s *serviceWrapper) waitForDeps(wrappers map[string]*serviceWrapper) bool { - if s.noWait { - return true - } - - for _, dep := range s.service.DependentServices() { - if s.ignored[dep.Target] { - continue - } - - if wrapper, ok := wrappers[dep.Target]; ok { - if wrapper.Wait() == ErrRestart { - s.project.Notify(events.ProjectReload, wrapper.service.Name(), nil) - s.err = ErrRestart - return false - } - } else { - log.Errorf("Failed to find %s", dep.Target) - } - } - - return true -} - -func (s *serviceWrapper) Do(wrappers map[string]*serviceWrapper, start, done events.EventType, action func(service Service) error) { - defer s.done.Done() - - if s.state == StateExecuted { - return - } - - if wrappers != nil && !s.waitForDeps(wrappers) { - return - } - - s.state = StateExecuted - - s.project.Notify(start, s.service.Name(), nil) - - s.err = action(s.service) - if s.err == ErrRestart { - s.project.Notify(done, s.service.Name(), nil) - s.project.Notify(events.ProjectReloadTrigger, s.service.Name(), nil) - } else if s.err != nil { - log.Errorf("Failed %s %s : %v", start, s.name, s.err) - } else { - s.project.Notify(done, s.service.Name(), nil) - } -} - -func (s *serviceWrapper) Wait() error { - s.done.Wait() - return s.err -} diff --git a/vendor/github.com/docker/libcompose/project/service.go b/vendor/github.com/docker/libcompose/project/service.go deleted file mode 100644 index 581df6740..000000000 --- a/vendor/github.com/docker/libcompose/project/service.go +++ /dev/null @@ -1,97 +0,0 @@ -package project - -import ( - "errors" - - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" - "github.com/docker/libcompose/project/events" - "github.com/docker/libcompose/project/options" -) - -// Service defines what a libcompose service provides. -type Service interface { - Build(ctx context.Context, buildOptions options.Build) error - Create(ctx context.Context, options options.Create) error - Delete(ctx context.Context, options options.Delete) error - Events(ctx context.Context, messages chan events.ContainerEvent) error - Info(ctx context.Context) (InfoSet, error) - Log(ctx context.Context, follow bool) error - Kill(ctx context.Context, signal string) error - Pause(ctx context.Context) error - Pull(ctx context.Context) error - Restart(ctx context.Context, timeout int) error - Run(ctx context.Context, commandParts []string, options options.Run) (int, error) - Scale(ctx context.Context, count int, timeout int) error - Start(ctx context.Context) error - Stop(ctx context.Context, timeout int) error - Unpause(ctx context.Context) error - Up(ctx context.Context, options options.Up) error - - RemoveImage(ctx context.Context, imageType options.ImageType) error - Containers(ctx context.Context) ([]Container, error) - DependentServices() []ServiceRelationship - Config() *config.ServiceConfig - Name() string -} - -// ServiceState holds the state of a service. -type ServiceState string - -// State definitions -var ( - StateExecuted = ServiceState("executed") - StateUnknown = ServiceState("unknown") -) - -// Error definitions -var ( - ErrRestart = errors.New("Restart execution") - ErrUnsupported = errors.New("UnsupportedOperation") -) - -// ServiceFactory is an interface factory to create Service object for the specified -// project, with the specified name and service configuration. -type ServiceFactory interface { - Create(project *Project, name string, serviceConfig *config.ServiceConfig) (Service, error) -} - -// ServiceRelationshipType defines the type of service relationship. -type ServiceRelationshipType string - -// RelTypeLink means the services are linked (docker links). -const RelTypeLink = ServiceRelationshipType("") - -// RelTypeNetNamespace means the services share the same network namespace. -const RelTypeNetNamespace = ServiceRelationshipType("netns") - -// RelTypeIpcNamespace means the service share the same ipc namespace. -const RelTypeIpcNamespace = ServiceRelationshipType("ipc") - -// RelTypeVolumesFrom means the services share some volumes. -const RelTypeVolumesFrom = ServiceRelationshipType("volumesFrom") - -// RelTypeDependsOn means the dependency was explicitly set using 'depends_on'. -const RelTypeDependsOn = ServiceRelationshipType("dependsOn") - -// RelTypeNetworkMode means the services depends on another service on networkMode -const RelTypeNetworkMode = ServiceRelationshipType("networkMode") - -// ServiceRelationship holds the relationship information between two services. -type ServiceRelationship struct { - Target, Alias string - Type ServiceRelationshipType - Optional bool -} - -// NewServiceRelationship creates a new Relationship based on the specified alias -// and relationship type. -func NewServiceRelationship(nameAlias string, relType ServiceRelationshipType) ServiceRelationship { - name, alias := NameAlias(nameAlias) - return ServiceRelationship{ - Target: name, - Alias: alias, - Type: relType, - } -} diff --git a/vendor/github.com/docker/libcompose/project/utils.go b/vendor/github.com/docker/libcompose/project/utils.go deleted file mode 100644 index 418f245fc..000000000 --- a/vendor/github.com/docker/libcompose/project/utils.go +++ /dev/null @@ -1,47 +0,0 @@ -package project - -import ( - "strings" -) - -// DefaultDependentServices return the dependent services (as an array of ServiceRelationship) -// for the specified project and service. It looks for : links, volumesFrom, net and ipc configuration. -func DefaultDependentServices(p *Project, s Service) []ServiceRelationship { - config := s.Config() - if config == nil { - return []ServiceRelationship{} - } - - result := []ServiceRelationship{} - for _, link := range config.Links { - result = append(result, NewServiceRelationship(link, RelTypeLink)) - } - - for _, volumesFrom := range config.VolumesFrom { - result = append(result, NewServiceRelationship(volumesFrom, RelTypeVolumesFrom)) - } - - for _, dependsOn := range config.DependsOn { - result = append(result, NewServiceRelationship(dependsOn, RelTypeDependsOn)) - } - - if config.NetworkMode != "" { - if strings.HasPrefix(config.NetworkMode, "service:") { - serviceName := config.NetworkMode[8:] - result = append(result, NewServiceRelationship(serviceName, RelTypeNetworkMode)) - } - } - - return result -} - -// NameAlias returns the name and alias based on the specified string. -// If the name contains a colon (like name:alias) it will split it, otherwise -// it will return the specified name as name and alias. -func NameAlias(name string) (string, string) { - parts := strings.SplitN(name, ":", 2) - if len(parts) == 2 { - return parts[0], parts[1] - } - return parts[0], parts[0] -} diff --git a/vendor/github.com/docker/libcompose/project/volume.go b/vendor/github.com/docker/libcompose/project/volume.go deleted file mode 100644 index 08f926e30..000000000 --- a/vendor/github.com/docker/libcompose/project/volume.go +++ /dev/null @@ -1,19 +0,0 @@ -package project - -import ( - "golang.org/x/net/context" - - "github.com/docker/libcompose/config" -) - -// Volumes defines the methods a libcompose volume aggregate should define. -type Volumes interface { - Initialize(ctx context.Context) error - Remove(ctx context.Context) error -} - -// VolumesFactory is an interface factory to create Volumes object for the specified -// configurations (service, volumes, …) -type VolumesFactory interface { - Create(projectName string, volumeConfigs map[string]*config.VolumeConfig, serviceConfigs *config.ServiceConfigs, volumeEnabled bool) (Volumes, error) -} diff --git a/vendor/github.com/docker/libcompose/utils/util.go b/vendor/github.com/docker/libcompose/utils/util.go deleted file mode 100644 index 6f42c1f05..000000000 --- a/vendor/github.com/docker/libcompose/utils/util.go +++ /dev/null @@ -1,178 +0,0 @@ -package utils - -import ( - "encoding/json" - "sync" - "time" - - "github.com/sirupsen/logrus" - - "gopkg.in/yaml.v2" -) - -// InParallel holds a pool and a waitgroup to execute tasks in parallel and to be able -// to wait for completion of all tasks. -type InParallel struct { - wg sync.WaitGroup - pool sync.Pool -} - -// Add runs the specified task in parallel and adds it to the waitGroup. -func (i *InParallel) Add(task func() error) { - i.wg.Add(1) - - go func() { - defer i.wg.Done() - err := task() - if err != nil { - i.pool.Put(err) - } - }() -} - -// Wait waits for all tasks to complete and returns the latest error encountered if any. -func (i *InParallel) Wait() error { - i.wg.Wait() - obj := i.pool.Get() - if err, ok := obj.(error); ok { - return err - } - return nil -} - -// ConvertByJSON converts a struct (src) to another one (target) using json marshalling/unmarshalling. -// If the structure are not compatible, this will throw an error as the unmarshalling will fail. -func ConvertByJSON(src, target interface{}) error { - newBytes, err := json.Marshal(src) - if err != nil { - return err - } - - err = json.Unmarshal(newBytes, target) - if err != nil { - logrus.Errorf("Failed to unmarshall: %v\n%s", err, string(newBytes)) - } - return err -} - -// Convert converts a struct (src) to another one (target) using yaml marshalling/unmarshalling. -// If the structure are not compatible, this will throw an error as the unmarshalling will fail. -func Convert(src, target interface{}) error { - newBytes, err := yaml.Marshal(src) - if err != nil { - return err - } - - err = yaml.Unmarshal(newBytes, target) - if err != nil { - logrus.Errorf("Failed to unmarshall: %v\n%s", err, string(newBytes)) - } - return err -} - -// CopySlice creates an exact copy of the provided string slice -func CopySlice(s []string) []string { - if s == nil { - return nil - } - r := make([]string, len(s)) - copy(r, s) - return r -} - -// CopyMap creates an exact copy of the provided string-to-string map -func CopyMap(m map[string]string) map[string]string { - if m == nil { - return nil - } - r := map[string]string{} - for k, v := range m { - r[k] = v - } - return r -} - -// FilterStringSet accepts a string set `s` (in the form of `map[string]bool`) and a filtering function `f` -// and returns a string set containing only the strings `x` for which `f(x) == true` -func FilterStringSet(s map[string]bool, f func(x string) bool) map[string]bool { - result := map[string]bool{} - for k := range s { - if f(k) { - result[k] = true - } - } - return result -} - -// FilterString returns a json representation of the specified map -// that is used as filter for docker. -func FilterString(data map[string][]string) string { - // I can't imagine this would ever fail - bytes, _ := json.Marshal(data) - return string(bytes) -} - -// Contains checks if the specified string (key) is present in the specified collection. -func Contains(collection []string, key string) bool { - for _, value := range collection { - if value == key { - return true - } - } - - return false -} - -// Merge performs a union of two string slices: the result is an unordered slice -// that includes every item from either argument exactly once -func Merge(coll1, coll2 []string) []string { - m := map[string]struct{}{} - for _, v := range append(coll1, coll2...) { - m[v] = struct{}{} - } - r := make([]string, 0, len(m)) - for k := range m { - r = append(r, k) - } - return r -} - -// ConvertKeysToStrings converts map[interface{}] to map[string] recursively -func ConvertKeysToStrings(item interface{}) interface{} { - switch typedDatas := item.(type) { - case map[string]interface{}: - for key, value := range typedDatas { - typedDatas[key] = ConvertKeysToStrings(value) - } - return typedDatas - case map[interface{}]interface{}: - newMap := make(map[string]interface{}) - for key, value := range typedDatas { - stringKey := key.(string) - newMap[stringKey] = ConvertKeysToStrings(value) - } - return newMap - case []interface{}: - for i, value := range typedDatas { - typedDatas[i] = ConvertKeysToStrings(value) - } - return typedDatas - default: - return item - } -} - -// DurationStrToSecondsInt converts duration string to *int in seconds -func DurationStrToSecondsInt(s string) *int { - if s == "" { - return nil - } - duration, err := time.ParseDuration(s) - if err != nil { - logrus.Errorf("Failed to parse duration:%v", s) - return nil - } - r := (int)(duration.Seconds()) - return &r - -} diff --git a/vendor/github.com/docker/libcompose/version/version.go b/vendor/github.com/docker/libcompose/version/version.go deleted file mode 100644 index 2d4593e92..000000000 --- a/vendor/github.com/docker/libcompose/version/version.go +++ /dev/null @@ -1,20 +0,0 @@ -package version - -var ( - // VERSION should be updated by hand at each release - VERSION = "0.4.0" - - // GITCOMMIT will be overwritten automatically by the build system - GITCOMMIT = "HEAD" - - // BUILDTIME will be overwritten automatically by the build system - BUILDTIME = "" - - // SHOWWARNING might be overwritten by the build system to not show the warning - SHOWWARNING = "true" -) - -// ShowWarning returns wether the warning should be printed or not -func ShowWarning() bool { - return SHOWWARNING != "false" -} diff --git a/vendor/github.com/docker/libcompose/yaml/build.go b/vendor/github.com/docker/libcompose/yaml/build.go deleted file mode 100644 index 920d2fae2..000000000 --- a/vendor/github.com/docker/libcompose/yaml/build.go +++ /dev/null @@ -1,181 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - "strconv" - "strings" -) - -// Build represents a build element in compose file. -// It can take multiple form in the compose file, hence this special type -type Build struct { - Context string - Dockerfile string - Args map[string]*string - CacheFrom []*string - Labels map[string]*string - // TODO: ShmSize (can be a string or int?) for v3.5 - Target string - // Note: as of Sep 2018 this is undocumented but supported by docker-compose - Network string -} - -// MarshalYAML implements the Marshaller interface. -func (b Build) MarshalYAML() (interface{}, error) { - m := map[string]interface{}{} - if b.Context != "" { - m["context"] = b.Context - } - if b.Dockerfile != "" { - m["dockerfile"] = b.Dockerfile - } - if len(b.Args) > 0 { - m["args"] = b.Args - } - if len(b.CacheFrom) > 0 { - m["cache_from"] = b.CacheFrom - } - if len(b.Labels) > 0 { - m["labels"] = b.Labels - } - if b.Target != "" { - m["target"] = b.Target - } - if b.Network != "" { - m["network"] = b.Network - } - return m, nil -} - -// UnmarshalYAML implements the Unmarshaller interface. -func (b *Build) UnmarshalYAML(unmarshal func(interface{}) error) error { - var stringType string - if err := unmarshal(&stringType); err == nil { - b.Context = stringType - return nil - } - - var mapType map[interface{}]interface{} - if err := unmarshal(&mapType); err == nil { - for mapKey, mapValue := range mapType { - switch mapKey { - case "context": - b.Context = mapValue.(string) - case "dockerfile": - b.Dockerfile = mapValue.(string) - case "args": - args, err := handleBuildArgs(mapValue) - if err != nil { - return err - } - b.Args = args - case "cache_from": - cacheFrom, err := handleBuildCacheFrom(mapValue) - if err != nil { - return err - } - b.CacheFrom = cacheFrom - case "labels": - labels, err := handleBuildLabels(mapValue) - if err != nil { - return err - } - b.Labels = labels - case "target": - b.Target = mapValue.(string) - case "network": - b.Network = mapValue.(string) - default: - // Ignore unknown keys - continue - } - } - return nil - } - - return errors.New("Failed to unmarshal Build") -} - -func handleBuildArgs(value interface{}) (map[string]*string, error) { - var args map[string]*string - switch v := value.(type) { - case map[interface{}]interface{}: - return handleBuildOptionMap(v) - case []interface{}: - return handleBuildArgsSlice(v) - default: - return args, fmt.Errorf("Failed to unmarshal Build args: %#v", value) - } -} - -func handleBuildCacheFrom(value interface{}) ([]*string, error) { - var cacheFrom []*string - switch v := value.(type) { - case []interface{}: - return handleBuildCacheFromSlice(v) - default: - return cacheFrom, fmt.Errorf("Failed to unmarshal Build cache_from: %#v", value) - } -} - -func handleBuildLabels(value interface{}) (map[string]*string, error) { - var labels map[string]*string - switch v := value.(type) { - case map[interface{}]interface{}: - return handleBuildOptionMap(v) - default: - return labels, fmt.Errorf("Failed to unmarshal Build labels: %#v", value) - } -} - -func handleBuildCacheFromSlice(s []interface{}) ([]*string, error) { - var args = []*string{} - for _, arg := range s { - strArg := arg.(string) - args = append(args, &strArg) - } - return args, nil -} - -func handleBuildArgsSlice(s []interface{}) (map[string]*string, error) { - var args = map[string]*string{} - for _, arg := range s { - // check if a value is provided - switch v := strings.SplitN(arg.(string), "=", 2); len(v) { - case 1: - // if we have not specified a a value for this build arg, we assign it an ascii null value and query the environment - // later when we build the service - str := "\x00" - args[v[0]] = &str - case 2: - // if we do have a value provided, we use it - args[v[0]] = &v[1] - } - } - return args, nil -} - -// Used for args and labels -func handleBuildOptionMap(m map[interface{}]interface{}) (map[string]*string, error) { - args := map[string]*string{} - for mapKey, mapValue := range m { - var argValue string - name, ok := mapKey.(string) - if !ok { - return args, fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - switch a := mapValue.(type) { - case string: - argValue = a - case int: - argValue = strconv.Itoa(a) - case int64: - argValue = strconv.Itoa(int(a)) - default: - return args, fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", mapValue, mapValue) - } - args[name] = &argValue - } - return args, nil -} diff --git a/vendor/github.com/docker/libcompose/yaml/command.go b/vendor/github.com/docker/libcompose/yaml/command.go deleted file mode 100644 index ace69b5d3..000000000 --- a/vendor/github.com/docker/libcompose/yaml/command.go +++ /dev/null @@ -1,42 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - - "github.com/docker/docker/api/types/strslice" - "github.com/flynn/go-shlex" -) - -// Command represents a docker command, can be a string or an array of strings. -type Command strslice.StrSlice - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *Command) UnmarshalYAML(unmarshal func(interface{}) error) error { - var stringType string - if err := unmarshal(&stringType); err == nil { - parts, err := shlex.Split(stringType) - if err != nil { - return err - } - *s = parts - return nil - } - - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - parts, err := toStrings(sliceType) - if err != nil { - return err - } - *s = parts - return nil - } - - var interfaceType interface{} - if err := unmarshal(&interfaceType); err == nil { - fmt.Println(interfaceType) - } - - return errors.New("Failed to unmarshal Command") -} diff --git a/vendor/github.com/docker/libcompose/yaml/external.go b/vendor/github.com/docker/libcompose/yaml/external.go deleted file mode 100644 index be7efca9f..000000000 --- a/vendor/github.com/docker/libcompose/yaml/external.go +++ /dev/null @@ -1,37 +0,0 @@ -package yaml - -// External represents an external network entry in compose file. -// It can be a boolean (true|false) or have a name -type External struct { - External bool - Name string -} - -// MarshalYAML implements the Marshaller interface. -func (n External) MarshalYAML() (interface{}, error) { - if n.Name == "" { - return n.External, nil - } - return map[string]interface{}{ - "name": n.Name, - }, nil -} - -// UnmarshalYAML implements the Unmarshaller interface. -func (n *External) UnmarshalYAML(unmarshal func(interface{}) error) error { - if err := unmarshal(&n.External); err == nil { - return nil - } - var dummyExternal struct { - Name string - } - - err := unmarshal(&dummyExternal) - if err != nil { - return err - } - n.Name = dummyExternal.Name - n.External = true - - return nil -} diff --git a/vendor/github.com/docker/libcompose/yaml/network.go b/vendor/github.com/docker/libcompose/yaml/network.go deleted file mode 100644 index d56ca4e08..000000000 --- a/vendor/github.com/docker/libcompose/yaml/network.go +++ /dev/null @@ -1,139 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - "sort" - "strings" -) - -// Networks represents a list of service networks in compose file. -// It has several representation, hence this specific struct. -type Networks struct { - Networks []*Network -} - -// Network represents a service network in compose file. -type Network struct { - Name string `yaml:"-"` - RealName string `yaml:"-"` - Aliases []string `yaml:"aliases,omitempty"` - IPv4Address string `yaml:"ipv4_address,omitempty"` - IPv6Address string `yaml:"ipv6_address,omitempty"` -} - -// Generate a hash string to detect service network config changes -func (n *Networks) HashString() string { - if n == nil { - return "" - } - result := []string{} - for _, net := range n.Networks { - result = append(result, net.HashString()) - } - sort.Strings(result) - return strings.Join(result, ",") -} - -// Generate a hash string to detect service network config changes -func (n *Network) HashString() string { - if n == nil { - return "" - } - result := []string{} - result = append(result, n.Name) - result = append(result, n.RealName) - sort.Strings(n.Aliases) - result = append(result, strings.Join(n.Aliases, ",")) - result = append(result, n.IPv4Address) - result = append(result, n.IPv6Address) - sort.Strings(result) - return strings.Join(result, ",") -} - -// MarshalYAML implements the Marshaller interface. -func (n Networks) MarshalYAML() (interface{}, error) { - m := map[string]*Network{} - for _, network := range n.Networks { - m[network.Name] = network - } - return m, nil -} - -// UnmarshalYAML implements the Unmarshaller interface. -func (n *Networks) UnmarshalYAML(unmarshal func(interface{}) error) error { - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - n.Networks = []*Network{} - for _, network := range sliceType { - name, ok := network.(string) - if !ok { - return fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - n.Networks = append(n.Networks, &Network{ - Name: name, - }) - } - return nil - } - - var mapType map[interface{}]interface{} - if err := unmarshal(&mapType); err == nil { - n.Networks = []*Network{} - for mapKey, mapValue := range mapType { - name, ok := mapKey.(string) - if !ok { - return fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - network, err := handleNetwork(name, mapValue) - if err != nil { - return err - } - n.Networks = append(n.Networks, network) - } - return nil - } - - return errors.New("Failed to unmarshal Networks") -} - -func handleNetwork(name string, value interface{}) (*Network, error) { - if value == nil { - return &Network{ - Name: name, - }, nil - } - switch v := value.(type) { - case map[interface{}]interface{}: - network := &Network{ - Name: name, - } - for mapKey, mapValue := range v { - name, ok := mapKey.(string) - if !ok { - return &Network{}, fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - switch name { - case "aliases": - aliases, ok := mapValue.([]interface{}) - if !ok { - return &Network{}, fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", aliases, aliases) - } - network.Aliases = []string{} - for _, alias := range aliases { - network.Aliases = append(network.Aliases, alias.(string)) - } - case "ipv4_address": - network.IPv4Address = mapValue.(string) - case "ipv6_address": - network.IPv6Address = mapValue.(string) - default: - // Ignorer unknown keys ? - continue - } - } - return network, nil - default: - return &Network{}, fmt.Errorf("Failed to unmarshal Network: %#v", value) - } -} diff --git a/vendor/github.com/docker/libcompose/yaml/types_yaml.go b/vendor/github.com/docker/libcompose/yaml/types_yaml.go deleted file mode 100644 index a3bed1d95..000000000 --- a/vendor/github.com/docker/libcompose/yaml/types_yaml.go +++ /dev/null @@ -1,257 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - "strconv" - "strings" - - "github.com/docker/docker/api/types/strslice" - "github.com/docker/go-units" -) - -// StringorInt represents a string or an integer. -type StringorInt int64 - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *StringorInt) UnmarshalYAML(unmarshal func(interface{}) error) error { - var intType int64 - if err := unmarshal(&intType); err == nil { - *s = StringorInt(intType) - return nil - } - - var stringType string - if err := unmarshal(&stringType); err == nil { - intType, err := strconv.ParseInt(stringType, 10, 64) - - if err != nil { - return err - } - *s = StringorInt(intType) - return nil - } - - return errors.New("Failed to unmarshal StringorInt") -} - -// MemStringorInt represents a string or an integer -// the String supports notations like 10m for then Megabyte of memory -type MemStringorInt int64 - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *MemStringorInt) UnmarshalYAML(unmarshal func(interface{}) error) error { - var intType int64 - if err := unmarshal(&intType); err == nil { - *s = MemStringorInt(intType) - return nil - } - - var stringType string - if err := unmarshal(&stringType); err == nil { - intType, err := units.RAMInBytes(stringType) - - if err != nil { - return err - } - *s = MemStringorInt(intType) - return nil - } - - return errors.New("Failed to unmarshal MemStringorInt") -} - -// Stringorslice represents -// Using engine-api Strslice and augment it with YAML marshalling stuff. a string or an array of strings. -type Stringorslice strslice.StrSlice - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *Stringorslice) UnmarshalYAML(unmarshal func(interface{}) error) error { - var stringType string - if err := unmarshal(&stringType); err == nil { - *s = []string{stringType} - return nil - } - - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - parts, err := toStrings(sliceType) - if err != nil { - return err - } - *s = parts - return nil - } - - return errors.New("Failed to unmarshal Stringorslice") -} - -// SliceorMap represents a slice or a map of strings. -type SliceorMap map[string]string - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *SliceorMap) UnmarshalYAML(unmarshal func(interface{}) error) error { - - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - parts := map[string]string{} - for _, s := range sliceType { - if str, ok := s.(string); ok { - str := strings.TrimSpace(str) - keyValueSlice := strings.SplitN(str, "=", 2) - - key := keyValueSlice[0] - val := "" - if len(keyValueSlice) == 2 { - val = keyValueSlice[1] - } - parts[key] = val - } else { - return fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", s, s) - } - } - *s = parts - return nil - } - - var mapType map[interface{}]interface{} - if err := unmarshal(&mapType); err == nil { - parts := map[string]string{} - for k, v := range mapType { - if sk, ok := k.(string); ok { - if sv, ok := v.(string); ok { - parts[sk] = sv - } else { - return fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", v, v) - } - } else { - return fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", k, k) - } - } - *s = parts - return nil - } - - return errors.New("Failed to unmarshal SliceorMap") -} - -// MaporEqualSlice represents a slice of strings that gets unmarshal from a -// YAML map into 'key=value' string. -type MaporEqualSlice []string - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *MaporEqualSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { - parts, err := unmarshalToStringOrSepMapParts(unmarshal, "=") - if err != nil { - return err - } - *s = parts - return nil -} - -// ToMap returns the list of string as a map splitting using = the key=value -func (s *MaporEqualSlice) ToMap() map[string]string { - return toMap(*s, "=") -} - -// MaporColonSlice represents a slice of strings that gets unmarshal from a -// YAML map into 'key:value' string. -type MaporColonSlice []string - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *MaporColonSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { - parts, err := unmarshalToStringOrSepMapParts(unmarshal, ":") - if err != nil { - return err - } - *s = parts - return nil -} - -// ToMap returns the list of string as a map splitting using = the key=value -func (s *MaporColonSlice) ToMap() map[string]string { - return toMap(*s, ":") -} - -// MaporSpaceSlice represents a slice of strings that gets unmarshal from a -// YAML map into 'key value' string. -type MaporSpaceSlice []string - -// UnmarshalYAML implements the Unmarshaller interface. -func (s *MaporSpaceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { - parts, err := unmarshalToStringOrSepMapParts(unmarshal, " ") - if err != nil { - return err - } - *s = parts - return nil -} - -// ToMap returns the list of string as a map splitting using = the key=value -func (s *MaporSpaceSlice) ToMap() map[string]string { - return toMap(*s, " ") -} - -func unmarshalToStringOrSepMapParts(unmarshal func(interface{}) error, key string) ([]string, error) { - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - return toStrings(sliceType) - } - var mapType map[interface{}]interface{} - if err := unmarshal(&mapType); err == nil { - return toSepMapParts(mapType, key) - } - return nil, errors.New("Failed to unmarshal MaporSlice") -} - -func toSepMapParts(value map[interface{}]interface{}, sep string) ([]string, error) { - if len(value) == 0 { - return nil, nil - } - parts := make([]string, 0, len(value)) - for k, v := range value { - if sk, ok := k.(string); ok { - if sv, ok := v.(string); ok { - parts = append(parts, sk+sep+sv) - } else if sv, ok := v.(int); ok { - parts = append(parts, sk+sep+strconv.Itoa(sv)) - } else if sv, ok := v.(int64); ok { - parts = append(parts, sk+sep+strconv.FormatInt(sv, 10)) - } else if sv, ok := v.(float64); ok { - parts = append(parts, sk+sep+strconv.FormatFloat(sv, 'f', -1, 64)) - } else if v == nil { - parts = append(parts, sk) - } else { - return nil, fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", v, v) - } - } else { - return nil, fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", k, k) - } - } - return parts, nil -} - -func toStrings(s []interface{}) ([]string, error) { - if len(s) == 0 { - return nil, nil - } - r := make([]string, len(s)) - for k, v := range s { - if sv, ok := v.(string); ok { - r[k] = sv - } else { - return nil, fmt.Errorf("Cannot unmarshal '%v' of type %T into a string value", v, v) - } - } - return r, nil -} - -func toMap(s []string, sep string) map[string]string { - m := map[string]string{} - for _, v := range s { - // Return everything past first sep - values := strings.Split(v, sep) - m[values[0]] = strings.SplitN(v, sep, 2)[1] - } - return m -} diff --git a/vendor/github.com/docker/libcompose/yaml/ulimit.go b/vendor/github.com/docker/libcompose/yaml/ulimit.go deleted file mode 100644 index c25c49364..000000000 --- a/vendor/github.com/docker/libcompose/yaml/ulimit.go +++ /dev/null @@ -1,108 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - "sort" -) - -// Ulimits represents a list of Ulimit. -// It is, however, represented in yaml as keys (and thus map in Go) -type Ulimits struct { - Elements []Ulimit -} - -// MarshalYAML implements the Marshaller interface. -func (u Ulimits) MarshalYAML() (interface{}, error) { - ulimitMap := make(map[string]Ulimit) - for _, ulimit := range u.Elements { - ulimitMap[ulimit.Name] = ulimit - } - return ulimitMap, nil -} - -// UnmarshalYAML implements the Unmarshaller interface. -func (u *Ulimits) UnmarshalYAML(unmarshal func(interface{}) error) error { - ulimits := make(map[string]Ulimit) - - var mapType map[interface{}]interface{} - if err := unmarshal(&mapType); err == nil { - for mapKey, mapValue := range mapType { - name, ok := mapKey.(string) - if !ok { - return fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - var soft, hard int64 - switch mv := mapValue.(type) { - case int: - soft = int64(mv) - hard = int64(mv) - case map[interface{}]interface{}: - if len(mv) != 2 { - return fmt.Errorf("Failed to unmarshal Ulimit: %#v", mapValue) - } - for mkey, mvalue := range mv { - switch mkey { - case "soft": - soft = int64(mvalue.(int)) - case "hard": - hard = int64(mvalue.(int)) - default: - // FIXME(vdemeester) Should we ignore or fail ? - continue - } - } - default: - return fmt.Errorf("Failed to unmarshal Ulimit: %v, %T", mapValue, mapValue) - } - ulimits[name] = Ulimit{ - Name: name, - ulimitValues: ulimitValues{ - Soft: soft, - Hard: hard, - }, - } - } - keys := make([]string, 0, len(ulimits)) - for key := range ulimits { - keys = append(keys, key) - } - sort.Strings(keys) - for _, key := range keys { - u.Elements = append(u.Elements, ulimits[key]) - } - return nil - } - - return errors.New("Failed to unmarshal Ulimit") -} - -// Ulimit represents ulimit information. -type Ulimit struct { - ulimitValues - Name string -} - -type ulimitValues struct { - Soft int64 `yaml:"soft"` - Hard int64 `yaml:"hard"` -} - -// MarshalYAML implements the Marshaller interface. -func (u Ulimit) MarshalYAML() (interface{}, error) { - if u.Soft == u.Hard { - return u.Soft, nil - } - return u.ulimitValues, nil -} - -// NewUlimit creates a Ulimit based on the specified parts. -func NewUlimit(name string, soft int64, hard int64) Ulimit { - return Ulimit{ - Name: name, - ulimitValues: ulimitValues{ - Soft: soft, - Hard: hard, - }, - } -} diff --git a/vendor/github.com/docker/libcompose/yaml/volume.go b/vendor/github.com/docker/libcompose/yaml/volume.go deleted file mode 100644 index 8eabe572a..000000000 --- a/vendor/github.com/docker/libcompose/yaml/volume.go +++ /dev/null @@ -1,97 +0,0 @@ -package yaml - -import ( - "errors" - "fmt" - "sort" - "strings" -) - -// Volumes represents a list of service volumes in compose file. -// It has several representation, hence this specific struct. -type Volumes struct { - Volumes []*Volume -} - -// Volume represent a service volume -type Volume struct { - Source string `yaml:"-"` - Destination string `yaml:"-"` - AccessMode string `yaml:"-"` -} - -// Generate a hash string to detect service volume config changes -func (v *Volumes) HashString() string { - if v == nil { - return "" - } - result := []string{} - for _, vol := range v.Volumes { - result = append(result, vol.String()) - } - sort.Strings(result) - return strings.Join(result, ",") -} - -// String implements the Stringer interface. -func (v *Volume) String() string { - var paths []string - if v.Source != "" { - paths = []string{v.Source, v.Destination} - } else { - paths = []string{v.Destination} - } - if v.AccessMode != "" { - paths = append(paths, v.AccessMode) - } - return strings.Join(paths, ":") -} - -// MarshalYAML implements the Marshaller interface. -func (v Volumes) MarshalYAML() (interface{}, error) { - vs := []string{} - for _, volume := range v.Volumes { - vs = append(vs, volume.String()) - } - return vs, nil -} - -// UnmarshalYAML implements the Unmarshaller interface. -func (v *Volumes) UnmarshalYAML(unmarshal func(interface{}) error) error { - var sliceType []interface{} - if err := unmarshal(&sliceType); err == nil { - v.Volumes = []*Volume{} - for _, volume := range sliceType { - name, ok := volume.(string) - if !ok { - return fmt.Errorf("Cannot unmarshal '%v' to type %T into a string value", name, name) - } - elts := strings.SplitN(name, ":", 3) - var vol *Volume - switch { - case len(elts) == 1: - vol = &Volume{ - Destination: elts[0], - } - case len(elts) == 2: - vol = &Volume{ - Source: elts[0], - Destination: elts[1], - } - case len(elts) == 3: - vol = &Volume{ - Source: elts[0], - Destination: elts[1], - AccessMode: elts[2], - } - default: - // FIXME - return fmt.Errorf("") - } - v.Volumes = append(v.Volumes, vol) - } - return nil - } - - return errors.New("Failed to unmarshal Volumes") -} diff --git a/vendor/github.com/donovanhide/eventsource/decoder.go b/vendor/github.com/donovanhide/eventsource/decoder.go deleted file mode 100644 index df339b25e..000000000 --- a/vendor/github.com/donovanhide/eventsource/decoder.go +++ /dev/null @@ -1,83 +0,0 @@ -package eventsource - -import ( - "bufio" - "io" - "strconv" - "strings" -) - -type publication struct { - id, event, data string - retry int64 -} - -func (s *publication) Id() string { return s.id } -func (s *publication) Event() string { return s.event } -func (s *publication) Data() string { return s.data } -func (s *publication) Retry() int64 { return s.retry } - -// A Decoder is capable of reading Events from a stream. -type Decoder struct { - *bufio.Reader -} - -// NewDecoder returns a new Decoder instance that reads events -// with the given io.Reader. -func NewDecoder(r io.Reader) *Decoder { - dec := &Decoder{bufio.NewReader(newNormaliser(r))} - return dec -} - -// Decode reads the next Event from a stream (and will block until one -// comes in). -// Graceful disconnects (between events) are indicated by an io.EOF error. -// Any error occuring mid-event is considered non-graceful and will -// show up as some other error (most likely io.ErrUnexpectedEOF). -func (dec *Decoder) Decode() (Event, error) { - // peek ahead before we start a new event so we can return EOFs - _, err := dec.Peek(1) - if err == io.ErrUnexpectedEOF { - err = io.EOF - } - if err != nil { - return nil, err - } - pub := new(publication) - inDecoding := false - for { - line, err := dec.ReadString('\n') - if err != nil { - return nil, err - } - if line == "\n" && inDecoding { - // the empty line signals the end of an event - break - } else if line == "\n" && !inDecoding { - // only a newline was sent, so we don't want to publish an empty event but try to read again - continue - } - line = strings.TrimSuffix(line, "\n") - if strings.HasPrefix(line, ":") { - continue - } - sections := strings.SplitN(line, ":", 2) - field, value := sections[0], "" - if len(sections) == 2 { - value = strings.TrimPrefix(sections[1], " ") - } - inDecoding = true - switch field { - case "event": - pub.event = value - case "data": - pub.data += value + "\n" - case "id": - pub.id = value - case "retry": - pub.retry, _ = strconv.ParseInt(value, 10, 64) - } - } - pub.data = strings.TrimSuffix(pub.data, "\n") - return pub, nil -} diff --git a/vendor/github.com/donovanhide/eventsource/encoder.go b/vendor/github.com/donovanhide/eventsource/encoder.go deleted file mode 100644 index e9c7c3160..000000000 --- a/vendor/github.com/donovanhide/eventsource/encoder.go +++ /dev/null @@ -1,58 +0,0 @@ -package eventsource - -import ( - "compress/gzip" - "fmt" - "io" - "strings" -) - -var ( - encFields = []struct { - prefix string - value func(Event) string - }{ - {"id: ", Event.Id}, - {"event: ", Event.Event}, - {"data: ", Event.Data}, - } -) - -// An Encoder is capable of writing Events to a stream. Optionally -// Events can be gzip compressed in this process. -type Encoder struct { - w io.Writer - compressed bool -} - -// NewEncoder returns an Encoder for a given io.Writer. -// When compressed is set to true, a gzip writer will be -// created. -func NewEncoder(w io.Writer, compressed bool) *Encoder { - if compressed { - return &Encoder{w: gzip.NewWriter(w), compressed: true} - } - return &Encoder{w: w} -} - -// Encode writes an event in the format specified by the -// server-sent events protocol. -func (enc *Encoder) Encode(ev Event) error { - for _, field := range encFields { - prefix, value := field.prefix, field.value(ev) - if len(value) == 0 { - continue - } - value = strings.Replace(value, "\n", "\n"+prefix, -1) - if _, err := io.WriteString(enc.w, prefix+value+"\n"); err != nil { - return fmt.Errorf("eventsource encode: %v", err) - } - } - if _, err := io.WriteString(enc.w, "\n"); err != nil { - return fmt.Errorf("eventsource encode: %v", err) - } - if enc.compressed { - return enc.w.(*gzip.Writer).Flush() - } - return nil -} diff --git a/vendor/github.com/donovanhide/eventsource/interface.go b/vendor/github.com/donovanhide/eventsource/interface.go deleted file mode 100644 index b8b2cd44b..000000000 --- a/vendor/github.com/donovanhide/eventsource/interface.go +++ /dev/null @@ -1,25 +0,0 @@ -// Package eventsource implements a client and server to allow streaming data one-way over a HTTP connection -// using the Server-Sent Events API http://dev.w3.org/html5/eventsource/ -// -// The client and server respect the Last-Event-ID header. -// If the Repository interface is implemented on the server, events can be replayed in case of a network disconnection. -package eventsource - -// Any event received by the client or sent by the server will implement this interface -type Event interface { - // Id is an identifier that can be used to allow a client to replay - // missed Events by returning the Last-Event-Id header. - // Return empty string if not required. - Id() string - // The name of the event. Return empty string if not required. - Event() string - // The payload of the event. - Data() string -} - -// If history is required, this interface will allow clients to reply previous events through the server. -// Both methods can be called from different goroutines concurrently, so you must make sure they are go-routine safe. -type Repository interface { - // Gets the Events which should follow on from the specified channel and event id. - Replay(channel, id string) chan Event -} diff --git a/vendor/github.com/donovanhide/eventsource/normalise.go b/vendor/github.com/donovanhide/eventsource/normalise.go deleted file mode 100644 index 3072ab692..000000000 --- a/vendor/github.com/donovanhide/eventsource/normalise.go +++ /dev/null @@ -1,35 +0,0 @@ -package eventsource - -import ( - "io" -) - -// A reader which normalises line endings -// "/r" and "/r/n" are converted to "/n" -type normaliser struct { - r io.Reader - lastChar byte -} - -func newNormaliser(r io.Reader) *normaliser { - return &normaliser{r: r} -} - -func (norm *normaliser) Read(p []byte) (n int, err error) { - n, err = norm.r.Read(p) - for i := 0; i < n; i++ { - switch { - case p[i] == '\n' && norm.lastChar == '\r': - copy(p[i:n], p[i+1:]) - norm.lastChar = p[i] - n-- - i-- - case p[i] == '\r': - norm.lastChar = p[i] - p[i] = '\n' - default: - norm.lastChar = p[i] - } - } - return -} diff --git a/vendor/github.com/donovanhide/eventsource/repository.go b/vendor/github.com/donovanhide/eventsource/repository.go deleted file mode 100644 index 9dd865162..000000000 --- a/vendor/github.com/donovanhide/eventsource/repository.go +++ /dev/null @@ -1,50 +0,0 @@ -package eventsource - -import ( - "sort" - "sync" -) - -// Example repository that uses a slice as storage for past events. -type SliceRepository struct { - events map[string][]Event - lock sync.RWMutex -} - -func NewSliceRepository() *SliceRepository { - return &SliceRepository{ - events: make(map[string][]Event), - } -} - -func (repo SliceRepository) indexOfEvent(channel, id string) int { - return sort.Search(len(repo.events[channel]), func(i int) bool { - return repo.events[channel][i].Id() >= id - }) -} - -func (repo SliceRepository) Replay(channel, id string) (out chan Event) { - out = make(chan Event) - go func() { - defer close(out) - repo.lock.RLock() - defer repo.lock.RUnlock() - events := repo.events[channel][repo.indexOfEvent(channel, id):] - for i := range events { - out <- events[i] - } - }() - return -} - -func (repo *SliceRepository) Add(channel string, event Event) { - repo.lock.Lock() - defer repo.lock.Unlock() - i := repo.indexOfEvent(channel, event.Id()) - if i < len(repo.events[channel]) && repo.events[channel][i].Id() == event.Id() { - repo.events[channel][i] = event - } else { - repo.events[channel] = append(repo.events[channel][:i], append([]Event{event}, repo.events[channel][i:]...)...) - } - return -} diff --git a/vendor/github.com/donovanhide/eventsource/server.go b/vendor/github.com/donovanhide/eventsource/server.go deleted file mode 100644 index 82cee69dd..000000000 --- a/vendor/github.com/donovanhide/eventsource/server.go +++ /dev/null @@ -1,189 +0,0 @@ -package eventsource - -import ( - "log" - "net/http" - "strings" - "sync" -) - -type subscription struct { - channel string - lastEventId string - out chan Event -} - -type outbound struct { - channels []string - event Event -} -type registration struct { - channel string - repository Repository -} - -type Server struct { - AllowCORS bool // Enable all handlers to be accessible from any origin - ReplayAll bool // Replay repository even if there's no Last-Event-Id specified - BufferSize int // How many messages do we let the client get behind before disconnecting - Gzip bool // Enable compression if client can accept it - Logger *log.Logger // Logger is a logger that, when set, will be used for logging debug messages - registrations chan *registration - pub chan *outbound - subs chan *subscription - unregister chan *subscription - quit chan bool - isClosed bool - isClosedMutex sync.RWMutex -} - -// Create a new Server ready for handler creation and publishing events -func NewServer() *Server { - srv := &Server{ - registrations: make(chan *registration), - pub: make(chan *outbound), - subs: make(chan *subscription), - unregister: make(chan *subscription, 2), - quit: make(chan bool), - BufferSize: 128, - } - go srv.run() - return srv -} - -// Stop handling publishing -func (srv *Server) Close() { - srv.quit <- true - srv.markServerClosed() -} - -// Create a new handler for serving a specified channel -func (srv *Server) Handler(channel string) http.HandlerFunc { - return func(w http.ResponseWriter, req *http.Request) { - h := w.Header() - h.Set("Content-Type", "text/event-stream; charset=utf-8") - h.Set("Cache-Control", "no-cache, no-store, must-revalidate") - h.Set("Connection", "keep-alive") - if srv.AllowCORS { - h.Set("Access-Control-Allow-Origin", "*") - } - useGzip := srv.Gzip && strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") - if useGzip { - h.Set("Content-Encoding", "gzip") - } - w.WriteHeader(http.StatusOK) - - // If the Handler is still active even though the server is closed, stop here. - // Otherwise the Handler will block while publishing to srv.subs indefinitely. - if srv.isServerClosed() { - return - } - - sub := &subscription{ - channel: channel, - lastEventId: req.Header.Get("Last-Event-ID"), - out: make(chan Event, srv.BufferSize), - } - srv.subs <- sub - flusher := w.(http.Flusher) - notifier := w.(http.CloseNotifier) - flusher.Flush() - enc := NewEncoder(w, useGzip) - for { - select { - case <-notifier.CloseNotify(): - srv.unregister <- sub - return - case ev, ok := <-sub.out: - if !ok { - return - } - if err := enc.Encode(ev); err != nil { - srv.unregister <- sub - if srv.Logger != nil { - srv.Logger.Println(err) - } - return - } - flusher.Flush() - } - } - } -} - -// Register the repository to be used for the specified channel -func (srv *Server) Register(channel string, repo Repository) { - srv.registrations <- ®istration{ - channel: channel, - repository: repo, - } -} - -// Publish an event with the specified id to one or more channels -func (srv *Server) Publish(channels []string, ev Event) { - srv.pub <- &outbound{ - channels: channels, - event: ev, - } -} - -func replay(repo Repository, sub *subscription) { - for ev := range repo.Replay(sub.channel, sub.lastEventId) { - sub.out <- ev - } -} - -func (srv *Server) run() { - subs := make(map[string]map[*subscription]struct{}) - repos := make(map[string]Repository) - for { - select { - case reg := <-srv.registrations: - repos[reg.channel] = reg.repository - case sub := <-srv.unregister: - delete(subs[sub.channel], sub) - case pub := <-srv.pub: - for _, c := range pub.channels { - for s := range subs[c] { - select { - case s.out <- pub.event: - default: - srv.unregister <- s - close(s.out) - } - - } - } - case sub := <-srv.subs: - if _, ok := subs[sub.channel]; !ok { - subs[sub.channel] = make(map[*subscription]struct{}) - } - subs[sub.channel][sub] = struct{}{} - if srv.ReplayAll || len(sub.lastEventId) > 0 { - repo, ok := repos[sub.channel] - if ok { - go replay(repo, sub) - } - } - case <-srv.quit: - for _, sub := range subs { - for s := range sub { - close(s.out) - } - } - return - } - } -} - -func (srv *Server) isServerClosed() bool { - srv.isClosedMutex.RLock() - defer srv.isClosedMutex.RUnlock() - return srv.isClosed -} - -func (srv *Server) markServerClosed() { - srv.isClosedMutex.Lock() - defer srv.isClosedMutex.Unlock() - srv.isClosed = true -} diff --git a/vendor/github.com/donovanhide/eventsource/stream.go b/vendor/github.com/donovanhide/eventsource/stream.go deleted file mode 100644 index 597087701..000000000 --- a/vendor/github.com/donovanhide/eventsource/stream.go +++ /dev/null @@ -1,196 +0,0 @@ -package eventsource - -import ( - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net/http" - "sync" - "time" -) - -// Stream handles a connection for receiving Server Sent Events. -// It will try and reconnect if the connection is lost, respecting both -// received retry delays and event id's. -type Stream struct { - c *http.Client - req *http.Request - lastEventId string - retry time.Duration - // Events emits the events received by the stream - Events chan Event - // Errors emits any errors encountered while reading events from the stream. - // It's mainly for informative purposes - the client isn't required to take any - // action when an error is encountered. The stream will always attempt to continue, - // even if that involves reconnecting to the server. - Errors chan error - // Logger is a logger that, when set, will be used for logging debug messages - Logger *log.Logger - // isClosed is a marker that the stream is/should be closed - isClosed bool - // isClosedMutex is a mutex protecting concurrent read/write access of isClosed - isClosedMutex sync.RWMutex -} - -type SubscriptionError struct { - Code int - Message string -} - -func (e SubscriptionError) Error() string { - return fmt.Sprintf("%d: %s", e.Code, e.Message) -} - -// Subscribe to the Events emitted from the specified url. -// If lastEventId is non-empty it will be sent to the server in case it can replay missed events. -func Subscribe(url, lastEventId string) (*Stream, error) { - req, err := http.NewRequest("GET", url, nil) - if err != nil { - return nil, err - } - return SubscribeWithRequest(lastEventId, req) -} - -// SubscribeWithRequest will take an http.Request to setup the stream, allowing custom headers -// to be specified, authentication to be configured, etc. -func SubscribeWithRequest(lastEventId string, request *http.Request) (*Stream, error) { - return SubscribeWith(lastEventId, http.DefaultClient, request) -} - -// SubscribeWith takes a http client and request providing customization over both headers and -// control over the http client settings (timeouts, tls, etc) -func SubscribeWith(lastEventId string, client *http.Client, request *http.Request) (*Stream, error) { - stream := &Stream{ - c: client, - req: request, - lastEventId: lastEventId, - retry: time.Millisecond * 3000, - Events: make(chan Event), - Errors: make(chan error), - } - stream.c.CheckRedirect = checkRedirect - - r, err := stream.connect() - if err != nil { - return nil, err - } - go stream.stream(r) - return stream, nil -} - -// Close will close the stream. It is safe for concurrent access and can be called multiple times. -func (stream *Stream) Close() { - if stream.isStreamClosed() { - return - } - - stream.markStreamClosed() - close(stream.Errors) - close(stream.Events) -} - -func (stream *Stream) isStreamClosed() bool { - stream.isClosedMutex.RLock() - defer stream.isClosedMutex.RUnlock() - return stream.isClosed -} - -func (stream *Stream) markStreamClosed() { - stream.isClosedMutex.Lock() - defer stream.isClosedMutex.Unlock() - stream.isClosed = true -} - -// Go's http package doesn't copy headers across when it encounters -// redirects so we need to do that manually. -func checkRedirect(req *http.Request, via []*http.Request) error { - if len(via) >= 10 { - return errors.New("stopped after 10 redirects") - } - for k, vv := range via[0].Header { - for _, v := range vv { - req.Header.Add(k, v) - } - } - return nil -} - -func (stream *Stream) connect() (r io.ReadCloser, err error) { - var resp *http.Response - stream.req.Header.Set("Cache-Control", "no-cache") - stream.req.Header.Set("Accept", "text/event-stream") - if len(stream.lastEventId) > 0 { - stream.req.Header.Set("Last-Event-ID", stream.lastEventId) - } - if resp, err = stream.c.Do(stream.req); err != nil { - return - } - if resp.StatusCode != 200 { - message, _ := ioutil.ReadAll(resp.Body) - err = SubscriptionError{ - Code: resp.StatusCode, - Message: string(message), - } - } - r = resp.Body - return -} - -func (stream *Stream) stream(r io.ReadCloser) { - defer r.Close() - - // receives events until an error is encountered - stream.receiveEvents(r) - - // tries to reconnect and start the stream again - stream.retryRestartStream() -} - -func (stream *Stream) receiveEvents(r io.ReadCloser) { - dec := NewDecoder(r) - - for { - ev, err := dec.Decode() - if stream.isStreamClosed() { - return - } - if err != nil { - stream.Errors <- err - return - } - - pub := ev.(*publication) - if pub.Retry() > 0 { - stream.retry = time.Duration(pub.Retry()) * time.Millisecond - } - if len(pub.Id()) > 0 { - stream.lastEventId = pub.Id() - } - stream.Events <- ev - } -} - -func (stream *Stream) retryRestartStream() { - backoff := stream.retry - for { - if stream.Logger != nil { - stream.Logger.Printf("Reconnecting in %0.4f secs\n", backoff.Seconds()) - } - time.Sleep(backoff) - if stream.isStreamClosed() { - return - } - // NOTE: because of the defer we're opening the new connection - // before closing the old one. Shouldn't be a problem in practice, - // but something to be aware of. - r, err := stream.connect() - if err == nil { - go stream.stream(r) - return - } - stream.Errors <- err - backoff *= 2 - } -} diff --git a/vendor/github.com/eapache/channels/LICENSE b/vendor/github.com/eapache/channels/LICENSE deleted file mode 100644 index 8c4bddf75..000000000 --- a/vendor/github.com/eapache/channels/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Evan Huus - -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/eapache/channels/batching_channel.go b/vendor/github.com/eapache/channels/batching_channel.go deleted file mode 100644 index 5be622f2f..000000000 --- a/vendor/github.com/eapache/channels/batching_channel.go +++ /dev/null @@ -1,87 +0,0 @@ -package channels - -// BatchingChannel implements the Channel interface, with the change that instead of producing individual elements -// on Out(), it batches together the entire internal buffer each time. Trying to construct an unbuffered batching channel -// will panic, that configuration is not supported (and provides no benefit over an unbuffered NativeChannel). -type BatchingChannel struct { - input, output chan interface{} - length chan int - buffer []interface{} - size BufferCap -} - -func NewBatchingChannel(size BufferCap) *BatchingChannel { - if size == None { - panic("channels: BatchingChannel does not support unbuffered behaviour") - } - if size < 0 && size != Infinity { - panic("channels: invalid negative size in NewBatchingChannel") - } - ch := &BatchingChannel{ - input: make(chan interface{}), - output: make(chan interface{}), - length: make(chan int), - size: size, - } - go ch.batchingBuffer() - return ch -} - -func (ch *BatchingChannel) In() chan<- interface{} { - return ch.input -} - -// Out returns a <-chan interface{} in order that BatchingChannel conforms to the standard Channel interface provided -// by this package, however each output value is guaranteed to be of type []interface{} - a slice collecting the most -// recent batch of values sent on the In channel. The slice is guaranteed to not be empty or nil. In practice the net -// result is that you need an additional type assertion to access the underlying values. -func (ch *BatchingChannel) Out() <-chan interface{} { - return ch.output -} - -func (ch *BatchingChannel) Len() int { - return <-ch.length -} - -func (ch *BatchingChannel) Cap() BufferCap { - return ch.size -} - -func (ch *BatchingChannel) Close() { - close(ch.input) -} - -func (ch *BatchingChannel) batchingBuffer() { - var input, output, nextInput chan interface{} - nextInput = ch.input - input = nextInput - - for input != nil || output != nil { - select { - case elem, open := <-input: - if open { - ch.buffer = append(ch.buffer, elem) - } else { - input = nil - nextInput = nil - } - case output <- ch.buffer: - ch.buffer = nil - case ch.length <- len(ch.buffer): - } - - if len(ch.buffer) == 0 { - input = nextInput - output = nil - } else if ch.size != Infinity && len(ch.buffer) >= int(ch.size) { - input = nil - output = ch.output - } else { - input = nextInput - output = ch.output - } - } - - close(ch.output) - close(ch.length) -} diff --git a/vendor/github.com/eapache/channels/black_hole.go b/vendor/github.com/eapache/channels/black_hole.go deleted file mode 100644 index 0d1ba97b3..000000000 --- a/vendor/github.com/eapache/channels/black_hole.go +++ /dev/null @@ -1,54 +0,0 @@ -package channels - -// BlackHole implements the InChannel interface and provides an analogue for the "Discard" variable in -// the ioutil package - it never blocks, and simply discards every value it reads. The number of items -// discarded in this way is counted and returned from Len. -type BlackHole struct { - input chan interface{} - length chan int - count int -} - -func NewBlackHole() *BlackHole { - ch := &BlackHole{ - input: make(chan interface{}), - length: make(chan int), - } - go ch.discard() - return ch -} - -func (ch *BlackHole) In() chan<- interface{} { - return ch.input -} - -func (ch *BlackHole) Len() int { - val, open := <-ch.length - if open { - return val - } else { - return ch.count - } -} - -func (ch *BlackHole) Cap() BufferCap { - return Infinity -} - -func (ch *BlackHole) Close() { - close(ch.input) -} - -func (ch *BlackHole) discard() { - for { - select { - case _, open := <-ch.input: - if !open { - close(ch.length) - return - } - ch.count++ - case ch.length <- ch.count: - } - } -} diff --git a/vendor/github.com/eapache/channels/channels.go b/vendor/github.com/eapache/channels/channels.go deleted file mode 100644 index efcb2b5c5..000000000 --- a/vendor/github.com/eapache/channels/channels.go +++ /dev/null @@ -1,277 +0,0 @@ -/* -Package channels provides a collection of helper functions, interfaces and implementations for -working with and extending the capabilities of golang's existing channels. The main interface of -interest is Channel, though sub-interfaces are also provided for cases where the full Channel interface -cannot be met (for example, InChannel for write-only channels). - -For integration with native typed golang channels, functions Wrap and Unwrap are provided which do the -appropriate type conversions. The NativeChannel, NativeInChannel and NativeOutChannel type definitions -are also provided for use with native channels which already carry values of type interface{}. - -The heart of the package consists of several distinct implementations of the Channel interface, including -channels backed by special buffers (resizable, infinite, ring buffers, etc) and other useful types. A -"black hole" channel for discarding unwanted values (similar in purpose to ioutil.Discard or /dev/null) -rounds out the set. - -Helper functions for operating on Channels include Pipe and Tee (which behave much like their Unix -namesakes), as well as Multiplex and Distribute. "Weak" versions of these functions also exist, which -do not close their output channel(s) on completion. - -Due to limitations of Go's type system, importing this library directly is often not practical for -production code. It serves equally well, however, as a reference guide and template for implementing -many common idioms; if you use it in this way I would appreciate the inclusion of some sort of credit -in the resulting code. - -Warning: several types in this package provide so-called "infinite" buffers. Be *very* careful using -these, as no buffer is truly infinite - if such a buffer grows too large your program will run out of -memory and crash. Caveat emptor. -*/ -package channels - -import "reflect" - -// BufferCap represents the capacity of the buffer backing a channel. Valid values consist of all -// positive integers, as well as the special values below. -type BufferCap int - -const ( - // None is the capacity for channels that have no buffer at all. - None BufferCap = 0 - // Infinity is the capacity for channels with no limit on their buffer size. - Infinity BufferCap = -1 -) - -// Buffer is an interface for any channel that provides access to query the state of its buffer. -// Even unbuffered channels can implement this interface by simply returning 0 from Len() and None from Cap(). -type Buffer interface { - Len() int // The number of elements currently buffered. - Cap() BufferCap // The maximum number of elements that can be buffered. -} - -// SimpleInChannel is an interface representing a writeable channel that does not necessarily -// implement the Buffer interface. -type SimpleInChannel interface { - In() chan<- interface{} // The writeable end of the channel. - Close() // Closes the channel. It is an error to write to In() after calling Close(). -} - -// InChannel is an interface representing a writeable channel with a buffer. -type InChannel interface { - SimpleInChannel - Buffer -} - -// SimpleOutChannel is an interface representing a readable channel that does not necessarily -// implement the Buffer interface. -type SimpleOutChannel interface { - Out() <-chan interface{} // The readable end of the channel. -} - -// OutChannel is an interface representing a readable channel implementing the Buffer interface. -type OutChannel interface { - SimpleOutChannel - Buffer -} - -// SimpleChannel is an interface representing a channel that is both readable and writeable, -// but does not necessarily implement the Buffer interface. -type SimpleChannel interface { - SimpleInChannel - SimpleOutChannel -} - -// Channel is an interface representing a channel that is readable, writeable and implements -// the Buffer interface -type Channel interface { - SimpleChannel - Buffer -} - -func pipe(input SimpleOutChannel, output SimpleInChannel, closeWhenDone bool) { - for elem := range input.Out() { - output.In() <- elem - } - if closeWhenDone { - output.Close() - } -} - -func multiplex(output SimpleInChannel, inputs []SimpleOutChannel, closeWhenDone bool) { - inputCount := len(inputs) - cases := make([]reflect.SelectCase, inputCount) - for i := range cases { - cases[i].Dir = reflect.SelectRecv - cases[i].Chan = reflect.ValueOf(inputs[i].Out()) - } - for inputCount > 0 { - chosen, recv, recvOK := reflect.Select(cases) - if recvOK { - output.In() <- recv.Interface() - } else { - cases[chosen].Chan = reflect.ValueOf(nil) - inputCount-- - } - } - if closeWhenDone { - output.Close() - } -} - -func tee(input SimpleOutChannel, outputs []SimpleInChannel, closeWhenDone bool) { - cases := make([]reflect.SelectCase, len(outputs)) - for i := range cases { - cases[i].Dir = reflect.SelectSend - } - for elem := range input.Out() { - for i := range cases { - cases[i].Chan = reflect.ValueOf(outputs[i].In()) - cases[i].Send = reflect.ValueOf(elem) - } - for _ = range cases { - chosen, _, _ := reflect.Select(cases) - cases[chosen].Chan = reflect.ValueOf(nil) - } - } - if closeWhenDone { - for i := range outputs { - outputs[i].Close() - } - } -} - -func distribute(input SimpleOutChannel, outputs []SimpleInChannel, closeWhenDone bool) { - cases := make([]reflect.SelectCase, len(outputs)) - for i := range cases { - cases[i].Dir = reflect.SelectSend - cases[i].Chan = reflect.ValueOf(outputs[i].In()) - } - for elem := range input.Out() { - for i := range cases { - cases[i].Send = reflect.ValueOf(elem) - } - reflect.Select(cases) - } - if closeWhenDone { - for i := range outputs { - outputs[i].Close() - } - } -} - -// Pipe connects the input channel to the output channel so that -// they behave as if a single channel. -func Pipe(input SimpleOutChannel, output SimpleInChannel) { - go pipe(input, output, true) -} - -// Multiplex takes an arbitrary number of input channels and multiplexes their output into a single output -// channel. When all input channels have been closed, the output channel is closed. Multiplex with a single -// input channel is equivalent to Pipe (though slightly less efficient). -func Multiplex(output SimpleInChannel, inputs ...SimpleOutChannel) { - if len(inputs) == 0 { - panic("channels: Multiplex requires at least one input") - } - go multiplex(output, inputs, true) -} - -// Tee (like its Unix namesake) takes a single input channel and an arbitrary number of output channels -// and duplicates each input into every output. When the input channel is closed, all outputs channels are closed. -// Tee with a single output channel is equivalent to Pipe (though slightly less efficient). -func Tee(input SimpleOutChannel, outputs ...SimpleInChannel) { - if len(outputs) == 0 { - panic("channels: Tee requires at least one output") - } - go tee(input, outputs, true) -} - -// Distribute takes a single input channel and an arbitrary number of output channels and duplicates each input -// into *one* available output. If multiple outputs are waiting for a value, one is chosen at random. When the -// input channel is closed, all outputs channels are closed. Distribute with a single output channel is -// equivalent to Pipe (though slightly less efficient). -func Distribute(input SimpleOutChannel, outputs ...SimpleInChannel) { - if len(outputs) == 0 { - panic("channels: Distribute requires at least one output") - } - go distribute(input, outputs, true) -} - -// WeakPipe behaves like Pipe (connecting the two channels) except that it does not close -// the output channel when the input channel is closed. -func WeakPipe(input SimpleOutChannel, output SimpleInChannel) { - go pipe(input, output, false) -} - -// WeakMultiplex behaves like Multiplex (multiplexing multiple inputs into a single output) except that it does not close -// the output channel when the input channels are closed. -func WeakMultiplex(output SimpleInChannel, inputs ...SimpleOutChannel) { - if len(inputs) == 0 { - panic("channels: WeakMultiplex requires at least one input") - } - go multiplex(output, inputs, false) -} - -// WeakTee behaves like Tee (duplicating a single input into multiple outputs) except that it does not close -// the output channels when the input channel is closed. -func WeakTee(input SimpleOutChannel, outputs ...SimpleInChannel) { - if len(outputs) == 0 { - panic("channels: WeakTee requires at least one output") - } - go tee(input, outputs, false) -} - -// WeakDistribute behaves like Distribute (distributing a single input amongst multiple outputs) except that -// it does not close the output channels when the input channel is closed. -func WeakDistribute(input SimpleOutChannel, outputs ...SimpleInChannel) { - if len(outputs) == 0 { - panic("channels: WeakDistribute requires at least one output") - } - go distribute(input, outputs, false) -} - -// Wrap takes any readable channel type (chan or <-chan but not chan<-) and -// exposes it as a SimpleOutChannel for easy integration with existing channel sources. -// It panics if the input is not a readable channel. -func Wrap(ch interface{}) SimpleOutChannel { - t := reflect.TypeOf(ch) - if t.Kind() != reflect.Chan || t.ChanDir()&reflect.RecvDir == 0 { - panic("channels: input to Wrap must be readable channel") - } - realChan := make(chan interface{}) - - go func() { - v := reflect.ValueOf(ch) - for { - x, ok := v.Recv() - if !ok { - close(realChan) - return - } - realChan <- x.Interface() - } - }() - - return NativeOutChannel(realChan) -} - -// Unwrap takes a SimpleOutChannel and uses reflection to pipe it to a typed native channel for -// easy integration with existing channel sources. Output can be any writable channel type (chan or chan<-). -// It panics if the output is not a writable channel, or if a value is received that cannot be sent on the -// output channel. -func Unwrap(input SimpleOutChannel, output interface{}) { - t := reflect.TypeOf(output) - if t.Kind() != reflect.Chan || t.ChanDir()&reflect.SendDir == 0 { - panic("channels: input to Unwrap must be readable channel") - } - - go func() { - v := reflect.ValueOf(output) - for { - x, ok := <-input.Out() - if !ok { - v.Close() - return - } - v.Send(reflect.ValueOf(x)) - } - }() -} diff --git a/vendor/github.com/eapache/channels/infinite_channel.go b/vendor/github.com/eapache/channels/infinite_channel.go deleted file mode 100644 index 3aa9e8e7e..000000000 --- a/vendor/github.com/eapache/channels/infinite_channel.go +++ /dev/null @@ -1,72 +0,0 @@ -package channels - -import "github.com/eapache/queue" - -// InfiniteChannel implements the Channel interface with an infinite buffer between the input and the output. -type InfiniteChannel struct { - input, output chan interface{} - length chan int - buffer *queue.Queue -} - -func NewInfiniteChannel() *InfiniteChannel { - ch := &InfiniteChannel{ - input: make(chan interface{}), - output: make(chan interface{}), - length: make(chan int), - buffer: queue.New(), - } - go ch.infiniteBuffer() - return ch -} - -func (ch *InfiniteChannel) In() chan<- interface{} { - return ch.input -} - -func (ch *InfiniteChannel) Out() <-chan interface{} { - return ch.output -} - -func (ch *InfiniteChannel) Len() int { - return <-ch.length -} - -func (ch *InfiniteChannel) Cap() BufferCap { - return Infinity -} - -func (ch *InfiniteChannel) Close() { - close(ch.input) -} - -func (ch *InfiniteChannel) infiniteBuffer() { - var input, output chan interface{} - var next interface{} - input = ch.input - - for input != nil || output != nil { - select { - case elem, open := <-input: - if open { - ch.buffer.Add(elem) - } else { - input = nil - } - case output <- next: - ch.buffer.Remove() - case ch.length <- ch.buffer.Length(): - } - - if ch.buffer.Length() > 0 { - output = ch.output - next = ch.buffer.Peek() - } else { - output = nil - next = nil - } - } - - close(ch.output) - close(ch.length) -} diff --git a/vendor/github.com/eapache/channels/native_channel.go b/vendor/github.com/eapache/channels/native_channel.go deleted file mode 100644 index 3807a1991..000000000 --- a/vendor/github.com/eapache/channels/native_channel.go +++ /dev/null @@ -1,92 +0,0 @@ -package channels - -// NativeInChannel implements the InChannel interface by wrapping a native go write-only channel. -type NativeInChannel chan<- interface{} - -func (ch NativeInChannel) In() chan<- interface{} { - return ch -} - -func (ch NativeInChannel) Len() int { - return len(ch) -} - -func (ch NativeInChannel) Cap() BufferCap { - return BufferCap(cap(ch)) -} - -func (ch NativeInChannel) Close() { - close(ch) -} - -// NativeOutChannel implements the OutChannel interface by wrapping a native go read-only channel. -type NativeOutChannel <-chan interface{} - -func (ch NativeOutChannel) Out() <-chan interface{} { - return ch -} - -func (ch NativeOutChannel) Len() int { - return len(ch) -} - -func (ch NativeOutChannel) Cap() BufferCap { - return BufferCap(cap(ch)) -} - -// NativeChannel implements the Channel interface by wrapping a native go channel. -type NativeChannel chan interface{} - -// NewNativeChannel makes a new NativeChannel with the given buffer size. Just a convenience wrapper -// to avoid having to cast the result of make(). -func NewNativeChannel(size BufferCap) NativeChannel { - return make(chan interface{}, size) -} - -func (ch NativeChannel) In() chan<- interface{} { - return ch -} - -func (ch NativeChannel) Out() <-chan interface{} { - return ch -} - -func (ch NativeChannel) Len() int { - return len(ch) -} - -func (ch NativeChannel) Cap() BufferCap { - return BufferCap(cap(ch)) -} - -func (ch NativeChannel) Close() { - close(ch) -} - -// DeadChannel is a placeholder implementation of the Channel interface with no buffer -// that is never ready for reading or writing. Closing a dead channel is a no-op. -// Behaves almost like NativeChannel(nil) except that closing a nil NativeChannel will panic. -type DeadChannel struct{} - -func NewDeadChannel() DeadChannel { - return DeadChannel{} -} - -func (ch DeadChannel) In() chan<- interface{} { - return nil -} - -func (ch DeadChannel) Out() <-chan interface{} { - return nil -} - -func (ch DeadChannel) Len() int { - return 0 -} - -func (ch DeadChannel) Cap() BufferCap { - return BufferCap(0) -} - -func (ch DeadChannel) Close() { -} diff --git a/vendor/github.com/eapache/channels/overflowing_channel.go b/vendor/github.com/eapache/channels/overflowing_channel.go deleted file mode 100644 index 35090f8e8..000000000 --- a/vendor/github.com/eapache/channels/overflowing_channel.go +++ /dev/null @@ -1,113 +0,0 @@ -package channels - -import "github.com/eapache/queue" - -// OverflowingChannel implements the Channel interface in a way that never blocks the writer. -// Specifically, if a value is written to an OverflowingChannel when its buffer is full -// (or, in an unbuffered case, when the recipient is not ready) then that value is simply discarded. -// Note that Go's scheduler can cause discarded values when they could be avoided, simply by scheduling -// the writer before the reader, so caveat emptor. -// For the opposite behaviour (discarding the oldest element, not the newest) see RingChannel. -type OverflowingChannel struct { - input, output chan interface{} - length chan int - buffer *queue.Queue - size BufferCap -} - -func NewOverflowingChannel(size BufferCap) *OverflowingChannel { - if size < 0 && size != Infinity { - panic("channels: invalid negative size in NewOverflowingChannel") - } - ch := &OverflowingChannel{ - input: make(chan interface{}), - output: make(chan interface{}), - length: make(chan int), - size: size, - } - if size == None { - go ch.overflowingDirect() - } else { - ch.buffer = queue.New() - go ch.overflowingBuffer() - } - return ch -} - -func (ch *OverflowingChannel) In() chan<- interface{} { - return ch.input -} - -func (ch *OverflowingChannel) Out() <-chan interface{} { - return ch.output -} - -func (ch *OverflowingChannel) Len() int { - if ch.size == None { - return 0 - } else { - return <-ch.length - } -} - -func (ch *OverflowingChannel) Cap() BufferCap { - return ch.size -} - -func (ch *OverflowingChannel) Close() { - close(ch.input) -} - -// for entirely unbuffered cases -func (ch *OverflowingChannel) overflowingDirect() { - for elem := range ch.input { - // if we can't write it immediately, drop it and move on - select { - case ch.output <- elem: - default: - } - } - close(ch.output) -} - -// for all buffered cases -func (ch *OverflowingChannel) overflowingBuffer() { - var input, output chan interface{} - var next interface{} - input = ch.input - - for input != nil || output != nil { - select { - // Prefer to write if possible, which is surprisingly effective in reducing - // dropped elements due to overflow. The naive read/write select chooses randomly - // when both channels are ready, which produces unnecessary drops 50% of the time. - case output <- next: - ch.buffer.Remove() - default: - select { - case elem, open := <-input: - if open { - if ch.size == Infinity || ch.buffer.Length() < int(ch.size) { - ch.buffer.Add(elem) - } - } else { - input = nil - } - case output <- next: - ch.buffer.Remove() - case ch.length <- ch.buffer.Length(): - } - } - - if ch.buffer.Length() > 0 { - output = ch.output - next = ch.buffer.Peek() - } else { - output = nil - next = nil - } - } - - close(ch.output) - close(ch.length) -} diff --git a/vendor/github.com/eapache/channels/resizable_channel.go b/vendor/github.com/eapache/channels/resizable_channel.go deleted file mode 100644 index fafed0a29..000000000 --- a/vendor/github.com/eapache/channels/resizable_channel.go +++ /dev/null @@ -1,109 +0,0 @@ -package channels - -import "github.com/eapache/queue" - -// ResizableChannel implements the Channel interface with a resizable buffer between the input and the output. -// The channel initially has a buffer size of 1, but can be resized by calling Resize(). -// -// Resizing to a buffer capacity of None is, unfortunately, not supported and will panic -// (see https://github.com/eapache/channels/issues/1). -// Resizing back and forth between a finite and infinite buffer is fully supported. -type ResizableChannel struct { - input, output chan interface{} - length chan int - capacity, resize chan BufferCap - size BufferCap - buffer *queue.Queue -} - -func NewResizableChannel() *ResizableChannel { - ch := &ResizableChannel{ - input: make(chan interface{}), - output: make(chan interface{}), - length: make(chan int), - capacity: make(chan BufferCap), - resize: make(chan BufferCap), - size: 1, - buffer: queue.New(), - } - go ch.magicBuffer() - return ch -} - -func (ch *ResizableChannel) In() chan<- interface{} { - return ch.input -} - -func (ch *ResizableChannel) Out() <-chan interface{} { - return ch.output -} - -func (ch *ResizableChannel) Len() int { - return <-ch.length -} - -func (ch *ResizableChannel) Cap() BufferCap { - val, open := <-ch.capacity - if open { - return val - } else { - return ch.size - } -} - -func (ch *ResizableChannel) Close() { - close(ch.input) -} - -func (ch *ResizableChannel) Resize(newSize BufferCap) { - if newSize == None { - panic("channels: ResizableChannel does not support unbuffered behaviour") - } - if newSize < 0 && newSize != Infinity { - panic("channels: invalid negative size trying to resize channel") - } - ch.resize <- newSize -} - -func (ch *ResizableChannel) magicBuffer() { - var input, output, nextInput chan interface{} - var next interface{} - nextInput = ch.input - input = nextInput - - for input != nil || output != nil { - select { - case elem, open := <-input: - if open { - ch.buffer.Add(elem) - } else { - input = nil - nextInput = nil - } - case output <- next: - ch.buffer.Remove() - case ch.size = <-ch.resize: - case ch.length <- ch.buffer.Length(): - case ch.capacity <- ch.size: - } - - if ch.buffer.Length() == 0 { - output = nil - next = nil - } else { - output = ch.output - next = ch.buffer.Peek() - } - - if ch.size != Infinity && ch.buffer.Length() >= int(ch.size) { - input = nil - } else { - input = nextInput - } - } - - close(ch.output) - close(ch.resize) - close(ch.length) - close(ch.capacity) -} diff --git a/vendor/github.com/eapache/channels/ring_channel.go b/vendor/github.com/eapache/channels/ring_channel.go deleted file mode 100644 index 7aec207bd..000000000 --- a/vendor/github.com/eapache/channels/ring_channel.go +++ /dev/null @@ -1,114 +0,0 @@ -package channels - -import "github.com/eapache/queue" - -// RingChannel implements the Channel interface in a way that never blocks the writer. -// Specifically, if a value is written to a RingChannel when its buffer is full then the oldest -// value in the buffer is discarded to make room (just like a standard ring-buffer). -// Note that Go's scheduler can cause discarded values when they could be avoided, simply by scheduling -// the writer before the reader, so caveat emptor. -// For the opposite behaviour (discarding the newest element, not the oldest) see OverflowingChannel. -type RingChannel struct { - input, output chan interface{} - length chan int - buffer *queue.Queue - size BufferCap -} - -func NewRingChannel(size BufferCap) *RingChannel { - if size < 0 && size != Infinity { - panic("channels: invalid negative size in NewRingChannel") - } - ch := &RingChannel{ - input: make(chan interface{}), - output: make(chan interface{}), - buffer: queue.New(), - size: size, - } - if size == None { - go ch.overflowingDirect() - } else { - ch.length = make(chan int) - go ch.ringBuffer() - } - return ch -} - -func (ch *RingChannel) In() chan<- interface{} { - return ch.input -} - -func (ch *RingChannel) Out() <-chan interface{} { - return ch.output -} - -func (ch *RingChannel) Len() int { - if ch.size == None { - return 0 - } else { - return <-ch.length - } -} - -func (ch *RingChannel) Cap() BufferCap { - return ch.size -} - -func (ch *RingChannel) Close() { - close(ch.input) -} - -// for entirely unbuffered cases -func (ch *RingChannel) overflowingDirect() { - for elem := range ch.input { - // if we can't write it immediately, drop it and move on - select { - case ch.output <- elem: - default: - } - } - close(ch.output) -} - -// for all buffered cases -func (ch *RingChannel) ringBuffer() { - var input, output chan interface{} - var next interface{} - input = ch.input - - for input != nil || output != nil { - select { - // Prefer to write if possible, which is surprisingly effective in reducing - // dropped elements due to overflow. The naive read/write select chooses randomly - // when both channels are ready, which produces unnecessary drops 50% of the time. - case output <- next: - ch.buffer.Remove() - default: - select { - case elem, open := <-input: - if open { - ch.buffer.Add(elem) - if ch.size != Infinity && ch.buffer.Length() > int(ch.size) { - ch.buffer.Remove() - } - } else { - input = nil - } - case output <- next: - ch.buffer.Remove() - case ch.length <- ch.buffer.Length(): - } - } - - if ch.buffer.Length() > 0 { - output = ch.output - next = ch.buffer.Peek() - } else { - output = nil - next = nil - } - } - - close(ch.output) - close(ch.length) -} diff --git a/vendor/github.com/eapache/channels/shared_buffer.go b/vendor/github.com/eapache/channels/shared_buffer.go deleted file mode 100644 index 556dc190a..000000000 --- a/vendor/github.com/eapache/channels/shared_buffer.go +++ /dev/null @@ -1,167 +0,0 @@ -package channels - -import ( - "reflect" - - "github.com/eapache/queue" -) - -//sharedBufferChannel implements SimpleChannel and is created by the public -//SharedBuffer type below -type sharedBufferChannel struct { - in chan interface{} - out chan interface{} - buf *queue.Queue - closed bool -} - -func (sch *sharedBufferChannel) In() chan<- interface{} { - return sch.in -} - -func (sch *sharedBufferChannel) Out() <-chan interface{} { - return sch.out -} - -func (sch *sharedBufferChannel) Close() { - close(sch.in) -} - -//SharedBuffer implements the Buffer interface, and permits multiple SimpleChannel instances to "share" a single buffer. -//Each channel spawned by NewChannel has its own internal queue (so values flowing through do not get mixed up with -//other channels) but the total number of elements buffered by all spawned channels is limited to a single capacity. This -//means *all* such channels block and unblock for writing together. The primary use case is for implementing pipeline-style -//parallelism with goroutines, limiting the total number of elements in the pipeline without limiting the number of elements -//at any particular step. -type SharedBuffer struct { - cases []reflect.SelectCase // 2n+1 of these; [0] is for control, [1,3,5...] for recv, [2,4,6...] for send - chans []*sharedBufferChannel // n of these - count int - size BufferCap - in chan *sharedBufferChannel -} - -func NewSharedBuffer(size BufferCap) *SharedBuffer { - if size < 0 && size != Infinity { - panic("channels: invalid negative size in NewSharedBuffer") - } else if size == None { - panic("channels: SharedBuffer does not support unbuffered behaviour") - } - - buf := &SharedBuffer{ - size: size, - in: make(chan *sharedBufferChannel), - } - - buf.cases = append(buf.cases, reflect.SelectCase{ - Dir: reflect.SelectRecv, - Chan: reflect.ValueOf(buf.in), - }) - - go buf.mainLoop() - - return buf -} - -//NewChannel spawns and returns a new channel sharing the underlying buffer. -func (buf *SharedBuffer) NewChannel() SimpleChannel { - ch := &sharedBufferChannel{ - in: make(chan interface{}), - out: make(chan interface{}), - buf: queue.New(), - } - buf.in <- ch - return ch -} - -//Close shuts down the SharedBuffer. It is an error to call Close while channels are still using -//the buffer (I'm not really sure what would happen if you do so). -func (buf *SharedBuffer) Close() { - // TODO: what if there are still active channels using this buffer? - close(buf.in) -} - -func (buf *SharedBuffer) mainLoop() { - for { - i, val, ok := reflect.Select(buf.cases) - - if i == 0 { - if !ok { - //Close was called on the SharedBuffer itself - return - } - - //NewChannel was called on the SharedBuffer - ch := val.Interface().(*sharedBufferChannel) - buf.chans = append(buf.chans, ch) - buf.cases = append(buf.cases, - reflect.SelectCase{Dir: reflect.SelectRecv}, - reflect.SelectCase{Dir: reflect.SelectSend}, - ) - if buf.size == Infinity || buf.count < int(buf.size) { - buf.cases[len(buf.cases)-2].Chan = reflect.ValueOf(ch.in) - } - } else if i%2 == 0 { - //Send - if buf.count == int(buf.size) { - //room in the buffer again, re-enable all recv cases - for j := range buf.chans { - if !buf.chans[j].closed { - buf.cases[(j*2)+1].Chan = reflect.ValueOf(buf.chans[j].in) - } - } - } - buf.count-- - ch := buf.chans[(i-1)/2] - if ch.buf.Length() > 0 { - buf.cases[i].Send = reflect.ValueOf(ch.buf.Peek()) - ch.buf.Remove() - } else { - //nothing left for this channel to send, disable sending - buf.cases[i].Chan = reflect.Value{} - buf.cases[i].Send = reflect.Value{} - if ch.closed { - // and it was closed, so close the output channel - //TODO: shrink slice - close(ch.out) - } - } - } else { - ch := buf.chans[i/2] - if ok { - //Receive - buf.count++ - if ch.buf.Length() == 0 && !buf.cases[i+1].Chan.IsValid() { - //this channel now has something to send - buf.cases[i+1].Chan = reflect.ValueOf(ch.out) - buf.cases[i+1].Send = val - } else { - ch.buf.Add(val.Interface()) - } - if buf.count == int(buf.size) { - //buffer full, disable recv cases - for j := range buf.chans { - buf.cases[(j*2)+1].Chan = reflect.Value{} - } - } - } else { - //Close - buf.cases[i].Chan = reflect.Value{} - ch.closed = true - if ch.buf.Length() == 0 && !buf.cases[i+1].Chan.IsValid() { - //nothing pending, close the out channel right away - //TODO: shrink slice - close(ch.out) - } - } - } - } -} - -func (buf *SharedBuffer) Len() int { - return buf.count -} - -func (buf *SharedBuffer) Cap() BufferCap { - return buf.size -} diff --git a/vendor/github.com/eapache/go-resiliency/LICENSE b/vendor/github.com/eapache/go-resiliency/LICENSE deleted file mode 100644 index 698a3f513..000000000 --- a/vendor/github.com/eapache/go-resiliency/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Evan Huus - -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/eapache/go-resiliency/breaker/breaker.go b/vendor/github.com/eapache/go-resiliency/breaker/breaker.go deleted file mode 100644 index f88ca7248..000000000 --- a/vendor/github.com/eapache/go-resiliency/breaker/breaker.go +++ /dev/null @@ -1,161 +0,0 @@ -// Package breaker implements the circuit-breaker resiliency pattern for Go. -package breaker - -import ( - "errors" - "sync" - "sync/atomic" - "time" -) - -// ErrBreakerOpen is the error returned from Run() when the function is not executed -// because the breaker is currently open. -var ErrBreakerOpen = errors.New("circuit breaker is open") - -const ( - closed uint32 = iota - open - halfOpen -) - -// Breaker implements the circuit-breaker resiliency pattern -type Breaker struct { - errorThreshold, successThreshold int - timeout time.Duration - - lock sync.Mutex - state uint32 - errors, successes int - lastError time.Time -} - -// New constructs a new circuit-breaker that starts closed. -// From closed, the breaker opens if "errorThreshold" errors are seen -// without an error-free period of at least "timeout". From open, the -// breaker half-closes after "timeout". From half-open, the breaker closes -// after "successThreshold" consecutive successes, or opens on a single error. -func New(errorThreshold, successThreshold int, timeout time.Duration) *Breaker { - return &Breaker{ - errorThreshold: errorThreshold, - successThreshold: successThreshold, - timeout: timeout, - } -} - -// Run will either return ErrBreakerOpen immediately if the circuit-breaker is -// already open, or it will run the given function and pass along its return -// value. It is safe to call Run concurrently on the same Breaker. -func (b *Breaker) Run(work func() error) error { - state := atomic.LoadUint32(&b.state) - - if state == open { - return ErrBreakerOpen - } - - return b.doWork(state, work) -} - -// Go will either return ErrBreakerOpen immediately if the circuit-breaker is -// already open, or it will run the given function in a separate goroutine. -// If the function is run, Go will return nil immediately, and will *not* return -// the return value of the function. It is safe to call Go concurrently on the -// same Breaker. -func (b *Breaker) Go(work func() error) error { - state := atomic.LoadUint32(&b.state) - - if state == open { - return ErrBreakerOpen - } - - // errcheck complains about ignoring the error return value, but - // that's on purpose; if you want an error from a goroutine you have to - // get it over a channel or something - go b.doWork(state, work) - - return nil -} - -func (b *Breaker) doWork(state uint32, work func() error) error { - var panicValue interface{} - - result := func() error { - defer func() { - panicValue = recover() - }() - return work() - }() - - if result == nil && panicValue == nil && state == closed { - // short-circuit the normal, success path without contending - // on the lock - return nil - } - - // oh well, I guess we have to contend on the lock - b.processResult(result, panicValue) - - if panicValue != nil { - // as close as Go lets us come to a "rethrow" although unfortunately - // we lose the original panicing location - panic(panicValue) - } - - return result -} - -func (b *Breaker) processResult(result error, panicValue interface{}) { - b.lock.Lock() - defer b.lock.Unlock() - - if result == nil && panicValue == nil { - if b.state == halfOpen { - b.successes++ - if b.successes == b.successThreshold { - b.closeBreaker() - } - } - } else { - if b.errors > 0 { - expiry := b.lastError.Add(b.timeout) - if time.Now().After(expiry) { - b.errors = 0 - } - } - - switch b.state { - case closed: - b.errors++ - if b.errors == b.errorThreshold { - b.openBreaker() - } else { - b.lastError = time.Now() - } - case halfOpen: - b.openBreaker() - } - } -} - -func (b *Breaker) openBreaker() { - b.changeState(open) - go b.timer() -} - -func (b *Breaker) closeBreaker() { - b.changeState(closed) -} - -func (b *Breaker) timer() { - time.Sleep(b.timeout) - - b.lock.Lock() - defer b.lock.Unlock() - - b.changeState(halfOpen) -} - -func (b *Breaker) changeState(newState uint32) { - b.errors = 0 - b.successes = 0 - atomic.StoreUint32(&b.state, newState) -} diff --git a/vendor/github.com/eapache/go-xerial-snappy/LICENSE b/vendor/github.com/eapache/go-xerial-snappy/LICENSE deleted file mode 100644 index 5bf3688d9..000000000 --- a/vendor/github.com/eapache/go-xerial-snappy/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2016 Evan Huus - -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/eapache/go-xerial-snappy/snappy.go b/vendor/github.com/eapache/go-xerial-snappy/snappy.go deleted file mode 100644 index b8f8b51fc..000000000 --- a/vendor/github.com/eapache/go-xerial-snappy/snappy.go +++ /dev/null @@ -1,43 +0,0 @@ -package snappy - -import ( - "bytes" - "encoding/binary" - - master "github.com/golang/snappy" -) - -var xerialHeader = []byte{130, 83, 78, 65, 80, 80, 89, 0} - -// Encode encodes data as snappy with no framing header. -func Encode(src []byte) []byte { - return master.Encode(nil, src) -} - -// Decode decodes snappy data whether it is traditional unframed -// or includes the xerial framing format. -func Decode(src []byte) ([]byte, error) { - if !bytes.Equal(src[:8], xerialHeader) { - return master.Decode(nil, src) - } - - var ( - pos = uint32(16) - max = uint32(len(src)) - dst = make([]byte, 0, len(src)) - chunk []byte - err error - ) - for pos < max { - size := binary.BigEndian.Uint32(src[pos : pos+4]) - pos += 4 - - chunk, err = master.Decode(chunk, src[pos:pos+size]) - if err != nil { - return nil, err - } - pos += size - dst = append(dst, chunk...) - } - return dst, nil -} diff --git a/vendor/github.com/eapache/queue/LICENSE b/vendor/github.com/eapache/queue/LICENSE deleted file mode 100644 index d5f36dbca..000000000 --- a/vendor/github.com/eapache/queue/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Evan Huus - -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/eapache/queue/queue.go b/vendor/github.com/eapache/queue/queue.go deleted file mode 100644 index 71d1acdf2..000000000 --- a/vendor/github.com/eapache/queue/queue.go +++ /dev/null @@ -1,102 +0,0 @@ -/* -Package queue provides a fast, ring-buffer queue based on the version suggested by Dariusz Górecki. -Using this instead of other, simpler, queue implementations (slice+append or linked list) provides -substantial memory and time benefits, and fewer GC pauses. - -The queue implemented here is as fast as it is for an additional reason: it is *not* thread-safe. -*/ -package queue - -// minQueueLen is smallest capacity that queue may have. -// Must be power of 2 for bitwise modulus: x % n == x & (n - 1). -const minQueueLen = 16 - -// Queue represents a single instance of the queue data structure. -type Queue struct { - buf []interface{} - head, tail, count int -} - -// New constructs and returns a new Queue. -func New() *Queue { - return &Queue{ - buf: make([]interface{}, minQueueLen), - } -} - -// Length returns the number of elements currently stored in the queue. -func (q *Queue) Length() int { - return q.count -} - -// resizes the queue to fit exactly twice its current contents -// this can result in shrinking if the queue is less than half-full -func (q *Queue) resize() { - newBuf := make([]interface{}, q.count<<1) - - if q.tail > q.head { - copy(newBuf, q.buf[q.head:q.tail]) - } else { - n := copy(newBuf, q.buf[q.head:]) - copy(newBuf[n:], q.buf[:q.tail]) - } - - q.head = 0 - q.tail = q.count - q.buf = newBuf -} - -// Add puts an element on the end of the queue. -func (q *Queue) Add(elem interface{}) { - if q.count == len(q.buf) { - q.resize() - } - - q.buf[q.tail] = elem - // bitwise modulus - q.tail = (q.tail + 1) & (len(q.buf) - 1) - q.count++ -} - -// Peek returns the element at the head of the queue. This call panics -// if the queue is empty. -func (q *Queue) Peek() interface{} { - if q.count <= 0 { - panic("queue: Peek() called on empty queue") - } - return q.buf[q.head] -} - -// Get returns the element at index i in the queue. If the index is -// invalid, the call will panic. This method accepts both positive and -// negative index values. Index 0 refers to the first element, and -// index -1 refers to the last. -func (q *Queue) Get(i int) interface{} { - // If indexing backwards, convert to positive index. - if i < 0 { - i += q.count - } - if i < 0 || i >= q.count { - panic("queue: Get() called with index out of range") - } - // bitwise modulus - return q.buf[(q.head+i)&(len(q.buf)-1)] -} - -// Remove removes and returns the element from the front of the queue. If the -// queue is empty, the call will panic. -func (q *Queue) Remove() interface{} { - if q.count <= 0 { - panic("queue: Remove() called on empty queue") - } - ret := q.buf[q.head] - q.buf[q.head] = nil - // bitwise modulus - q.head = (q.head + 1) & (len(q.buf) - 1) - q.count-- - // Resize down if buffer 1/4 full. - if len(q.buf) > minQueueLen && (q.count<<2) == len(q.buf) { - q.resize() - } - return ret -} diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/LICENSE b/vendor/github.com/elazarl/go-bindata-assetfs/LICENSE deleted file mode 100644 index 5782c7269..000000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -Copyright (c) 2014, Elazar Leibovich -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - -* Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go b/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go deleted file mode 100644 index 04f6d7a39..000000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/assetfs.go +++ /dev/null @@ -1,167 +0,0 @@ -package assetfs - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "net/http" - "os" - "path" - "path/filepath" - "strings" - "time" -) - -var ( - defaultFileTimestamp = time.Now() -) - -// FakeFile implements os.FileInfo interface for a given path and size -type FakeFile struct { - // Path is the path of this file - Path string - // Dir marks of the path is a directory - Dir bool - // Len is the length of the fake file, zero if it is a directory - Len int64 - // Timestamp is the ModTime of this file - Timestamp time.Time -} - -func (f *FakeFile) Name() string { - _, name := filepath.Split(f.Path) - return name -} - -func (f *FakeFile) Mode() os.FileMode { - mode := os.FileMode(0644) - if f.Dir { - return mode | os.ModeDir - } - return mode -} - -func (f *FakeFile) ModTime() time.Time { - return f.Timestamp -} - -func (f *FakeFile) Size() int64 { - return f.Len -} - -func (f *FakeFile) IsDir() bool { - return f.Mode().IsDir() -} - -func (f *FakeFile) Sys() interface{} { - return nil -} - -// AssetFile implements http.File interface for a no-directory file with content -type AssetFile struct { - *bytes.Reader - io.Closer - FakeFile -} - -func NewAssetFile(name string, content []byte, timestamp time.Time) *AssetFile { - if timestamp.IsZero() { - timestamp = defaultFileTimestamp - } - return &AssetFile{ - bytes.NewReader(content), - ioutil.NopCloser(nil), - FakeFile{name, false, int64(len(content)), timestamp}} -} - -func (f *AssetFile) Readdir(count int) ([]os.FileInfo, error) { - return nil, errors.New("not a directory") -} - -func (f *AssetFile) Size() int64 { - return f.FakeFile.Size() -} - -func (f *AssetFile) Stat() (os.FileInfo, error) { - return f, nil -} - -// AssetDirectory implements http.File interface for a directory -type AssetDirectory struct { - AssetFile - ChildrenRead int - Children []os.FileInfo -} - -func NewAssetDirectory(name string, children []string, fs *AssetFS) *AssetDirectory { - fileinfos := make([]os.FileInfo, 0, len(children)) - for _, child := range children { - _, err := fs.AssetDir(filepath.Join(name, child)) - fileinfos = append(fileinfos, &FakeFile{child, err == nil, 0, time.Time{}}) - } - return &AssetDirectory{ - AssetFile{ - bytes.NewReader(nil), - ioutil.NopCloser(nil), - FakeFile{name, true, 0, time.Time{}}, - }, - 0, - fileinfos} -} - -func (f *AssetDirectory) Readdir(count int) ([]os.FileInfo, error) { - if count <= 0 { - return f.Children, nil - } - if f.ChildrenRead+count > len(f.Children) { - count = len(f.Children) - f.ChildrenRead - } - rv := f.Children[f.ChildrenRead : f.ChildrenRead+count] - f.ChildrenRead += count - return rv, nil -} - -func (f *AssetDirectory) Stat() (os.FileInfo, error) { - return f, nil -} - -// AssetFS implements http.FileSystem, allowing -// embedded files to be served from net/http package. -type AssetFS struct { - // Asset should return content of file in path if exists - Asset func(path string) ([]byte, error) - // AssetDir should return list of files in the path - AssetDir func(path string) ([]string, error) - // AssetInfo should return the info of file in path if exists - AssetInfo func(path string) (os.FileInfo, error) - // Prefix would be prepended to http requests - Prefix string -} - -func (fs *AssetFS) Open(name string) (http.File, error) { - name = path.Join(fs.Prefix, name) - if len(name) > 0 && name[0] == '/' { - name = name[1:] - } - if b, err := fs.Asset(name); err == nil { - timestamp := defaultFileTimestamp - if fs.AssetInfo != nil { - if info, err := fs.AssetInfo(name); err == nil { - timestamp = info.ModTime() - } - } - return NewAssetFile(name, b, timestamp), nil - } - if children, err := fs.AssetDir(name); err == nil { - return NewAssetDirectory(name, children, fs), nil - } else { - // If the error is not found, return an error that will - // result in a 404 error. Otherwise the server returns - // a 500 error for files not found. - if strings.Contains(err.Error(), "not found") { - return nil, os.ErrNotExist - } - return nil, err - } -} diff --git a/vendor/github.com/elazarl/go-bindata-assetfs/doc.go b/vendor/github.com/elazarl/go-bindata-assetfs/doc.go deleted file mode 100644 index a664249f3..000000000 --- a/vendor/github.com/elazarl/go-bindata-assetfs/doc.go +++ /dev/null @@ -1,13 +0,0 @@ -// assetfs allows packages to serve static content embedded -// with the go-bindata tool with the standard net/http package. -// -// See https://github.com/jteeuwen/go-bindata for more information -// about embedding binary data with go-bindata. -// -// Usage example, after running -// $ go-bindata data/... -// use: -// http.Handle("/", -// http.FileServer( -// &assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, Prefix: "data"})) -package assetfs diff --git a/vendor/github.com/evanphx/json-patch/LICENSE b/vendor/github.com/evanphx/json-patch/LICENSE deleted file mode 100644 index 0eb9b72d8..000000000 --- a/vendor/github.com/evanphx/json-patch/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2014, Evan Phoenix -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright notice - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. -* Neither the name of the Evan Phoenix 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/evanphx/json-patch/errors.go b/vendor/github.com/evanphx/json-patch/errors.go deleted file mode 100644 index 75304b443..000000000 --- a/vendor/github.com/evanphx/json-patch/errors.go +++ /dev/null @@ -1,38 +0,0 @@ -package jsonpatch - -import "fmt" - -// AccumulatedCopySizeError is an error type returned when the accumulated size -// increase caused by copy operations in a patch operation has exceeded the -// limit. -type AccumulatedCopySizeError struct { - limit int64 - accumulated int64 -} - -// NewAccumulatedCopySizeError returns an AccumulatedCopySizeError. -func NewAccumulatedCopySizeError(l, a int64) *AccumulatedCopySizeError { - return &AccumulatedCopySizeError{limit: l, accumulated: a} -} - -// Error implements the error interface. -func (a *AccumulatedCopySizeError) Error() string { - return fmt.Sprintf("Unable to complete the copy, the accumulated size increase of copy is %d, exceeding the limit %d", a.accumulated, a.limit) -} - -// ArraySizeError is an error type returned when the array size has exceeded -// the limit. -type ArraySizeError struct { - limit int - size int -} - -// NewArraySizeError returns an ArraySizeError. -func NewArraySizeError(l, s int) *ArraySizeError { - return &ArraySizeError{limit: l, size: s} -} - -// Error implements the error interface. -func (a *ArraySizeError) Error() string { - return fmt.Sprintf("Unable to create array of size %d, limit is %d", a.size, a.limit) -} diff --git a/vendor/github.com/evanphx/json-patch/merge.go b/vendor/github.com/evanphx/json-patch/merge.go deleted file mode 100644 index 6806c4c20..000000000 --- a/vendor/github.com/evanphx/json-patch/merge.go +++ /dev/null @@ -1,383 +0,0 @@ -package jsonpatch - -import ( - "bytes" - "encoding/json" - "fmt" - "reflect" -) - -func merge(cur, patch *lazyNode, mergeMerge bool) *lazyNode { - curDoc, err := cur.intoDoc() - - if err != nil { - pruneNulls(patch) - return patch - } - - patchDoc, err := patch.intoDoc() - - if err != nil { - return patch - } - - mergeDocs(curDoc, patchDoc, mergeMerge) - - return cur -} - -func mergeDocs(doc, patch *partialDoc, mergeMerge bool) { - for k, v := range *patch { - if v == nil { - if mergeMerge { - (*doc)[k] = nil - } else { - delete(*doc, k) - } - } else { - cur, ok := (*doc)[k] - - if !ok || cur == nil { - pruneNulls(v) - (*doc)[k] = v - } else { - (*doc)[k] = merge(cur, v, mergeMerge) - } - } - } -} - -func pruneNulls(n *lazyNode) { - sub, err := n.intoDoc() - - if err == nil { - pruneDocNulls(sub) - } else { - ary, err := n.intoAry() - - if err == nil { - pruneAryNulls(ary) - } - } -} - -func pruneDocNulls(doc *partialDoc) *partialDoc { - for k, v := range *doc { - if v == nil { - delete(*doc, k) - } else { - pruneNulls(v) - } - } - - return doc -} - -func pruneAryNulls(ary *partialArray) *partialArray { - newAry := []*lazyNode{} - - for _, v := range *ary { - if v != nil { - pruneNulls(v) - newAry = append(newAry, v) - } - } - - *ary = newAry - - return ary -} - -var errBadJSONDoc = fmt.Errorf("Invalid JSON Document") -var errBadJSONPatch = fmt.Errorf("Invalid JSON Patch") -var errBadMergeTypes = fmt.Errorf("Mismatched JSON Documents") - -// MergeMergePatches merges two merge patches together, such that -// applying this resulting merged merge patch to a document yields the same -// as merging each merge patch to the document in succession. -func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) { - return doMergePatch(patch1Data, patch2Data, true) -} - -// MergePatch merges the patchData into the docData. -func MergePatch(docData, patchData []byte) ([]byte, error) { - return doMergePatch(docData, patchData, false) -} - -func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) { - doc := &partialDoc{} - - docErr := json.Unmarshal(docData, doc) - - patch := &partialDoc{} - - patchErr := json.Unmarshal(patchData, patch) - - if _, ok := docErr.(*json.SyntaxError); ok { - return nil, errBadJSONDoc - } - - if _, ok := patchErr.(*json.SyntaxError); ok { - return nil, errBadJSONPatch - } - - if docErr == nil && *doc == nil { - return nil, errBadJSONDoc - } - - if patchErr == nil && *patch == nil { - return nil, errBadJSONPatch - } - - if docErr != nil || patchErr != nil { - // Not an error, just not a doc, so we turn straight into the patch - if patchErr == nil { - if mergeMerge { - doc = patch - } else { - doc = pruneDocNulls(patch) - } - } else { - patchAry := &partialArray{} - patchErr = json.Unmarshal(patchData, patchAry) - - if patchErr != nil { - return nil, errBadJSONPatch - } - - pruneAryNulls(patchAry) - - out, patchErr := json.Marshal(patchAry) - - if patchErr != nil { - return nil, errBadJSONPatch - } - - return out, nil - } - } else { - mergeDocs(doc, patch, mergeMerge) - } - - return json.Marshal(doc) -} - -// resemblesJSONArray indicates whether the byte-slice "appears" to be -// a JSON array or not. -// False-positives are possible, as this function does not check the internal -// structure of the array. It only checks that the outer syntax is present and -// correct. -func resemblesJSONArray(input []byte) bool { - input = bytes.TrimSpace(input) - - hasPrefix := bytes.HasPrefix(input, []byte("[")) - hasSuffix := bytes.HasSuffix(input, []byte("]")) - - return hasPrefix && hasSuffix -} - -// CreateMergePatch will return a merge patch document capable of converting -// the original document(s) to the modified document(s). -// The parameters can be bytes of either two JSON Documents, or two arrays of -// JSON documents. -// The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07 -func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { - originalResemblesArray := resemblesJSONArray(originalJSON) - modifiedResemblesArray := resemblesJSONArray(modifiedJSON) - - // Do both byte-slices seem like JSON arrays? - if originalResemblesArray && modifiedResemblesArray { - return createArrayMergePatch(originalJSON, modifiedJSON) - } - - // Are both byte-slices are not arrays? Then they are likely JSON objects... - if !originalResemblesArray && !modifiedResemblesArray { - return createObjectMergePatch(originalJSON, modifiedJSON) - } - - // None of the above? Then return an error because of mismatched types. - return nil, errBadMergeTypes -} - -// createObjectMergePatch will return a merge-patch document capable of -// converting the original document to the modified document. -func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { - originalDoc := map[string]interface{}{} - modifiedDoc := map[string]interface{}{} - - err := json.Unmarshal(originalJSON, &originalDoc) - if err != nil { - return nil, errBadJSONDoc - } - - err = json.Unmarshal(modifiedJSON, &modifiedDoc) - if err != nil { - return nil, errBadJSONDoc - } - - dest, err := getDiff(originalDoc, modifiedDoc) - if err != nil { - return nil, err - } - - return json.Marshal(dest) -} - -// createArrayMergePatch will return an array of merge-patch documents capable -// of converting the original document to the modified document for each -// pair of JSON documents provided in the arrays. -// Arrays of mismatched sizes will result in an error. -func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) { - originalDocs := []json.RawMessage{} - modifiedDocs := []json.RawMessage{} - - err := json.Unmarshal(originalJSON, &originalDocs) - if err != nil { - return nil, errBadJSONDoc - } - - err = json.Unmarshal(modifiedJSON, &modifiedDocs) - if err != nil { - return nil, errBadJSONDoc - } - - total := len(originalDocs) - if len(modifiedDocs) != total { - return nil, errBadJSONDoc - } - - result := []json.RawMessage{} - for i := 0; i < len(originalDocs); i++ { - original := originalDocs[i] - modified := modifiedDocs[i] - - patch, err := createObjectMergePatch(original, modified) - if err != nil { - return nil, err - } - - result = append(result, json.RawMessage(patch)) - } - - return json.Marshal(result) -} - -// Returns true if the array matches (must be json types). -// As is idiomatic for go, an empty array is not the same as a nil array. -func matchesArray(a, b []interface{}) bool { - if len(a) != len(b) { - return false - } - if (a == nil && b != nil) || (a != nil && b == nil) { - return false - } - for i := range a { - if !matchesValue(a[i], b[i]) { - return false - } - } - return true -} - -// Returns true if the values matches (must be json types) -// The types of the values must match, otherwise it will always return false -// If two map[string]interface{} are given, all elements must match. -func matchesValue(av, bv interface{}) bool { - if reflect.TypeOf(av) != reflect.TypeOf(bv) { - return false - } - switch at := av.(type) { - case string: - bt := bv.(string) - if bt == at { - return true - } - case float64: - bt := bv.(float64) - if bt == at { - return true - } - case bool: - bt := bv.(bool) - if bt == at { - return true - } - case nil: - // Both nil, fine. - return true - case map[string]interface{}: - bt := bv.(map[string]interface{}) - for key := range at { - if !matchesValue(at[key], bt[key]) { - return false - } - } - for key := range bt { - if !matchesValue(at[key], bt[key]) { - return false - } - } - return true - case []interface{}: - bt := bv.([]interface{}) - return matchesArray(at, bt) - } - return false -} - -// getDiff returns the (recursive) difference between a and b as a map[string]interface{}. -func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) { - into := map[string]interface{}{} - for key, bv := range b { - av, ok := a[key] - // value was added - if !ok { - into[key] = bv - continue - } - // If types have changed, replace completely - if reflect.TypeOf(av) != reflect.TypeOf(bv) { - into[key] = bv - continue - } - // Types are the same, compare values - switch at := av.(type) { - case map[string]interface{}: - bt := bv.(map[string]interface{}) - dst := make(map[string]interface{}, len(bt)) - dst, err := getDiff(at, bt) - if err != nil { - return nil, err - } - if len(dst) > 0 { - into[key] = dst - } - case string, float64, bool: - if !matchesValue(av, bv) { - into[key] = bv - } - case []interface{}: - bt := bv.([]interface{}) - if !matchesArray(at, bt) { - into[key] = bv - } - case nil: - switch bv.(type) { - case nil: - // Both nil, fine. - default: - into[key] = bv - } - default: - panic(fmt.Sprintf("Unknown type:%T in key %s", av, key)) - } - } - // Now add all deleted values as nil - for key := range a { - _, found := b[key] - if !found { - into[key] = nil - } - } - return into, nil -} diff --git a/vendor/github.com/evanphx/json-patch/patch.go b/vendor/github.com/evanphx/json-patch/patch.go deleted file mode 100644 index 1b5f95e61..000000000 --- a/vendor/github.com/evanphx/json-patch/patch.go +++ /dev/null @@ -1,776 +0,0 @@ -package jsonpatch - -import ( - "bytes" - "encoding/json" - "fmt" - "strconv" - "strings" - - "github.com/pkg/errors" -) - -const ( - eRaw = iota - eDoc - eAry -) - -var ( - // SupportNegativeIndices decides whether to support non-standard practice of - // allowing negative indices to mean indices starting at the end of an array. - // Default to true. - SupportNegativeIndices bool = true - // AccumulatedCopySizeLimit limits the total size increase in bytes caused by - // "copy" operations in a patch. - AccumulatedCopySizeLimit int64 = 0 -) - -var ( - ErrTestFailed = errors.New("test failed") - ErrMissing = errors.New("missing value") - ErrUnknownType = errors.New("unknown object type") - ErrInvalid = errors.New("invalid state detected") - ErrInvalidIndex = errors.New("invalid index referenced") -) - -type lazyNode struct { - raw *json.RawMessage - doc partialDoc - ary partialArray - which int -} - -// Operation is a single JSON-Patch step, such as a single 'add' operation. -type Operation map[string]*json.RawMessage - -// Patch is an ordered collection of Operations. -type Patch []Operation - -type partialDoc map[string]*lazyNode -type partialArray []*lazyNode - -type container interface { - get(key string) (*lazyNode, error) - set(key string, val *lazyNode) error - add(key string, val *lazyNode) error - remove(key string) error -} - -func newLazyNode(raw *json.RawMessage) *lazyNode { - return &lazyNode{raw: raw, doc: nil, ary: nil, which: eRaw} -} - -func (n *lazyNode) MarshalJSON() ([]byte, error) { - switch n.which { - case eRaw: - return json.Marshal(n.raw) - case eDoc: - return json.Marshal(n.doc) - case eAry: - return json.Marshal(n.ary) - default: - return nil, ErrUnknownType - } -} - -func (n *lazyNode) UnmarshalJSON(data []byte) error { - dest := make(json.RawMessage, len(data)) - copy(dest, data) - n.raw = &dest - n.which = eRaw - return nil -} - -func deepCopy(src *lazyNode) (*lazyNode, int, error) { - if src == nil { - return nil, 0, nil - } - a, err := src.MarshalJSON() - if err != nil { - return nil, 0, err - } - sz := len(a) - ra := make(json.RawMessage, sz) - copy(ra, a) - return newLazyNode(&ra), sz, nil -} - -func (n *lazyNode) intoDoc() (*partialDoc, error) { - if n.which == eDoc { - return &n.doc, nil - } - - if n.raw == nil { - return nil, ErrInvalid - } - - err := json.Unmarshal(*n.raw, &n.doc) - - if err != nil { - return nil, err - } - - n.which = eDoc - return &n.doc, nil -} - -func (n *lazyNode) intoAry() (*partialArray, error) { - if n.which == eAry { - return &n.ary, nil - } - - if n.raw == nil { - return nil, ErrInvalid - } - - err := json.Unmarshal(*n.raw, &n.ary) - - if err != nil { - return nil, err - } - - n.which = eAry - return &n.ary, nil -} - -func (n *lazyNode) compact() []byte { - buf := &bytes.Buffer{} - - if n.raw == nil { - return nil - } - - err := json.Compact(buf, *n.raw) - - if err != nil { - return *n.raw - } - - return buf.Bytes() -} - -func (n *lazyNode) tryDoc() bool { - if n.raw == nil { - return false - } - - err := json.Unmarshal(*n.raw, &n.doc) - - if err != nil { - return false - } - - n.which = eDoc - return true -} - -func (n *lazyNode) tryAry() bool { - if n.raw == nil { - return false - } - - err := json.Unmarshal(*n.raw, &n.ary) - - if err != nil { - return false - } - - n.which = eAry - return true -} - -func (n *lazyNode) equal(o *lazyNode) bool { - if n.which == eRaw { - if !n.tryDoc() && !n.tryAry() { - if o.which != eRaw { - return false - } - - return bytes.Equal(n.compact(), o.compact()) - } - } - - if n.which == eDoc { - if o.which == eRaw { - if !o.tryDoc() { - return false - } - } - - if o.which != eDoc { - return false - } - - for k, v := range n.doc { - ov, ok := o.doc[k] - - if !ok { - return false - } - - if v == nil && ov == nil { - continue - } - - if !v.equal(ov) { - return false - } - } - - return true - } - - if o.which != eAry && !o.tryAry() { - return false - } - - if len(n.ary) != len(o.ary) { - return false - } - - for idx, val := range n.ary { - if !val.equal(o.ary[idx]) { - return false - } - } - - return true -} - -// Kind reads the "op" field of the Operation. -func (o Operation) Kind() string { - if obj, ok := o["op"]; ok && obj != nil { - var op string - - err := json.Unmarshal(*obj, &op) - - if err != nil { - return "unknown" - } - - return op - } - - return "unknown" -} - -// Path reads the "path" field of the Operation. -func (o Operation) Path() (string, error) { - if obj, ok := o["path"]; ok && obj != nil { - var op string - - err := json.Unmarshal(*obj, &op) - - if err != nil { - return "unknown", err - } - - return op, nil - } - - return "unknown", errors.Wrapf(ErrMissing, "operation missing path field") -} - -// From reads the "from" field of the Operation. -func (o Operation) From() (string, error) { - if obj, ok := o["from"]; ok && obj != nil { - var op string - - err := json.Unmarshal(*obj, &op) - - if err != nil { - return "unknown", err - } - - return op, nil - } - - return "unknown", errors.Wrapf(ErrMissing, "operation, missing from field") -} - -func (o Operation) value() *lazyNode { - if obj, ok := o["value"]; ok { - return newLazyNode(obj) - } - - return nil -} - -// ValueInterface decodes the operation value into an interface. -func (o Operation) ValueInterface() (interface{}, error) { - if obj, ok := o["value"]; ok && obj != nil { - var v interface{} - - err := json.Unmarshal(*obj, &v) - - if err != nil { - return nil, err - } - - return v, nil - } - - return nil, errors.Wrapf(ErrMissing, "operation, missing value field") -} - -func isArray(buf []byte) bool { -Loop: - for _, c := range buf { - switch c { - case ' ': - case '\n': - case '\t': - continue - case '[': - return true - default: - break Loop - } - } - - return false -} - -func findObject(pd *container, path string) (container, string) { - doc := *pd - - split := strings.Split(path, "/") - - if len(split) < 2 { - return nil, "" - } - - parts := split[1 : len(split)-1] - - key := split[len(split)-1] - - var err error - - for _, part := range parts { - - next, ok := doc.get(decodePatchKey(part)) - - if next == nil || ok != nil { - return nil, "" - } - - if isArray(*next.raw) { - doc, err = next.intoAry() - - if err != nil { - return nil, "" - } - } else { - doc, err = next.intoDoc() - - if err != nil { - return nil, "" - } - } - } - - return doc, decodePatchKey(key) -} - -func (d *partialDoc) set(key string, val *lazyNode) error { - (*d)[key] = val - return nil -} - -func (d *partialDoc) add(key string, val *lazyNode) error { - (*d)[key] = val - return nil -} - -func (d *partialDoc) get(key string) (*lazyNode, error) { - return (*d)[key], nil -} - -func (d *partialDoc) remove(key string) error { - _, ok := (*d)[key] - if !ok { - return errors.Wrapf(ErrMissing, "Unable to remove nonexistent key: %s", key) - } - - delete(*d, key) - return nil -} - -// set should only be used to implement the "replace" operation, so "key" must -// be an already existing index in "d". -func (d *partialArray) set(key string, val *lazyNode) error { - idx, err := strconv.Atoi(key) - if err != nil { - return err - } - (*d)[idx] = val - return nil -} - -func (d *partialArray) add(key string, val *lazyNode) error { - if key == "-" { - *d = append(*d, val) - return nil - } - - idx, err := strconv.Atoi(key) - if err != nil { - return errors.Wrapf(err, "value was not a proper array index: '%s'", key) - } - - sz := len(*d) + 1 - - ary := make([]*lazyNode, sz) - - cur := *d - - if idx >= len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if SupportNegativeIndices { - if idx < -len(ary) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if idx < 0 { - idx += len(ary) - } - } - - copy(ary[0:idx], cur[0:idx]) - ary[idx] = val - copy(ary[idx+1:], cur[idx:]) - - *d = ary - return nil -} - -func (d *partialArray) get(key string) (*lazyNode, error) { - idx, err := strconv.Atoi(key) - - if err != nil { - return nil, err - } - - if idx >= len(*d) { - return nil, errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - return (*d)[idx], nil -} - -func (d *partialArray) remove(key string) error { - idx, err := strconv.Atoi(key) - if err != nil { - return err - } - - cur := *d - - if idx >= len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if SupportNegativeIndices { - if idx < -len(cur) { - return errors.Wrapf(ErrInvalidIndex, "Unable to access invalid index: %d", idx) - } - - if idx < 0 { - idx += len(cur) - } - } - - ary := make([]*lazyNode, len(cur)-1) - - copy(ary[0:idx], cur[0:idx]) - copy(ary[idx:], cur[idx+1:]) - - *d = ary - return nil - -} - -func (p Patch) add(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "add operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "add operation does not apply: doc is missing path: \"%s\"", path) - } - - err = con.add(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in add for path: '%s'", path) - } - - return nil -} - -func (p Patch) remove(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "remove operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "remove operation does not apply: doc is missing path: \"%s\"", path) - } - - err = con.remove(key) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) - } - - return nil -} - -func (p Patch) replace(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "replace operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing path: %s", path) - } - - _, ok := con.get(key) - if ok != nil { - return errors.Wrapf(ErrMissing, "replace operation does not apply: doc is missing key: %s", path) - } - - err = con.set(key, op.value()) - if err != nil { - return errors.Wrapf(err, "error in remove for path: '%s'", path) - } - - return nil -} - -func (p Patch) move(doc *container, op Operation) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode from") - } - - con, key := findObject(doc, from) - - if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing from path: %s", from) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) - } - - err = con.remove(key) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", key) - } - - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "move operation failed to decode path") - } - - con, key = findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "move operation does not apply: doc is missing destination path: %s", path) - } - - err = con.add(key, val) - if err != nil { - return errors.Wrapf(err, "error in move for path: '%s'", path) - } - - return nil -} - -func (p Patch) test(doc *container, op Operation) error { - path, err := op.Path() - if err != nil { - return errors.Wrapf(err, "test operation failed to decode path") - } - - con, key := findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "test operation does not apply: is missing path: %s", path) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in test for path: '%s'", path) - } - - if val == nil { - if op.value().raw == nil { - return nil - } - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) - } else if op.value() == nil { - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) - } - - if val.equal(op.value()) { - return nil - } - - return errors.Wrapf(ErrTestFailed, "testing value %s failed", path) -} - -func (p Patch) copy(doc *container, op Operation, accumulatedCopySize *int64) error { - from, err := op.From() - if err != nil { - return errors.Wrapf(err, "copy operation failed to decode from") - } - - con, key := findObject(doc, from) - - if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing from path: %s", from) - } - - val, err := con.get(key) - if err != nil { - return errors.Wrapf(err, "error in copy for from: '%s'", from) - } - - path, err := op.Path() - if err != nil { - return errors.Wrapf(ErrMissing, "copy operation failed to decode path") - } - - con, key = findObject(doc, path) - - if con == nil { - return errors.Wrapf(ErrMissing, "copy operation does not apply: doc is missing destination path: %s", path) - } - - valCopy, sz, err := deepCopy(val) - if err != nil { - return errors.Wrapf(err, "error while performing deep copy") - } - - (*accumulatedCopySize) += int64(sz) - if AccumulatedCopySizeLimit > 0 && *accumulatedCopySize > AccumulatedCopySizeLimit { - return NewAccumulatedCopySizeError(AccumulatedCopySizeLimit, *accumulatedCopySize) - } - - err = con.add(key, valCopy) - if err != nil { - return errors.Wrapf(err, "error while adding value during copy") - } - - return nil -} - -// Equal indicates if 2 JSON documents have the same structural equality. -func Equal(a, b []byte) bool { - ra := make(json.RawMessage, len(a)) - copy(ra, a) - la := newLazyNode(&ra) - - rb := make(json.RawMessage, len(b)) - copy(rb, b) - lb := newLazyNode(&rb) - - return la.equal(lb) -} - -// DecodePatch decodes the passed JSON document as an RFC 6902 patch. -func DecodePatch(buf []byte) (Patch, error) { - var p Patch - - err := json.Unmarshal(buf, &p) - - if err != nil { - return nil, err - } - - return p, nil -} - -// Apply mutates a JSON document according to the patch, and returns the new -// document. -func (p Patch) Apply(doc []byte) ([]byte, error) { - return p.ApplyIndent(doc, "") -} - -// ApplyIndent mutates a JSON document according to the patch, and returns the new -// document indented. -func (p Patch) ApplyIndent(doc []byte, indent string) ([]byte, error) { - var pd container - if doc[0] == '[' { - pd = &partialArray{} - } else { - pd = &partialDoc{} - } - - err := json.Unmarshal(doc, pd) - - if err != nil { - return nil, err - } - - err = nil - - var accumulatedCopySize int64 - - for _, op := range p { - switch op.Kind() { - case "add": - err = p.add(&pd, op) - case "remove": - err = p.remove(&pd, op) - case "replace": - err = p.replace(&pd, op) - case "move": - err = p.move(&pd, op) - case "test": - err = p.test(&pd, op) - case "copy": - err = p.copy(&pd, op, &accumulatedCopySize) - default: - err = fmt.Errorf("Unexpected kind: %s", op.Kind()) - } - - if err != nil { - return nil, err - } - } - - if indent != "" { - return json.MarshalIndent(pd, "", indent) - } - - return json.Marshal(pd) -} - -// From http://tools.ietf.org/html/rfc6901#section-4 : -// -// Evaluation of each reference token begins by decoding any escaped -// character sequence. This is performed by first transforming any -// occurrence of the sequence '~1' to '/', and then transforming any -// occurrence of the sequence '~0' to '~'. - -var ( - rfc6901Decoder = strings.NewReplacer("~1", "/", "~0", "~") -) - -func decodePatchKey(k string) string { - return rfc6901Decoder.Replace(k) -} diff --git a/vendor/github.com/exoscale/egoscale/LICENSE b/vendor/github.com/exoscale/egoscale/LICENSE deleted file mode 100644 index 327ecb823..000000000 --- a/vendor/github.com/exoscale/egoscale/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 2014 exoscale(tm) - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT 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/exoscale/egoscale/accounts.go b/vendor/github.com/exoscale/egoscale/accounts.go deleted file mode 100644 index 9bcdec608..000000000 --- a/vendor/github.com/exoscale/egoscale/accounts.go +++ /dev/null @@ -1,80 +0,0 @@ -package egoscale - -// Account provides the detailed account information -type Account struct { - AccountDetails map[string]string `json:"accountdetails,omitempty" doc:"details for the account"` - CPUAvailable string `json:"cpuavailable,omitempty" doc:"the total number of cpu cores available to be created for this account"` - CPULimit string `json:"cpulimit,omitempty" doc:"the total number of cpu cores the account can own"` - CPUTotal int64 `json:"cputotal,omitempty" doc:"the total number of cpu cores owned by account"` - DefaultZoneID *UUID `json:"defaultzoneid,omitempty" doc:"the default zone of the account"` - EipLimit string `json:"eiplimit,omitempty" doc:"the total number of public elastic ip addresses this account can acquire"` - Groups []string `json:"groups,omitempty" doc:"the list of acl groups that account belongs to"` - ID *UUID `json:"id,omitempty" doc:"the id of the account"` - IPAvailable string `json:"ipavailable,omitempty" doc:"the total number of public ip addresses available for this account to acquire"` - IPLimit string `json:"iplimit,omitempty" doc:"the total number of public ip addresses this account can acquire"` - IPTotal int64 `json:"iptotal,omitempty" doc:"the total number of public ip addresses allocated for this account"` - IsCleanupRequired bool `json:"iscleanuprequired,omitempty" doc:"true if the account requires cleanup"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if account is default, false otherwise"` - MemoryAvailable string `json:"memoryavailable,omitempty" doc:"the total memory (in MB) available to be created for this account"` - MemoryLimit string `json:"memorylimit,omitempty" doc:"the total memory (in MB) the account can own"` - MemoryTotal int64 `json:"memorytotal,omitempty" doc:"the total memory (in MB) owned by account"` - Name string `json:"name,omitempty" doc:"the name of the account"` - NetworkAvailable string `json:"networkavailable,omitempty" doc:"the total number of networks available to be created for this account"` - NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"` - NetworkLimit string `json:"networklimit,omitempty" doc:"the total number of networks the account can own"` - NetworkTotal int64 `json:"networktotal,omitempty" doc:"the total number of networks owned by account"` - PrimaryStorageAvailable string `json:"primarystorageavailable,omitempty" doc:"the total primary storage space (in GiB) available to be used for this account"` - PrimaryStorageLimit string `json:"primarystoragelimit,omitempty" doc:"the total primary storage space (in GiB) the account can own"` - PrimaryStorageTotal int64 `json:"primarystoragetotal,omitempty" doc:"the total primary storage space (in GiB) owned by account"` - ProjectAvailable string `json:"projectavailable,omitempty" doc:"the total number of projects available for administration by this account"` - ProjectLimit string `json:"projectlimit,omitempty" doc:"the total number of projects the account can own"` - ProjectTotal int64 `json:"projecttotal,omitempty" doc:"the total number of projects being administrated by this account"` - SecondaryStorageAvailable string `json:"secondarystorageavailable,omitempty" doc:"the total secondary storage space (in GiB) available to be used for this account"` - SecondaryStorageLimit string `json:"secondarystoragelimit,omitempty" doc:"the total secondary storage space (in GiB) the account can own"` - SecondaryStorageTotal int64 `json:"secondarystoragetotal,omitempty" doc:"the total secondary storage space (in GiB) owned by account"` - SMTP bool `json:"smtp,omitempty" doc:"if SMTP outbound is allowed"` - SnapshotAvailable string `json:"snapshotavailable,omitempty" doc:"the total number of snapshots available for this account"` - SnapshotLimit string `json:"snapshotlimit,omitempty" doc:"the total number of snapshots which can be stored by this account"` - SnapshotTotal int64 `json:"snapshottotal,omitempty" doc:"the total number of snapshots stored by this account"` - State string `json:"state,omitempty" doc:"the state of the account"` - TemplateAvailable string `json:"templateavailable,omitempty" doc:"the total number of templates available to be created by this account"` - TemplateLimit string `json:"templatelimit,omitempty" doc:"the total number of templates which can be created by this account"` - TemplateTotal int64 `json:"templatetotal,omitempty" doc:"the total number of templates which have been created by this account"` - User []User `json:"user,omitempty" doc:"the list of users associated with account"` - VMAvailable string `json:"vmavailable,omitempty" doc:"the total number of virtual machines available for this account to acquire"` - VMLimit string `json:"vmlimit,omitempty" doc:"the total number of virtual machines that can be deployed by this account"` - VMRunning int `json:"vmrunning,omitempty" doc:"the total number of virtual machines running for this account"` - VMStopped int `json:"vmstopped,omitempty" doc:"the total number of virtual machines stopped for this account"` - VMTotal int64 `json:"vmtotal,omitempty" doc:"the total number of virtual machines deployed by this account"` - VolumeAvailable string `json:"volumeavailable,omitempty" doc:"the total volume available for this account"` - VolumeLimit string `json:"volumelimit,omitempty" doc:"the total volume which can be used by this account"` - VolumeTotal int64 `json:"volumetotal,omitempty" doc:"the total volume being used by this account"` -} - -// ListRequest builds the ListAccountsGroups request -func (a Account) ListRequest() (ListCommand, error) { - return &ListAccounts{ - ID: a.ID, - State: a.State, - }, nil -} - -//go:generate go run generate/main.go -interface=Listable ListAccounts - -// ListAccounts represents a query to display the accounts -type ListAccounts struct { - ID *UUID `json:"id,omitempty" doc:"List account by account ID"` - IsCleanUpRequired *bool `json:"iscleanuprequired,omitempty" doc:"list accounts by cleanuprequired attribute (values are true or false)"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List account by account name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - State string `json:"state,omitempty" doc:"List accounts by state. Valid states are enabled, disabled, and locked."` - _ bool `name:"listAccounts" description:"Lists accounts and provides detailed account information for listed accounts"` -} - -// ListAccountsResponse represents a list of accounts -type ListAccountsResponse struct { - Count int `json:"count"` - Account []Account `json:"account"` -} diff --git a/vendor/github.com/exoscale/egoscale/accounts_response.go b/vendor/github.com/exoscale/egoscale/accounts_response.go deleted file mode 100644 index 106daca32..000000000 --- a/vendor/github.com/exoscale/egoscale/accounts_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAccounts) Response() interface{} { - return new(ListAccountsResponse) -} - -// ListRequest returns itself -func (ls *ListAccounts) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAccounts) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAccounts) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAccounts) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAccountsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAccountsResponse was expected, got %T", resp)) - return - } - - for i := range items.Account { - if !callback(&items.Account[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/addresses.go b/vendor/github.com/exoscale/egoscale/addresses.go deleted file mode 100644 index 602915f7d..000000000 --- a/vendor/github.com/exoscale/egoscale/addresses.go +++ /dev/null @@ -1,156 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net" -) - -// IPAddress represents an IP Address -type IPAddress struct { - Allocated string `json:"allocated,omitempty" doc:"date the public IP address was acquired"` - Associated string `json:"associated,omitempty" doc:"date the public IP address was associated"` - AssociatedNetworkID *UUID `json:"associatednetworkid,omitempty" doc:"the ID of the Network associated with the IP address"` - AssociatedNetworkName string `json:"associatednetworkname,omitempty" doc:"the name of the Network associated with the IP address"` - ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"` - ID *UUID `json:"id,omitempty" doc:"public IP address id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"public IP address"` - IsElastic bool `json:"iselastic,omitempty" doc:"is an elastic ip"` - IsPortable bool `json:"isportable,omitempty" doc:"is public IP portable across the zones"` - IsSourceNat bool `json:"issourcenat,omitempty" doc:"true if the IP address is a source nat address, false otherwise"` - IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"true if this ip is for static nat, false otherwise"` - IsSystem bool `json:"issystem,omitempty" doc:"true if this ip is system ip (was allocated as a part of deployVm or createLbRule)"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the Network where ip belongs to"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the physical network this belongs to"` - Purpose string `json:"purpose,omitempty" doc:"purpose of the IP address. In Acton this value is not null for Ips with isSystem=true, and can have either StaticNat or LB value"` - ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the ip address"` - State string `json:"state,omitempty" doc:"State of the ip address. Can be: Allocatin, Allocated and Releasing"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with ip address"` - VirtualMachineDisplayName string `json:"virtualmachinedisplayname,omitempty" doc:"virtual machine display name the ip address is assigned to (not null only for static nat Ip)"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"virtual machine id the ip address is assigned to (not null only for static nat Ip)"` - VirtualMachineName string `json:"virtualmachinename,omitempty" doc:"virtual machine name the ip address is assigned to (not null only for static nat Ip)"` - VlanID *UUID `json:"vlanid,omitempty" doc:"the ID of the VLAN associated with the IP address. This parameter is visible to ROOT admins only"` - VlanName string `json:"vlanname,omitempty" doc:"the VLAN associated with the IP address"` - VMIPAddress net.IP `json:"vmipaddress,omitempty" doc:"virtual machine (dnat) ip address (not null only for static nat Ip)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the zone the public IP address belongs to"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the public IP address belongs to"` -} - -// ResourceType returns the type of the resource -func (IPAddress) ResourceType() string { - return "PublicIpAddress" -} - -// ListRequest builds the ListAdresses request -func (ipaddress IPAddress) ListRequest() (ListCommand, error) { - req := &ListPublicIPAddresses{ - AssociatedNetworkID: ipaddress.AssociatedNetworkID, - ID: ipaddress.ID, - IPAddress: ipaddress.IPAddress, - PhysicalNetworkID: ipaddress.PhysicalNetworkID, - VlanID: ipaddress.VlanID, - ZoneID: ipaddress.ZoneID, - } - if ipaddress.IsElastic { - req.IsElastic = &ipaddress.IsElastic - } - if ipaddress.IsSourceNat { - req.IsSourceNat = &ipaddress.IsSourceNat - } - if ipaddress.ForVirtualNetwork { - req.ForVirtualNetwork = &ipaddress.ForVirtualNetwork - } - - return req, nil -} - -// Delete removes the resource -func (ipaddress IPAddress) Delete(ctx context.Context, client *Client) error { - if ipaddress.ID == nil { - return fmt.Errorf("an IPAddress may only be deleted using ID") - } - - return client.BooleanRequestWithContext(ctx, &DisassociateIPAddress{ - ID: ipaddress.ID, - }) -} - -// AssociateIPAddress (Async) represents the IP creation -type AssociateIPAddress struct { - IsPortable *bool `json:"isportable,omitempty" doc:"should be set to true if public IP is required to be transferable across zones, if not specified defaults to false"` - NetworkdID *UUID `json:"networkid,omitempty" doc:"The network this ip address should be associated to."` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the availability zone you want to acquire an public IP address from"` - _ bool `name:"associateIpAddress" description:"Acquires and associates a public IP to an account."` -} - -// Response returns the struct to unmarshal -func (AssociateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AssociateIPAddress) AsyncResponse() interface{} { - return new(IPAddress) -} - -// DisassociateIPAddress (Async) represents the IP deletion -type DisassociateIPAddress struct { - ID *UUID `json:"id" doc:"the id of the public ip address to disassociate"` - _ bool `name:"disassociateIpAddress" description:"Disassociates an ip address from the account."` -} - -// Response returns the struct to unmarshal -func (DisassociateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DisassociateIPAddress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// UpdateIPAddress (Async) represents the IP modification -type UpdateIPAddress struct { - ID *UUID `json:"id" doc:"the id of the public ip address to update"` - CustomID *UUID `json:"customid,omitempty" doc:"an optional field, in case you want to set a custom id to the resource. Allowed to Root Admins only"` - _ bool `name:"updateIpAddress" description:"Updates an ip address"` -} - -// Response returns the struct to unmarshal -func (UpdateIPAddress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateIPAddress) AsyncResponse() interface{} { - return new(IPAddress) -} - -//go:generate go run generate/main.go -interface=Listable ListPublicIPAddresses - -// ListPublicIPAddresses represents a search for public IP addresses -type ListPublicIPAddresses struct { - AllocatedOnly *bool `json:"allocatedonly,omitempty" doc:"limits search results to allocated public IP addresses"` - AssociatedNetworkID *UUID `json:"associatednetworkid,omitempty" doc:"lists all public IP addresses associated to the network specified"` - ForLoadBalancing *bool `json:"forloadbalancing,omitempty" doc:"list only ips used for load balancing"` - ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the IP address"` - ID *UUID `json:"id,omitempty" doc:"lists ip address by id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"lists the specified IP address"` - IsElastic *bool `json:"iselastic,omitempty" doc:"list only elastic ip addresses"` - IsSourceNat *bool `json:"issourcenat,omitempty" doc:"list only source nat ip addresses"` - IsStaticNat *bool `json:"isstaticnat,omitempty" doc:"list only static nat ip addresses"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"lists all public IP addresses by physical network id"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - VlanID *UUID `json:"vlanid,omitempty" doc:"lists all public IP addresses by VLAN ID"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"lists all public IP addresses by Zone ID"` - _ bool `name:"listPublicIpAddresses" description:"Lists all public ip addresses"` -} - -// ListPublicIPAddressesResponse represents a list of public IP addresses -type ListPublicIPAddressesResponse struct { - Count int `json:"count"` - PublicIPAddress []IPAddress `json:"publicipaddress"` -} diff --git a/vendor/github.com/exoscale/egoscale/affinity_groups.go b/vendor/github.com/exoscale/egoscale/affinity_groups.go deleted file mode 100644 index 61b979a28..000000000 --- a/vendor/github.com/exoscale/egoscale/affinity_groups.go +++ /dev/null @@ -1,158 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net/url" -) - -// AffinityGroup represents an (anti-)affinity group -// -// Affinity and Anti-Affinity groups provide a way to influence where VMs should run. -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#affinity-groups -type AffinityGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the affinity group"` - Description string `json:"description,omitempty" doc:"the description of the affinity group"` - ID *UUID `json:"id,omitempty" doc:"the ID of the affinity group"` - Name string `json:"name,omitempty" doc:"the name of the affinity group"` - Type string `json:"type,omitempty" doc:"the type of the affinity group"` - VirtualMachineIDs []UUID `json:"virtualmachineIds,omitempty" doc:"virtual machine Ids associated with this affinity group"` -} - -// ListRequest builds the ListAffinityGroups request -func (ag AffinityGroup) ListRequest() (ListCommand, error) { - return &ListAffinityGroups{ - ID: ag.ID, - Name: ag.Name, - }, nil -} - -// Delete removes the given Affinity Group -func (ag AffinityGroup) Delete(ctx context.Context, client *Client) error { - if ag.ID == nil && ag.Name == "" { - return fmt.Errorf("an Affinity Group may only be deleted using ID or Name") - } - - req := &DeleteAffinityGroup{} - - if ag.ID != nil { - req.ID = ag.ID - } else { - req.Name = ag.Name - } - - return client.BooleanRequestWithContext(ctx, req) -} - -// AffinityGroupType represent an affinity group type -type AffinityGroupType struct { - Type string `json:"type,omitempty" doc:"the type of the affinity group"` -} - -// CreateAffinityGroup (Async) represents a new (anti-)affinity group -type CreateAffinityGroup struct { - Description string `json:"description,omitempty" doc:"Optional description of the affinity group"` - Name string `json:"name,omitempty" doc:"Name of the affinity group"` - Type string `json:"type" doc:"Type of the affinity group from the available affinity/anti-affinity group types"` - _ bool `name:"createAffinityGroup" description:"Creates an affinity/anti-affinity group"` -} - -func (req CreateAffinityGroup) onBeforeSend(params url.Values) error { - // Name must be set, but can be empty - if req.Name == "" { - params.Set("name", "") - } - return nil -} - -// Response returns the struct to unmarshal -func (CreateAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateAffinityGroup) AsyncResponse() interface{} { - return new(AffinityGroup) -} - -// UpdateVMAffinityGroup (Async) represents a modification of a (anti-)affinity group -type UpdateVMAffinityGroup struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - AffinityGroupIDs []UUID `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"` - AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"` - _ bool `name:"updateVMAffinityGroup" description:"Updates the affinity/anti-affinity group associations of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect."` -} - -func (req UpdateVMAffinityGroup) onBeforeSend(params url.Values) error { - // Either AffinityGroupIDs or AffinityGroupNames must be set - if len(req.AffinityGroupIDs) == 0 && len(req.AffinityGroupNames) == 0 { - params.Set("affinitygroupids", "") - } - return nil -} - -// Response returns the struct to unmarshal -func (UpdateVMAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateVMAffinityGroup) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// DeleteAffinityGroup (Async) represents an (anti-)affinity group to be deleted -type DeleteAffinityGroup struct { - ID *UUID `json:"id,omitempty" doc:"The ID of the affinity group. Mutually exclusive with name parameter"` - Name string `json:"name,omitempty" doc:"The name of the affinity group. Mutually exclusive with ID parameter"` - _ bool `name:"deleteAffinityGroup" description:"Deletes affinity group"` -} - -// Response returns the struct to unmarshal -func (DeleteAffinityGroup) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteAffinityGroup) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListAffinityGroups - -// ListAffinityGroups represents an (anti-)affinity groups search -type ListAffinityGroups struct { - ID *UUID `json:"id,omitempty" doc:"List the affinity group by the ID provided"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"Lists affinity groups by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Type string `json:"type,omitempty" doc:"Lists affinity groups by type"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"Lists affinity groups by virtual machine ID"` - _ bool `name:"listAffinityGroups" description:"Lists affinity groups"` -} - -// ListAffinityGroupsResponse represents a list of (anti-)affinity groups -type ListAffinityGroupsResponse struct { - Count int `json:"count"` - AffinityGroup []AffinityGroup `json:"affinitygroup"` -} - -// ListAffinityGroupTypes represents an (anti-)affinity groups search -type ListAffinityGroupTypes struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listAffinityGroupTypes" description:"Lists affinity group types available"` -} - -// Response returns the struct to unmarshal -func (ListAffinityGroupTypes) Response() interface{} { - return new(ListAffinityGroupTypesResponse) -} - -// ListAffinityGroupTypesResponse represents a list of (anti-)affinity group types -type ListAffinityGroupTypesResponse struct { - Count int `json:"count"` - AffinityGroupType []AffinityGroupType `json:"affinitygrouptype"` -} diff --git a/vendor/github.com/exoscale/egoscale/affinitygroups_response.go b/vendor/github.com/exoscale/egoscale/affinitygroups_response.go deleted file mode 100644 index 12c5bd747..000000000 --- a/vendor/github.com/exoscale/egoscale/affinitygroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAffinityGroups) Response() interface{} { - return new(ListAffinityGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListAffinityGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAffinityGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAffinityGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAffinityGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAffinityGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAffinityGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.AffinityGroup { - if !callback(&items.AffinityGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/apis.go b/vendor/github.com/exoscale/egoscale/apis.go deleted file mode 100644 index 098a03761..000000000 --- a/vendor/github.com/exoscale/egoscale/apis.go +++ /dev/null @@ -1,48 +0,0 @@ -package egoscale - -// API represents an API service -type API struct { - Description string `json:"description,omitempty" doc:"description of the api"` - IsAsync bool `json:"isasync" doc:"true if api is asynchronous"` - Name string `json:"name,omitempty" doc:"the name of the api command"` - Related string `json:"related,omitempty" doc:"comma separated related apis"` - Since string `json:"since,omitempty" doc:"version of CloudStack the api was introduced in"` - Type string `json:"type,omitempty" doc:"response field type"` - Params []APIParam `json:"params,omitempty" doc:"the list params the api accepts"` - Response []APIField `json:"response,omitempty" doc:"api response fields"` -} - -// APIParam represents an API parameter field -type APIParam struct { - Description string `json:"description"` - Length int64 `json:"length"` - Name string `json:"name"` - Required bool `json:"required"` - Since string `json:"since,omitempty"` - Type string `json:"type"` -} - -// APIField represents an API response field -type APIField struct { - Description string `json:"description"` - Name string `json:"name"` - Response []APIField `json:"response,omitempty"` - Type string `json:"type"` -} - -// ListAPIs represents a query to list the api -type ListAPIs struct { - Name string `json:"name,omitempty" doc:"API name"` - _ bool `name:"listApis" description:"lists all available apis on the server"` -} - -// ListAPIsResponse represents a list of API -type ListAPIsResponse struct { - Count int `json:"count"` - API []API `json:"api"` -} - -// Response returns the struct to unmarshal -func (*ListAPIs) Response() interface{} { - return new(ListAPIsResponse) -} diff --git a/vendor/github.com/exoscale/egoscale/async_jobs.go b/vendor/github.com/exoscale/egoscale/async_jobs.go deleted file mode 100644 index d815aabda..000000000 --- a/vendor/github.com/exoscale/egoscale/async_jobs.go +++ /dev/null @@ -1,96 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "errors" -) - -// AsyncJobResult represents an asynchronous job result -type AsyncJobResult struct { - AccountID *UUID `json:"accountid,omitempty" doc:"the account that executed the async command"` - Cmd string `json:"cmd,omitempty" doc:"the async command executed"` - Created string `json:"created,omitempty" doc:"the created date of the job"` - JobID *UUID `json:"jobid" doc:"extra field for the initial async call"` - JobInstanceID *UUID `json:"jobinstanceid,omitempty" doc:"the unique ID of the instance/entity object related to the job"` - JobInstanceType string `json:"jobinstancetype,omitempty" doc:"the instance/entity object related to the job"` - JobProcStatus int `json:"jobprocstatus,omitempty" doc:"the progress information of the PENDING job"` - JobResult *json.RawMessage `json:"jobresult,omitempty" doc:"the result reason"` - JobResultCode int `json:"jobresultcode,omitempty" doc:"the result code for the job"` - JobResultType string `json:"jobresulttype,omitempty" doc:"the result type"` - JobStatus JobStatusType `json:"jobstatus,omitempty" doc:"the current job status-should be 0 for PENDING"` - UserID *UUID `json:"userid,omitempty" doc:"the user that executed the async command"` -} - -// ListRequest buils the (empty) ListAsyncJobs request -func (a AsyncJobResult) ListRequest() (ListCommand, error) { - req := &ListAsyncJobs{ - StartDate: a.Created, - } - - return req, nil -} - -// Error builds an error message from the result -func (a AsyncJobResult) Error() error { - r := new(ErrorResponse) - if e := json.Unmarshal(*a.JobResult, r); e != nil { - return e - } - return r -} - -// QueryAsyncJobResult represents a query to fetch the status of async job -type QueryAsyncJobResult struct { - JobID *UUID `json:"jobid" doc:"the ID of the asynchronous job"` - _ bool `name:"queryAsyncJobResult" description:"Retrieves the current status of asynchronous job."` -} - -// Response returns the struct to unmarshal -func (QueryAsyncJobResult) Response() interface{} { - return new(AsyncJobResult) -} - -//go:generate go run generate/main.go -interface=Listable ListAsyncJobs - -// ListAsyncJobs list the asynchronous jobs -type ListAsyncJobs struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - StartDate string `json:"startdate,omitempty" doc:"the start date of the async job"` - _ bool `name:"listAsyncJobs" description:"Lists all pending asynchronous jobs for the account."` -} - -// ListAsyncJobsResponse represents a list of job results -type ListAsyncJobsResponse struct { - Count int `json:"count"` - AsyncJob []AsyncJobResult `json:"asyncjobs"` -} - -// Result unmarshals the result of an AsyncJobResult into the given interface -func (a AsyncJobResult) Result(i interface{}) error { - if a.JobStatus == Failure { - return a.Error() - } - - if a.JobStatus == Success { - m := map[string]json.RawMessage{} - err := json.Unmarshal(*(a.JobResult), &m) - - if err == nil { - if len(m) >= 1 { - if _, ok := m["success"]; ok { - return json.Unmarshal(*(a.JobResult), i) - } - - // otherwise, pick the first key - for k := range m { - return json.Unmarshal(m[k], i) - } - } - return errors.New("empty response") - } - } - - return nil -} diff --git a/vendor/github.com/exoscale/egoscale/asyncjobs_response.go b/vendor/github.com/exoscale/egoscale/asyncjobs_response.go deleted file mode 100644 index e4744e8bd..000000000 --- a/vendor/github.com/exoscale/egoscale/asyncjobs_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListAsyncJobs) Response() interface{} { - return new(ListAsyncJobsResponse) -} - -// ListRequest returns itself -func (ls *ListAsyncJobs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListAsyncJobs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListAsyncJobs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListAsyncJobs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListAsyncJobsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListAsyncJobsResponse was expected, got %T", resp)) - return - } - - for i := range items.AsyncJob { - if !callback(&items.AsyncJob[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/cidr.go b/vendor/github.com/exoscale/egoscale/cidr.go deleted file mode 100644 index 74c054b71..000000000 --- a/vendor/github.com/exoscale/egoscale/cidr.go +++ /dev/null @@ -1,62 +0,0 @@ -package egoscale - -import ( - "bytes" - "encoding/json" - "fmt" - "net" -) - -// CIDR represents a nicely JSON serializable net.IPNet -type CIDR struct { - net.IPNet -} - -// UnmarshalJSON unmarshals the raw JSON into the MAC address -func (cidr *CIDR) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - c, err := ParseCIDR(s) - if err != nil { - return err - } - *cidr = CIDR{c.IPNet} - - return nil -} - -// MarshalJSON converts the CIDR to a string representation -func (cidr CIDR) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", cidr)), nil -} - -// String returns the string representation of a CIDR -func (cidr CIDR) String() string { - return cidr.IPNet.String() -} - -// ParseCIDR parses a CIDR from a string -func ParseCIDR(s string) (*CIDR, error) { - _, net, err := net.ParseCIDR(s) - if err != nil { - return nil, err - } - return &CIDR{*net}, nil -} - -// MustParseCIDR forces parseCIDR or panics -func MustParseCIDR(s string) *CIDR { - cidr, err := ParseCIDR(s) - if err != nil { - panic(err) - } - - return cidr -} - -// Equal compare two CIDR -func (cidr CIDR) Equal(c CIDR) bool { - return (cidr.IPNet.IP.Equal(c.IPNet.IP) && bytes.Equal(cidr.IPNet.Mask, c.IPNet.Mask)) -} diff --git a/vendor/github.com/exoscale/egoscale/client.go b/vendor/github.com/exoscale/egoscale/client.go deleted file mode 100644 index 083deddc5..000000000 --- a/vendor/github.com/exoscale/egoscale/client.go +++ /dev/null @@ -1,410 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "io/ioutil" - "log" - "net/http" - "net/http/httputil" - "os" - "reflect" - "strings" - "time" -) - -// Taggable represents a resource to which tags can be attached -// -// This is a helper to fill the resourcetype of a CreateTags call -type Taggable interface { - // ResourceType is the name of the Taggable type - ResourceType() string -} - -// Deletable represents an Interface that can be "Delete" by the client -type Deletable interface { - // Delete removes the given resource(s) or throws - Delete(context context.Context, client *Client) error -} - -// Listable represents an Interface that can be "List" by the client -type Listable interface { - // ListRequest builds the list command - ListRequest() (ListCommand, error) -} - -// Client represents the API client -type Client struct { - // HTTPClient holds the HTTP client - HTTPClient *http.Client - // Endpoint is the HTTP URL - Endpoint string - // APIKey is the API identifier - APIKey string - // apisecret is the API secret, hence non exposed - apiSecret string - // PageSize represents the default size for a paginated result - PageSize int - // Timeout represents the default timeout for the async requests - Timeout time.Duration - // Expiration representation how long a signed payload may be used - Expiration time.Duration - // RetryStrategy represents the waiting strategy for polling the async requests - RetryStrategy RetryStrategyFunc - // Logger contains any log, plug your own - Logger *log.Logger -} - -// RetryStrategyFunc represents a how much time to wait between two calls to the API -type RetryStrategyFunc func(int64) time.Duration - -// IterateItemFunc represents the callback to iterate a list of results, if false stops -type IterateItemFunc func(interface{}, error) bool - -// WaitAsyncJobResultFunc represents the callback to wait a results of an async request, if false stops -type WaitAsyncJobResultFunc func(*AsyncJobResult, error) bool - -// NewClient creates an API client with default timeout (60) -// -// Timeout is set to both the HTTP client and the client itself. -func NewClient(endpoint, apiKey, apiSecret string) *Client { - timeout := 60 * time.Second - expiration := 10 * time.Minute - - httpClient := &http.Client{ - Transport: http.DefaultTransport, - } - - client := &Client{ - HTTPClient: httpClient, - Endpoint: endpoint, - APIKey: apiKey, - apiSecret: apiSecret, - PageSize: 50, - Timeout: timeout, - Expiration: expiration, - RetryStrategy: MonotonicRetryStrategyFunc(2), - Logger: log.New(ioutil.Discard, "", 0), - } - - if prefix, ok := os.LookupEnv("EXOSCALE_TRACE"); ok { - client.Logger = log.New(os.Stderr, prefix, log.LstdFlags) - client.TraceOn() - } - - return client -} - -// Get populates the given resource or fails -func (client *Client) Get(ls Listable) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.GetWithContext(ctx, ls) -} - -// GetWithContext populates the given resource or fails -func (client *Client) GetWithContext(ctx context.Context, ls Listable) (interface{}, error) { - gs, err := client.ListWithContext(ctx, ls) - if err != nil { - return nil, err - } - - count := len(gs) - if count != 1 { - req, err := ls.ListRequest() - if err != nil { - return nil, err - } - params, err := client.Payload(req) - if err != nil { - return nil, err - } - - // removing sensitive/useless informations - params.Del("expires") - params.Del("response") - params.Del("signature") - params.Del("signatureversion") - - // formatting the query string nicely - payload := params.Encode() - payload = strings.Replace(payload, "&", ", ", -1) - - if count == 0 { - return nil, &ErrorResponse{ - CSErrorCode: ServerAPIException, - ErrorCode: ParamError, - ErrorText: fmt.Sprintf("not found, query: %s", payload), - } - } - return nil, fmt.Errorf("more than one element found: %s", payload) - } - - return gs[0], nil -} - -// Delete removes the given resource of fails -func (client *Client) Delete(g Deletable) error { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.DeleteWithContext(ctx, g) -} - -// DeleteWithContext removes the given resource of fails -func (client *Client) DeleteWithContext(ctx context.Context, g Deletable) error { - return g.Delete(ctx, client) -} - -// List lists the given resource (and paginate till the end) -func (client *Client) List(g Listable) ([]interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.ListWithContext(ctx, g) -} - -// ListWithContext lists the given resources (and paginate till the end) -func (client *Client) ListWithContext(ctx context.Context, g Listable) (s []interface{}, err error) { - s = make([]interface{}, 0) - - defer func() { - if e := recover(); e != nil { - if g == nil || reflect.ValueOf(g).IsNil() { - err = fmt.Errorf("g Listable shouldn't be nil, got %#v", g) - return - } - - panic(e) - } - }() - - req, e := g.ListRequest() - if e != nil { - err = e - return - } - client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool { - if item != nil { - s = append(s, item) - return true - } - err = e - return false - }) - - return -} - -// AsyncListWithContext lists the given resources (and paginate till the end) -// -// -// // NB: goroutine may leak if not read until the end. Create a proper context! -// ctx, cancel := context.WithCancel(context.Background()) -// defer cancel() -// -// outChan, errChan := client.AsyncListWithContext(ctx, new(egoscale.VirtualMachine)) -// -// for { -// select { -// case i, ok := <- outChan: -// if ok { -// vm := i.(egoscale.VirtualMachine) -// // ... -// } else { -// outChan = nil -// } -// case err, ok := <- errChan: -// if ok { -// // do something -// } -// // Once an error has been received, you can expect the channels to be closed. -// errChan = nil -// } -// if errChan == nil && outChan == nil { -// break -// } -// } -// -func (client *Client) AsyncListWithContext(ctx context.Context, g Listable) (<-chan interface{}, <-chan error) { - outChan := make(chan interface{}, client.PageSize) - errChan := make(chan error) - - go func() { - defer close(outChan) - defer close(errChan) - - req, err := g.ListRequest() - if err != nil { - errChan <- err - return - } - client.PaginateWithContext(ctx, req, func(item interface{}, e error) bool { - if item != nil { - outChan <- item - return true - } - errChan <- e - return false - }) - }() - - return outChan, errChan -} - -// Paginate runs the ListCommand and paginates -func (client *Client) Paginate(g Listable, callback IterateItemFunc) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - client.PaginateWithContext(ctx, g, callback) -} - -// PaginateWithContext runs the ListCommand as long as the ctx is valid -func (client *Client) PaginateWithContext(ctx context.Context, g Listable, callback IterateItemFunc) { - req, err := g.ListRequest() - if err != nil { - callback(nil, err) - return - } - - pageSize := client.PageSize - - page := 1 - - for { - req.SetPage(page) - req.SetPageSize(pageSize) - resp, err := client.RequestWithContext(ctx, req) - if err != nil { - // in case of 431, the response is knowingly empty - if errResponse, ok := err.(*ErrorResponse); ok && page == 1 && errResponse.ErrorCode == ParamError { - break - } - - callback(nil, err) - break - } - - size := 0 - didErr := false - req.Each(resp, func(element interface{}, err error) bool { - // If the context was cancelled, kill it in flight - if e := ctx.Err(); e != nil { - element = nil - err = e - } - - if callback(element, err) { - size++ - return true - } - - didErr = true - return false - }) - - if size < pageSize || didErr { - break - } - - page++ - } -} - -// APIName returns the name of the given command -func (client *Client) APIName(command Command) string { - // This is due to a limitation of Go<=1.7 - _, ok := command.(*AuthorizeSecurityGroupEgress) - _, okPtr := command.(AuthorizeSecurityGroupEgress) - if ok || okPtr { - return "authorizeSecurityGroupEgress" - } - - info, err := info(command) - if err != nil { - panic(err) - } - return info.Name -} - -// APIDescription returns the description of the given command -func (client *Client) APIDescription(command Command) string { - info, err := info(command) - if err != nil { - return "*missing description*" - } - return info.Description -} - -// Response returns the response structure of the given command -func (client *Client) Response(command Command) interface{} { - switch c := command.(type) { - case AsyncCommand: - return c.AsyncResponse() - default: - return command.Response() - } -} - -// TraceOn activates the HTTP tracer -func (client *Client) TraceOn() { - if _, ok := client.HTTPClient.Transport.(*traceTransport); !ok { - client.HTTPClient.Transport = &traceTransport{ - transport: client.HTTPClient.Transport, - logger: client.Logger, - } - } -} - -// TraceOff deactivates the HTTP tracer -func (client *Client) TraceOff() { - if rt, ok := client.HTTPClient.Transport.(*traceTransport); ok { - client.HTTPClient.Transport = rt.transport - } -} - -// traceTransport contains the original HTTP transport to enable it to be reverted -type traceTransport struct { - transport http.RoundTripper - logger *log.Logger -} - -// RoundTrip executes a single HTTP transaction -func (t *traceTransport) RoundTrip(req *http.Request) (*http.Response, error) { - if dump, err := httputil.DumpRequest(req, true); err == nil { - t.logger.Printf("%s", dump) - } - - resp, err := t.transport.RoundTrip(req) - if err != nil { - return nil, err - } - - if dump, err := httputil.DumpResponse(resp, true); err == nil { - t.logger.Printf("%s", dump) - } - - return resp, nil -} - -// MonotonicRetryStrategyFunc returns a function that waits for n seconds for each iteration -func MonotonicRetryStrategyFunc(seconds int) RetryStrategyFunc { - return func(iteration int64) time.Duration { - return time.Duration(seconds) * time.Second - } -} - -// FibonacciRetryStrategy waits for an increasing amount of time following the Fibonacci sequence -func FibonacciRetryStrategy(iteration int64) time.Duration { - var a, b, i, tmp int64 - a = 0 - b = 1 - for i = 0; i < iteration; i++ { - tmp = a + b - a = b - b = tmp - } - return time.Duration(a) * time.Second -} diff --git a/vendor/github.com/exoscale/egoscale/cserrorcode_string.go b/vendor/github.com/exoscale/egoscale/cserrorcode_string.go deleted file mode 100644 index 4711d5425..000000000 --- a/vendor/github.com/exoscale/egoscale/cserrorcode_string.go +++ /dev/null @@ -1,47 +0,0 @@ -// Code generated by "stringer -type CSErrorCode"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _CSErrorCode_name = "CloudRuntimeExceptionExecutionExceptionHypervisorVersionChangedExceptionCloudExceptionAccountLimitExceptionAgentUnavailableExceptionCloudAuthenticationExceptionConcurrentOperationExceptionConflictingNetworkSettingsExceptionDiscoveredWithErrorExceptionHAStateExceptionInsufficientAddressCapacityExceptionInsufficientCapacityExceptionInsufficientNetworkCapacityExceptionInsufficientServerCapacityExceptionInsufficientStorageCapacityExceptionInternalErrorExceptionInvalidParameterValueExceptionManagementServerExceptionNetworkRuleConflictExceptionPermissionDeniedExceptionResourceAllocationExceptionResourceInUseExceptionResourceUnavailableExceptionStorageUnavailableExceptionUnsupportedServiceExceptionVirtualMachineMigrationExceptionAsyncCommandQueuedRequestLimitExceptionServerAPIException" - -var _CSErrorCode_map = map[CSErrorCode]string{ - 4250: _CSErrorCode_name[0:21], - 4260: _CSErrorCode_name[21:39], - 4265: _CSErrorCode_name[39:72], - 4275: _CSErrorCode_name[72:86], - 4280: _CSErrorCode_name[86:107], - 4285: _CSErrorCode_name[107:132], - 4290: _CSErrorCode_name[132:160], - 4300: _CSErrorCode_name[160:188], - 4305: _CSErrorCode_name[188:223], - 4310: _CSErrorCode_name[223:251], - 4315: _CSErrorCode_name[251:267], - 4320: _CSErrorCode_name[267:303], - 4325: _CSErrorCode_name[303:332], - 4330: _CSErrorCode_name[332:368], - 4335: _CSErrorCode_name[368:403], - 4340: _CSErrorCode_name[403:439], - 4345: _CSErrorCode_name[439:461], - 4350: _CSErrorCode_name[461:491], - 4355: _CSErrorCode_name[491:516], - 4360: _CSErrorCode_name[516:544], - 4365: _CSErrorCode_name[544:569], - 4370: _CSErrorCode_name[569:596], - 4375: _CSErrorCode_name[596:618], - 4380: _CSErrorCode_name[618:646], - 4385: _CSErrorCode_name[646:673], - 4390: _CSErrorCode_name[673:700], - 4395: _CSErrorCode_name[700:732], - 4540: _CSErrorCode_name[732:750], - 4545: _CSErrorCode_name[750:771], - 9999: _CSErrorCode_name[771:789], -} - -func (i CSErrorCode) String() string { - if str, ok := _CSErrorCode_map[i]; ok { - return str - } - return "CSErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" -} diff --git a/vendor/github.com/exoscale/egoscale/dns.go b/vendor/github.com/exoscale/egoscale/dns.go deleted file mode 100644 index 4b6535c14..000000000 --- a/vendor/github.com/exoscale/egoscale/dns.go +++ /dev/null @@ -1,367 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" -) - -// DNSDomain represents a domain -type DNSDomain struct { - ID int64 `json:"id"` - AccountID int64 `json:"account_id,omitempty"` - UserID int64 `json:"user_id,omitempty"` - RegistrantID int64 `json:"registrant_id,omitempty"` - Name string `json:"name"` - UnicodeName string `json:"unicode_name"` - Token string `json:"token"` - State string `json:"state"` - Language string `json:"language,omitempty"` - Lockable bool `json:"lockable"` - AutoRenew bool `json:"auto_renew"` - WhoisProtected bool `json:"whois_protected"` - RecordCount int64 `json:"record_count"` - ServiceCount int64 `json:"service_count"` - ExpiresOn string `json:"expires_on,omitempty"` - CreatedAt string `json:"created_at"` - UpdatedAt string `json:"updated_at"` -} - -// DNSDomainResponse represents a domain creation response -type DNSDomainResponse struct { - Domain *DNSDomain `json:"domain"` -} - -// DNSRecord represents a DNS record -type DNSRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Name string `json:"name"` - TTL int `json:"ttl,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Content string `json:"content"` - RecordType string `json:"record_type"` - Prio int `json:"prio,omitempty"` -} - -// DNSRecordResponse represents the creation of a DNS record -type DNSRecordResponse struct { - Record DNSRecord `json:"record"` -} - -// UpdateDNSRecord represents a DNS record -type UpdateDNSRecord struct { - ID int64 `json:"id,omitempty"` - DomainID int64 `json:"domain_id,omitempty"` - Name string `json:"name,omitempty"` - TTL int `json:"ttl,omitempty"` - CreatedAt string `json:"created_at,omitempty"` - UpdatedAt string `json:"updated_at,omitempty"` - Content string `json:"content,omitempty"` - RecordType string `json:"record_type,omitempty"` - Prio int `json:"prio,omitempty"` -} - -// UpdateDNSRecordResponse represents the creation of a DNS record -type UpdateDNSRecordResponse struct { - Record UpdateDNSRecord `json:"record"` -} - -// DNSErrorResponse represents an error in the API -type DNSErrorResponse struct { - Message string `json:"message,omitempty"` - Errors map[string][]string `json:"errors"` -} - -// Record represent record type -type Record int - -//go:generate stringer -type=Record -const ( - // A record type - A Record = iota - // AAAA record type - AAAA - // ALIAS record type - ALIAS - // CNAME record type - CNAME - // HINFO record type - HINFO - // MX record type - MX - // NAPTR record type - NAPTR - // NS record type - NS - // POOL record type - POOL - // SPF record type - SPF - // SRV record type - SRV - // SSHFP record type - SSHFP - // TXT record type - TXT - // URL record type - URL -) - -// Error formats the DNSerror into a string -func (req *DNSErrorResponse) Error() string { - if len(req.Errors) > 0 { - errs := []string{} - for name, ss := range req.Errors { - if len(ss) > 0 { - errs = append(errs, fmt.Sprintf("%s: %s", name, strings.Join(ss, ", "))) - } - } - return fmt.Sprintf("dns error: %s (%s)", req.Message, strings.Join(errs, "; ")) - } - return fmt.Sprintf("dns error: %s", req.Message) -} - -// CreateDomain creates a DNS domain -func (client *Client) CreateDomain(ctx context.Context, name string) (*DNSDomain, error) { - m, err := json.Marshal(DNSDomainResponse{ - Domain: &DNSDomain{ - Name: name, - }, - }) - if err != nil { - return nil, err - } - - resp, err := client.dnsRequest(ctx, "/v1/domains", nil, string(m), "POST") - if err != nil { - return nil, err - } - - var d *DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - return d.Domain, nil -} - -// GetDomain gets a DNS domain -func (client *Client) GetDomain(ctx context.Context, name string) (*DNSDomain, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name, nil, "", "GET") - if err != nil { - return nil, err - } - - var d *DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - return d.Domain, nil -} - -// GetDomains gets DNS domains -func (client *Client) GetDomains(ctx context.Context) ([]DNSDomain, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains", nil, "", "GET") - if err != nil { - return nil, err - } - - var d []DNSDomainResponse - if err := json.Unmarshal(resp, &d); err != nil { - return nil, err - } - - domains := make([]DNSDomain, len(d)) - for i := range d { - domains[i] = *d[i].Domain - } - return domains, nil -} - -// DeleteDomain delets a DNS domain -func (client *Client) DeleteDomain(ctx context.Context, name string) error { - _, err := client.dnsRequest(ctx, "/v1/domains/"+name, nil, "", "DELETE") - return err -} - -// GetRecord returns a DNS record -func (client *Client) GetRecord(ctx context.Context, domain string, recordID int64) (*DNSRecord, error) { - id := strconv.FormatInt(recordID, 10) - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records/"+id, nil, "", "GET") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// GetRecords returns the DNS records -func (client *Client) GetRecords(ctx context.Context, domain string) ([]DNSRecord, error) { - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records", nil, "", "GET") - if err != nil { - return nil, err - } - - var r []DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - records := make([]DNSRecord, 0, len(r)) - for _, rec := range r { - records = append(records, rec.Record) - } - - return records, nil -} - -// GetRecordsWithFilters returns the DNS records (filters can be empty) -func (client *Client) GetRecordsWithFilters(ctx context.Context, domain, name, recordType string) ([]DNSRecord, error) { - - filters := url.Values{} - if name != "" { - filters.Add("name", name) - } - if recordType != "" { - filters.Add("record_type", recordType) - } - - resp, err := client.dnsRequest(ctx, "/v1/domains/"+domain+"/records", filters, "", "GET") - if err != nil { - return nil, err - } - - var r []DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - records := make([]DNSRecord, 0, len(r)) - for _, rec := range r { - records = append(records, rec.Record) - } - - return records, nil -} - -// CreateRecord creates a DNS record -func (client *Client) CreateRecord(ctx context.Context, name string, rec DNSRecord) (*DNSRecord, error) { - body, err := json.Marshal(DNSRecordResponse{ - Record: rec, - }) - if err != nil { - return nil, err - } - - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records", nil, string(body), "POST") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// UpdateRecord updates a DNS record -func (client *Client) UpdateRecord(ctx context.Context, name string, rec UpdateDNSRecord) (*DNSRecord, error) { - body, err := json.Marshal(UpdateDNSRecordResponse{ - Record: rec, - }) - if err != nil { - return nil, err - } - - id := strconv.FormatInt(rec.ID, 10) - resp, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records/"+id, nil, string(body), "PUT") - if err != nil { - return nil, err - } - - var r DNSRecordResponse - if err = json.Unmarshal(resp, &r); err != nil { - return nil, err - } - - return &(r.Record), nil -} - -// DeleteRecord deletes a record -func (client *Client) DeleteRecord(ctx context.Context, name string, recordID int64) error { - id := strconv.FormatInt(recordID, 10) - _, err := client.dnsRequest(ctx, "/v1/domains/"+name+"/records/"+id, nil, "", "DELETE") - - return err -} - -func (client *Client) dnsRequest(ctx context.Context, uri string, urlValues url.Values, params, method string) (json.RawMessage, error) { - rawURL := client.Endpoint + uri - url, err := url.Parse(rawURL) - if err != nil { - return nil, err - } - - q := url.Query() - for k, vs := range urlValues { - for _, v := range vs { - q.Add(k, v) - } - } - url.RawQuery = q.Encode() - - req, err := http.NewRequest(method, url.String(), strings.NewReader(params)) - if err != nil { - return nil, err - } - - var hdr = make(http.Header) - hdr.Add("X-DNS-TOKEN", client.APIKey+":"+client.apiSecret) - hdr.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - hdr.Add("Accept", "application/json") - if params != "" { - hdr.Add("Content-Type", "application/json") - } - req.Header = hdr - - resp, err := client.HTTPClient.Do(req.WithContext(ctx)) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - contentType := resp.Header.Get("content-type") - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`response content-type expected to be "application/json", got %q`, contentType) - } - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - e := new(DNSErrorResponse) - if err := json.Unmarshal(b, e); err != nil { - return nil, err - } - return nil, e - } - - return b, nil -} diff --git a/vendor/github.com/exoscale/egoscale/doc.go b/vendor/github.com/exoscale/egoscale/doc.go deleted file mode 100644 index 0d9997efa..000000000 --- a/vendor/github.com/exoscale/egoscale/doc.go +++ /dev/null @@ -1,180 +0,0 @@ -/* - -Package egoscale is a mapping for the Exoscale API (https://community.exoscale.com/api/compute/). - -Requests and Responses - -To build a request, construct the adequate struct. This library expects a pointer for efficiency reasons only. The response is a struct corresponding to the data at stake. E.g. DeployVirtualMachine gives a VirtualMachine, as a pointer as well to avoid big copies. - -Then everything within the struct is not a pointer. Find below some examples of how egoscale may be used. If anything feels odd or unclear, please let us know: https://github.com/exoscale/egoscale/issues - - req := &egoscale.DeployVirtualMachine{ - Size: 10, - ServiceOfferingID: egoscale.MustParseUUID("..."), - TemplateID: egoscale.MustParseUUID("..."), - ZoneID: egoscale.MastParseUUID("..."), - } - - fmt.Println("Deployment started") - resp, err := cs.Request(req) - if err != nil { - panic(err) - } - - vm := resp.(*egoscale.VirtualMachine) - fmt.Printf("Virtual Machine ID: %s\n", vm.ID) - -This example deploys a virtual machine while controlling the job status as it goes. It enables a finer control over errors, e.g. HTTP timeout, and eventually a way to kill it of (from the client side). - - req := &egoscale.DeployVirtualMachine{ - Size: 10, - ServiceOfferingID: egoscale.MustParseUUID("..."), - TemplateID: egoscale.MustParseUUID("..."), - ZoneID: egoscale.MustParseUUID("..."), - } - vm := &egoscale.VirtualMachine{} - - fmt.Println("Deployment started") - cs.AsyncRequest(req, func(jobResult *egoscale.AsyncJobResult, err error) bool { - if err != nil { - // any kind of error - panic(err) - } - - // Keep waiting - if jobResult.JobStatus == egoscale.Pending { - fmt.Println("wait...") - return true - } - - // Unmarshal the response into the response struct - if err := jobResult.Response(vm); err != nil { - // JSON unmarshaling error - panic(err) - } - - // Stop waiting - return false - }) - - fmt.Printf("Virtual Machine ID: %s\n", vm.ID) - -Debugging and traces - -As this library is mostly an HTTP client, you can reuse all the existing tools around it. - - cs := egoscale.NewClient("https://api.exoscale.com/compute", "EXO...", "...") - // sets a logger on stderr - cs.Logger = log.New(os.Stderr, "prefix", log.LstdFlags) - // activates the HTTP traces - cs.TraceOn() - -Nota bene: when running the tests or the egoscale library via another tool, e.g. the exo cli, the environment variable EXOSCALE_TRACE=prefix does the above configuration for you. As a developer using egoscale as a library, you'll find it more convenient to plug your favorite io.Writer as it's a Logger. - - -APIs - -All the available APIs on the server and provided by the API Discovery plugin. - - cs := egoscale.NewClient("https://api.exoscale.com/compute", "EXO...", "...") - - resp, err := cs.Request(&egoscale.ListAPIs{}) - if err != nil { - panic(err) - } - - for _, api := range resp.(*egoscale.ListAPIsResponse).API { - fmt.Printf("%s %s\n", api.Name, api.Description) - } - // Output: - // listNetworks Lists all available networks - // ... - -Security Groups - -Security Groups provide a way to isolate traffic to VMs. Rules are added via the two Authorization commands. - - resp, err := cs.Request(&egoscale.CreateSecurityGroup{ - Name: "Load balancer", - Description: "Open HTTP/HTTPS ports from the outside world", - }) - securityGroup := resp.(*egoscale.SecurityGroup) - - resp, err = cs.Request(&egoscale.AuthorizeSecurityGroupIngress{ - Description: "SSH traffic", - SecurityGroupID: securityGroup.ID, - CidrList: []CIDR{ - *egoscale.MustParseCIDR("0.0.0.0/0"), - *egoscale.MustParseCIDR("::/0"), - }, - Protocol: "tcp", - StartPort: 22, - EndPort: 22, - }) - // The modified SecurityGroup is returned - securityGroup := resp.(*egoscale.SecurityGroup) - - // ... - err = client.BooleanRequest(&egoscale.DeleteSecurityGroup{ - ID: securityGroup.ID, - }) - // ... - -Security Group also implement the generic List, Get and Delete interfaces (Listable and Deletable). - - // List all Security Groups - sgs, _ := cs.List(&egoscale.SecurityGroup{}) - for _, s := range sgs { - sg := s.(egoscale.SecurityGroup) - // ... - } - - // Get a Security Group - sgQuery := &egoscale.SecurityGroup{Name: "Load balancer"} - resp, err := cs.Get(sgQuery); err != nil { - ... - } - sg := resp.(*egoscale.SecurityGroup) - - if err := cs.Delete(sg); err != nil { - ... - } - // The SecurityGroup has been deleted - -See: https://community.exoscale.com/documentation/compute/security-groups/ - -Zones - -A Zone corresponds to a Data Center. You may list them. Zone implements the Listable interface, which let you perform a list in two different ways. The first exposes the underlying request while the second one hide them and you only manipulate the structs of your interest. - - // Using ListZones request - req := &egoscale.ListZones{} - resp, err := client.Request(req) - if err != nil { - panic(err) - } - - for _, zone := range resp.(*egoscale.ListZonesResponse) { - ... - } - - // Using client.List - zone := &egoscale.Zone{} - zones, err := client.List(zone) - if err != nil { - panic(err) - } - - for _, z := range zones { - zone := z.(egoscale.Zone) - ... - } - -Elastic IPs - -An Elastic IP is a way to attach an IP address to many Virtual Machines. The API side of the story configures the external environment, like the routing. Some work is required within the machine to properly configure the interfaces. - -See: https://community.exoscale.com/documentation/compute/eip/ - -*/ -package egoscale diff --git a/vendor/github.com/exoscale/egoscale/errorcode_string.go b/vendor/github.com/exoscale/egoscale/errorcode_string.go deleted file mode 100644 index 19711257e..000000000 --- a/vendor/github.com/exoscale/egoscale/errorcode_string.go +++ /dev/null @@ -1,37 +0,0 @@ -// Code generated by "stringer -type ErrorCode"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const ( - _ErrorCode_name_0 = "Unauthorized" - _ErrorCode_name_1 = "MethodNotAllowed" - _ErrorCode_name_2 = "UnsupportedActionError" - _ErrorCode_name_3 = "APILimitExceededMalformedParameterErrorParamError" - _ErrorCode_name_4 = "InternalErrorAccountErrorAccountResourceLimitErrorInsufficientCapacityErrorResourceUnavailableErrorResourceAllocationErrorResourceInUseErrorNetworkRuleConflictError" -) - -var ( - _ErrorCode_index_3 = [...]uint8{0, 16, 39, 49} - _ErrorCode_index_4 = [...]uint8{0, 13, 25, 50, 75, 99, 122, 140, 164} -) - -func (i ErrorCode) String() string { - switch { - case i == 401: - return _ErrorCode_name_0 - case i == 405: - return _ErrorCode_name_1 - case i == 422: - return _ErrorCode_name_2 - case 429 <= i && i <= 431: - i -= 429 - return _ErrorCode_name_3[_ErrorCode_index_3[i]:_ErrorCode_index_3[i+1]] - case 530 <= i && i <= 537: - i -= 530 - return _ErrorCode_name_4[_ErrorCode_index_4[i]:_ErrorCode_index_4[i+1]] - default: - return "ErrorCode(" + strconv.FormatInt(int64(i), 10) + ")" - } -} diff --git a/vendor/github.com/exoscale/egoscale/events.go b/vendor/github.com/exoscale/egoscale/events.go deleted file mode 100644 index c6adbfd69..000000000 --- a/vendor/github.com/exoscale/egoscale/events.go +++ /dev/null @@ -1,76 +0,0 @@ -package egoscale - -// Event represents an event in the system -type Event struct { - Account string `json:"account,omitempty" doc:"the account name for the account that owns the object being acted on in the event (e.g. the owner of the virtual machine, ip address, or security group)"` - Created string `json:"created,omitempty" doc:"the date the event was created"` - Description string `json:"description,omitempty" doc:"a brief description of the event"` - ID *UUID `json:"id" doc:"the ID of the event"` - Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"` - ParentID *UUID `json:"parentid,omitempty" doc:"whether the event is parented"` - State string `json:"state,omitempty" doc:"the state of the event"` - Type string `json:"type,omitempty" doc:"the type of the event (see event types)"` - UserName string `json:"username,omitempty" doc:"the name of the user who performed the action (can be different from the account if an admin is performing an action for a user, e.g. starting/stopping a user's virtual machine)"` -} - -// ListRequest builds the ListEvents request -func (event Event) ListRequest() (ListCommand, error) { - req := &ListEvents{ - ID: event.ID, - Level: event.Level, - Type: event.Type, - } - - return req, nil -} - -// EventType represent a type of event -type EventType struct { - Name string `json:"name,omitempty" doc:"Event Type"` -} - -// ListRequest builds the ListEventTypes request -func (EventType) ListRequest() (ListCommand, error) { - req := &ListEventTypes{} - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListEvents - -// ListEvents list the events -type ListEvents struct { - Duration int `json:"duration,omitempty" doc:"the duration of the event"` - EndDate string `json:"enddate,omitempty" doc:"the end date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"` - EntryTime int `json:"entrytime,omitempty" doc:"the time the event was entered"` - ID *UUID `json:"id,omitempty" doc:"the ID of the event"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Level string `json:"level,omitempty" doc:"the event level (INFO, WARN, ERROR)"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - StartDate string `json:"startdate,omitempty" doc:"the start date range of the list you want to retrieve (use format \"yyyy-MM-dd\" or the new format \"yyyy-MM-dd HH:mm:ss\")"` - Type string `json:"type,omitempty" doc:"the event type (see event types)"` - _ bool `name:"listEvents" description:"A command to list events."` -} - -// ListEventsResponse represents a response of a list query -type ListEventsResponse struct { - Count int `json:"count"` - Event []Event `json:"event"` -} - -//go:generate go run generate/main.go -interface=Listable ListEventTypes - -// ListEventTypes list the event types -type ListEventTypes struct { - Page int `json:"page,omitempty"` // fake - PageSize int `json:"pagesize,omitempty"` // fake - _ bool `name:"listEventTypes" description:"List Event Types"` -} - -// ListEventTypesResponse represents a response of a list query -type ListEventTypesResponse struct { - Count int `json:"count"` - EventType []EventType `json:"eventtype"` - _ bool `name:"listEventTypes" description:"List Event Types"` -} diff --git a/vendor/github.com/exoscale/egoscale/events_response.go b/vendor/github.com/exoscale/egoscale/events_response.go deleted file mode 100644 index 2af10cf45..000000000 --- a/vendor/github.com/exoscale/egoscale/events_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListEvents) Response() interface{} { - return new(ListEventsResponse) -} - -// ListRequest returns itself -func (ls *ListEvents) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListEvents) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListEvents) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListEvents) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListEventsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListEventsResponse was expected, got %T", resp)) - return - } - - for i := range items.Event { - if !callback(&items.Event[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/eventtypes_response.go b/vendor/github.com/exoscale/egoscale/eventtypes_response.go deleted file mode 100644 index 073d9648f..000000000 --- a/vendor/github.com/exoscale/egoscale/eventtypes_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListEventTypes) Response() interface{} { - return new(ListEventTypesResponse) -} - -// ListRequest returns itself -func (ls *ListEventTypes) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListEventTypes) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListEventTypes) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListEventTypes) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListEventTypesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListEventTypesResponse was expected, got %T", resp)) - return - } - - for i := range items.EventType { - if !callback(&items.EventType[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/instance_groups.go b/vendor/github.com/exoscale/egoscale/instance_groups.go deleted file mode 100644 index 52bffba9a..000000000 --- a/vendor/github.com/exoscale/egoscale/instance_groups.go +++ /dev/null @@ -1,71 +0,0 @@ -package egoscale - -// InstanceGroup represents a group of VM -type InstanceGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the instance group"` - Created string `json:"created,omitempty" doc:"time and date the instance group was created"` - ID *UUID `json:"id,omitempty" doc:"the id of the instance group"` - Name string `json:"name,omitempty" doc:"the name of the instance group"` -} - -// ListRequest builds the ListInstanceGroups request -func (ig InstanceGroup) ListRequest() (ListCommand, error) { - req := &ListInstanceGroups{ - ID: ig.ID, - Name: ig.Name, - } - - return req, nil -} - -// CreateInstanceGroup creates a VM group -type CreateInstanceGroup struct { - Name string `json:"name" doc:"the name of the instance group"` - _ bool `name:"createInstanceGroup" description:"Creates a vm group"` -} - -// Response returns the struct to unmarshal -func (CreateInstanceGroup) Response() interface{} { - return new(InstanceGroup) -} - -// UpdateInstanceGroup updates a VM group -type UpdateInstanceGroup struct { - ID *UUID `json:"id" doc:"Instance group ID"` - Name string `json:"name,omitempty" doc:"new instance group name"` - _ bool `name:"updateInstanceGroup" description:"Updates a vm group"` -} - -// Response returns the struct to unmarshal -func (UpdateInstanceGroup) Response() interface{} { - return new(InstanceGroup) -} - -// DeleteInstanceGroup deletes a VM group -type DeleteInstanceGroup struct { - ID *UUID `json:"id" doc:"the ID of the instance group"` - _ bool `name:"deleteInstanceGroup" description:"Deletes a vm group"` -} - -// Response returns the struct to unmarshal -func (DeleteInstanceGroup) Response() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListInstanceGroups - -// ListInstanceGroups lists VM groups -type ListInstanceGroups struct { - ID *UUID `json:"id,omitempty" doc:"List instance groups by ID"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List instance groups by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listInstanceGroups" description:"Lists vm groups"` -} - -// ListInstanceGroupsResponse represents a list of instance groups -type ListInstanceGroupsResponse struct { - Count int `json:"count"` - InstanceGroup []InstanceGroup `json:"instancegroup"` -} diff --git a/vendor/github.com/exoscale/egoscale/instancegroups_response.go b/vendor/github.com/exoscale/egoscale/instancegroups_response.go deleted file mode 100644 index 90fc1dbac..000000000 --- a/vendor/github.com/exoscale/egoscale/instancegroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListInstanceGroups) Response() interface{} { - return new(ListInstanceGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListInstanceGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListInstanceGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListInstanceGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListInstanceGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListInstanceGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListInstanceGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.InstanceGroup { - if !callback(&items.InstanceGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/isos.go b/vendor/github.com/exoscale/egoscale/isos.go deleted file mode 100644 index d9a0ace82..000000000 --- a/vendor/github.com/exoscale/egoscale/isos.go +++ /dev/null @@ -1,94 +0,0 @@ -package egoscale - -// ISO represents an attachable ISO disc -type ISO Template - -// ResourceType returns the type of the resource -func (ISO) ResourceType() string { - return "ISO" -} - -// ListRequest produces the ListIsos command. -func (iso ISO) ListRequest() (ListCommand, error) { - req := &ListISOs{ - ID: iso.ID, - Name: iso.Name, - ZoneID: iso.ZoneID, - } - if iso.Bootable { - *req.Bootable = true - } - if iso.IsFeatured { - req.IsoFilter = "featured" - } - if iso.IsPublic { - *req.IsPublic = true - } - if iso.IsReady { - *req.IsReady = true - } - - for i := range iso.Tags { - req.Tags = append(req.Tags, iso.Tags[i]) - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListISOs - -// ListISOs represents the list all available ISO files request -type ListISOs struct { - _ bool `name:"listIsos" description:"Lists all available ISO files."` - Bootable *bool `json:"bootable,omitempty" doc:"True if the ISO is bootable, false otherwise"` - ID *UUID `json:"id,omitempty" doc:"List ISO by id"` - IsoFilter string `json:"isofilter,omitempty" doc:"Possible values are \"featured\", \"self\", \"selfexecutable\",\"sharedexecutable\",\"executable\", and \"community\". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured. * all : all templates (only usable by admins)."` - IsPublic *bool `json:"ispublic,omitempty" doc:"True if the ISO is publicly available to all users, false otherwise."` - IsReady *bool `json:"isready,omitempty" doc:"True if this ISO is ready to be deployed"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"List all isos by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowRemoved *bool `json:"showremoved,omitempty" doc:"Show removed ISOs as well"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The ID of the zone"` -} - -// ListISOsResponse represents a list of ISO files -type ListISOsResponse struct { - Count int `json:"count"` - ISO []ISO `json:"iso"` -} - -// AttachISO represents the request to attach an ISO to a virtual machine. -type AttachISO struct { - _ bool `name:"attachIso" description:"Attaches an ISO to a virtual machine."` - ID *UUID `json:"id" doc:"the ID of the ISO file"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"the ID of the virtual machine"` -} - -// Response returns the struct to unmarshal -func (AttachISO) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AttachISO) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// DetachISO represents the request to detach an ISO to a virtual machine. -type DetachISO struct { - _ bool `name:"detachIso" description:"Detaches any ISO file (if any) currently attached to a virtual machine."` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"The ID of the virtual machine"` -} - -// Response returns the struct to unmarshal -func (DetachISO) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DetachISO) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/exoscale/egoscale/isos_response.go b/vendor/github.com/exoscale/egoscale/isos_response.go deleted file mode 100644 index 2faa45a88..000000000 --- a/vendor/github.com/exoscale/egoscale/isos_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListISOs) Response() interface{} { - return new(ListISOsResponse) -} - -// ListRequest returns itself -func (ls *ListISOs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListISOs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListISOs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListISOs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListISOsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListISOsResponse was expected, got %T", resp)) - return - } - - for i := range items.ISO { - if !callback(&items.ISO[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/jobstatustype_string.go b/vendor/github.com/exoscale/egoscale/jobstatustype_string.go deleted file mode 100644 index 298561608..000000000 --- a/vendor/github.com/exoscale/egoscale/jobstatustype_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type JobStatusType"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _JobStatusType_name = "PendingSuccessFailure" - -var _JobStatusType_index = [...]uint8{0, 7, 14, 21} - -func (i JobStatusType) String() string { - if i < 0 || i >= JobStatusType(len(_JobStatusType_index)-1) { - return "JobStatusType(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _JobStatusType_name[_JobStatusType_index[i]:_JobStatusType_index[i+1]] -} diff --git a/vendor/github.com/exoscale/egoscale/macaddress.go b/vendor/github.com/exoscale/egoscale/macaddress.go deleted file mode 100644 index 3c1dcaea4..000000000 --- a/vendor/github.com/exoscale/egoscale/macaddress.go +++ /dev/null @@ -1,63 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "fmt" - "net" -) - -// MACAddress is a nicely JSON serializable net.HardwareAddr -type MACAddress net.HardwareAddr - -// String returns the MAC address in standard format -func (mac MACAddress) String() string { - return (net.HardwareAddr)(mac).String() -} - -// MAC48 builds a MAC-48 MACAddress -func MAC48(a, b, c, d, e, f byte) MACAddress { - m := make(MACAddress, 6) - m[0] = a - m[1] = b - m[2] = c - m[3] = d - m[4] = e - m[5] = f - return m -} - -// UnmarshalJSON unmarshals the raw JSON into the MAC address -func (mac *MACAddress) UnmarshalJSON(b []byte) error { - var addr string - if err := json.Unmarshal(b, &addr); err != nil { - return err - } - hw, err := ParseMAC(addr) - if err != nil { - return err - } - - *mac = make(MACAddress, 6) - copy(*mac, hw) - return nil -} - -// MarshalJSON converts the MAC Address to a string representation -func (mac MACAddress) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", mac.String())), nil -} - -// ParseMAC converts a string into a MACAddress -func ParseMAC(s string) (MACAddress, error) { - hw, err := net.ParseMAC(s) - return (MACAddress)(hw), err -} - -// MustParseMAC acts like ParseMAC but panics if in case of an error -func MustParseMAC(s string) MACAddress { - mac, err := ParseMAC(s) - if err != nil { - panic(err) - } - return mac -} diff --git a/vendor/github.com/exoscale/egoscale/network_offerings.go b/vendor/github.com/exoscale/egoscale/network_offerings.go deleted file mode 100644 index 989d5871f..000000000 --- a/vendor/github.com/exoscale/egoscale/network_offerings.go +++ /dev/null @@ -1,91 +0,0 @@ -package egoscale - -// NetworkOffering corresponds to the Compute Offerings -type NetworkOffering struct { - Availability string `json:"availability,omitempty" doc:"availability of the network offering"` - ConserveMode bool `json:"conservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"` - Created string `json:"created,omitempty" doc:"the date this network offering was created"` - Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with network offering"` - DisplayText string `json:"displaytext,omitempty" doc:"an alternate display text of the network offering."` - EgressDefaultPolicy bool `json:"egressdefaultpolicy,omitempty" doc:"true if guest network default egress policy is allow; false if default egress policy is deny"` - GuestIPType string `json:"guestiptype,omitempty" doc:"guest type of the network offering, can be Shared or Isolated"` - ID *UUID `json:"id,omitempty" doc:"the id of the network offering"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if network offering is default, false otherwise"` - IsPersistent bool `json:"ispersistent,omitempty" doc:"true if network offering supports persistent networks, false otherwise"` - MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrents connections to be handled by lb"` - Name string `json:"name,omitempty" doc:"the name of the network offering"` - NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."` - Service []Service `json:"service,omitempty" doc:"the list of supported services"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"the ID of the service offering used by virtual router provider"` - SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network offering supports specifying ip ranges, false otherwise"` - SpecifyVlan bool `json:"specifyvlan,omitempty" doc:"true if network offering supports vlans, false otherwise"` - State string `json:"state,omitempty" doc:"state of the network offering. Can be Disabled/Enabled/Inactive"` - SupportsStrechedL2Subnet bool `json:"supportsstrechedl2subnet,omitempty" doc:"true if network offering supports network that span multiple zones"` - Tags string `json:"tags,omitempty" doc:"the tags for the network offering"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type for the network offering, supported types are Public, Management, Control, Guest, Vlan or Storage."` -} - -// ListRequest builds the ListNetworkOfferings request -// -// This doesn't take into account the IsDefault flag as the default value is true. -func (no NetworkOffering) ListRequest() (ListCommand, error) { - req := &ListNetworkOfferings{ - Availability: no.Availability, - ID: no.ID, - Name: no.Name, - State: no.State, - TrafficType: no.TrafficType, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListNetworkOfferings - -// ListNetworkOfferings represents a query for network offerings -type ListNetworkOfferings struct { - Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required"` - DisplayText string `json:"displaytext,omitempty" doc:"list network offerings by display text"` - GuestIPType string `json:"guestiptype,omitempty" doc:"list network offerings by guest type: Shared or Isolated"` - ID *UUID `json:"id,omitempty" doc:"list network offerings by id"` - IsDefault *bool `json:"isdefault,omitempty" doc:"true if need to list only default network offerings. Default value is false"` - IsTagged *bool `json:"istagged,omitempty" doc:"true if offering has tags specified"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"list network offerings by name"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the network. Pass this in if you want to see the available network offering that a network can be changed to."` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SourceNATSupported *bool `json:"sourcenatsupported,omitempty" doc:"true if need to list only netwok offerings where source nat is supported, false otherwise"` - SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"true if need to list only network offerings which support specifying ip ranges"` - SpecifyVlan *bool `json:"specifyvlan,omitempty" doc:"the tags for the network offering."` - State string `json:"state,omitempty" doc:"list network offerings by state"` - SupportedServices []Service `json:"supportedservices,omitempty" doc:"list network offerings supporting certain services"` - Tags string `json:"tags,omitempty" doc:"list network offerings by tags"` - TrafficType string `json:"traffictype,omitempty" doc:"list by traffic type"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list network offerings available for network creation in specific zone"` - _ bool `name:"listNetworkOfferings" description:"Lists all available network offerings."` -} - -// ListNetworkOfferingsResponse represents a list of service offerings -type ListNetworkOfferingsResponse struct { - Count int `json:"count"` - NetworkOffering []NetworkOffering `json:"networkoffering"` -} - -// UpdateNetworkOffering represents a modification of a network offering -type UpdateNetworkOffering struct { - Availability string `json:"availability,omitempty" doc:"the availability of network offering. Default value is Required for Guest Virtual network offering; Optional for Guest Direct network offering"` - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network offering"` - ID *UUID `json:"id,omitempty" doc:"the id of the network offering"` - KeepAliveEnabled *bool `json:"keepaliveenabled,omitempty" doc:"if true keepalive will be turned on in the loadbalancer. At the time of writing this has only an effect on haproxy; the mode http and httpclose options are unset in the haproxy conf file."` - MaxConnections int `json:"maxconnections,omitempty" doc:"maximum number of concurrent connections supported by the network offering"` - Name string `json:"name,omitempty" doc:"the name of the network offering"` - SortKey int `json:"sortkey,omitempty" doc:"sort key of the network offering, integer"` - State string `json:"state,omitempty" doc:"update state for the network offering"` - _ bool `name:"updateNetworkOffering" description:"Updates a network offering."` -} - -// Response returns the struct to unmarshal -func (UpdateNetworkOffering) Response() interface{} { - return new(NetworkOffering) -} diff --git a/vendor/github.com/exoscale/egoscale/networkofferings_response.go b/vendor/github.com/exoscale/egoscale/networkofferings_response.go deleted file mode 100644 index 656de7253..000000000 --- a/vendor/github.com/exoscale/egoscale/networkofferings_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNetworkOfferings) Response() interface{} { - return new(ListNetworkOfferingsResponse) -} - -// ListRequest returns itself -func (ls *ListNetworkOfferings) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNetworkOfferings) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNetworkOfferings) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNetworkOfferings) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNetworkOfferingsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNetworkOfferingsResponse was expected, got %T", resp)) - return - } - - for i := range items.NetworkOffering { - if !callback(&items.NetworkOffering[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/networks.go b/vendor/github.com/exoscale/egoscale/networks.go deleted file mode 100644 index 4d6ce12e3..000000000 --- a/vendor/github.com/exoscale/egoscale/networks.go +++ /dev/null @@ -1,229 +0,0 @@ -package egoscale - -import ( - "net" - "net/url" -) - -// Network represents a network -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html -type Network struct { - Account string `json:"account,omitempty" doc:"the owner of the network"` - AccountID *UUID `json:"accountid,omitempty" doc:"the owner ID of the network"` - BroadcastDomainType string `json:"broadcastdomaintype,omitempty" doc:"Broadcast domain type of the network"` - BroadcastURI string `json:"broadcasturi,omitempty" doc:"broadcast uri of the network."` - CanUseForDeploy bool `json:"canusefordeploy,omitempty" doc:"list networks available for vm deployment"` - CIDR *CIDR `json:"cidr,omitempty" doc:"Cloudstack managed address space, all CloudStack managed VMs get IP address from CIDR"` - DisplayText string `json:"displaytext,omitempty" doc:"the displaytext of the network"` - DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the network"` - DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the network"` - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - Gateway net.IP `json:"gateway,omitempty" doc:"the network's gateway"` - ID *UUID `json:"id,omitempty" doc:"the id of the network"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if network is default, false otherwise"` - IsPersistent bool `json:"ispersistent,omitempty" doc:"list networks that are persistent"` - IsSystem bool `json:"issystem,omitempty" doc:"true if network is system, false otherwise"` - Name string `json:"name,omitempty" doc:"the name of the network"` - Netmask net.IP `json:"netmask,omitempty" doc:"the network's netmask"` - NetworkCIDR *CIDR `json:"networkcidr,omitempty" doc:"the network CIDR of the guest network configured with IP reservation. It is the summation of CIDR and RESERVED_IP_RANGE"` - NetworkDomain string `json:"networkdomain,omitempty" doc:"the network domain"` - NetworkOfferingAvailability string `json:"networkofferingavailability,omitempty" doc:"availability of the network offering the network is created from"` - NetworkOfferingConserveMode bool `json:"networkofferingconservemode,omitempty" doc:"true if network offering is ip conserve mode enabled"` - NetworkOfferingDisplayText string `json:"networkofferingdisplaytext,omitempty" doc:"display text of the network offering the network is created from"` - NetworkOfferingID *UUID `json:"networkofferingid,omitempty" doc:"network offering id the network is created from"` - NetworkOfferingName string `json:"networkofferingname,omitempty" doc:"name of the network offering the network is created from"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the physical network id"` - Related string `json:"related,omitempty" doc:"related to what other network configuration"` - ReservedIPRange string `json:"reservediprange,omitempty" doc:"the network's IP range not to be used by CloudStack guest VMs and can be used for non CloudStack purposes"` - RestartRequired bool `json:"restartrequired,omitempty" doc:"true network requires restart"` - Service []Service `json:"service,omitempty" doc:"the list of services"` - SpecifyIPRanges bool `json:"specifyipranges,omitempty" doc:"true if network supports specifying ip ranges, false otherwise"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` - State string `json:"state,omitempty" doc:"state of the network"` - StrechedL2Subnet bool `json:"strechedl2subnet,omitempty" doc:"true if network can span multiple zones"` - SubdomainAccess bool `json:"subdomainaccess,omitempty" doc:"true if users from subdomains can access the domain level network"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with network"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the network"` - Type string `json:"type,omitempty" doc:"the type of the network"` - Vlan string `json:"vlan,omitemtpy" doc:"The vlan of the network. This parameter is visible to ROOT admins only"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"zone id of the network"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone the network belongs to"` - ZonesNetworkSpans []Zone `json:"zonesnetworkspans,omitempty" doc:"If a network is enabled for 'streched l2 subnet' then represents zones on which network currently spans"` -} - -// ListRequest builds the ListNetworks request -func (network Network) ListRequest() (ListCommand, error) { - //TODO add tags support - req := &ListNetworks{ - ID: network.ID, - Keyword: network.Name, // this is a hack as listNetworks doesn't support to search by name. - PhysicalNetworkID: network.PhysicalNetworkID, - TrafficType: network.TrafficType, - Type: network.Type, - ZoneID: network.ZoneID, - } - - if network.CanUseForDeploy { - req.CanUseForDeploy = &network.CanUseForDeploy - } - if network.RestartRequired { - req.RestartRequired = &network.RestartRequired - } - - return req, nil -} - -// ResourceType returns the type of the resource -func (Network) ResourceType() string { - return "Network" -} - -// Service is a feature of a network -type Service struct { - Capability []ServiceCapability `json:"capability,omitempty"` - Name string `json:"name"` - Provider []ServiceProvider `json:"provider,omitempty"` -} - -// ServiceCapability represents optional capability of a service -type ServiceCapability struct { - CanChooseServiceCapability bool `json:"canchooseservicecapability"` - Name string `json:"name"` - Value string `json:"value"` -} - -// ServiceProvider represents the provider of the service -type ServiceProvider struct { - CanEnableIndividualService bool `json:"canenableindividualservice"` - DestinationPhysicalNetworkID *UUID `json:"destinationphysicalnetworkid"` - ID *UUID `json:"id"` - Name string `json:"name"` - PhysicalNetworkID *UUID `json:"physicalnetworkid"` - ServiceList []string `json:"servicelist,omitempty"` -} - -// CreateNetwork creates a network -type CreateNetwork struct { - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the network"` // This field is required but might be empty - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - EndIpv6 net.IP `json:"endipv6,omitempty" doc:"the ending IPv6 address in the IPv6 network range"` - Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the network. Required for Shared networks and Isolated networks when it belongs to VPC"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the CIDR of IPv6 network, must be at least /64"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of the IPv6 network. Required for Shared networks and Isolated networks when it belongs to VPC"` - IsolatedPVlan string `json:"isolatedpvlan,omitempty" doc:"the isolated private vlan for this network"` - Name string `json:"name,omitempty" doc:"the name of the network"` // This field is required but might be empty - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the network. Required for managed networks."` - NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"` - NetworkOfferingID *UUID `json:"networkofferingid" doc:"the network offering id"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"the Physical Network ID the network belongs to"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` - StartIpv6 net.IP `json:"startipv6,omitempty" doc:"the beginning IPv6 address in the IPv6 network range"` - Vlan string `json:"vlan,omitempty" doc:"the ID or VID of the network"` - ZoneID *UUID `json:"zoneid" doc:"the Zone ID for the network"` - _ bool `name:"createNetwork" description:"Creates a network"` -} - -// Response returns the struct to unmarshal -func (CreateNetwork) Response() interface{} { - return new(Network) -} - -func (req CreateNetwork) onBeforeSend(params url.Values) error { - // Those fields are required but might be empty - if req.Name == "" { - params.Set("name", "") - } - if req.DisplayText == "" { - params.Set("displaytext", "") - } - return nil -} - -// UpdateNetwork (Async) updates a network -type UpdateNetwork struct { - _ bool `name:"updateNetwork" description:"Updates a network"` - ChangeCIDR *bool `json:"changecidr,omitempty" doc:"Force update even if cidr type is different"` - DisplayText string `json:"displaytext,omitempty" doc:"the new display text for the network"` - EndIP net.IP `json:"endip,omitempty" doc:"the ending IP address in the network IP range. Required for managed networks."` - GuestVMCIDR *CIDR `json:"guestvmcidr,omitempty" doc:"CIDR for Guest VMs,Cloudstack allocates IPs to Guest VMs only from this CIDR"` - ID *UUID `json:"id" doc:"the ID of the network"` - Name string `json:"name,omitempty" doc:"the new name for the network"` - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the network. Required for managed networks."` - NetworkDomain string `json:"networkdomain,omitempty" doc:"network domain"` - NetworkOfferingID *UUID `json:"networkofferingid,omitempty" doc:"network offering ID"` - StartIP net.IP `json:"startip,omitempty" doc:"the beginning IP address in the network IP range. Required for managed networks."` -} - -// Response returns the struct to unmarshal -func (UpdateNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateNetwork) AsyncResponse() interface{} { - return new(Network) -} - -// RestartNetwork (Async) updates a network -type RestartNetwork struct { - ID *UUID `json:"id" doc:"The id of the network to restart."` - Cleanup *bool `json:"cleanup,omitempty" doc:"If cleanup old network elements"` - _ bool `name:"restartNetwork" description:"Restarts the network; includes 1) restarting network elements - virtual routers, dhcp servers 2) reapplying all public ips 3) reapplying loadBalancing/portForwarding rules"` -} - -// Response returns the struct to unmarshal -func (RestartNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RestartNetwork) AsyncResponse() interface{} { - return new(Network) -} - -// DeleteNetwork deletes a network -type DeleteNetwork struct { - ID *UUID `json:"id" doc:"the ID of the network"` - Forced *bool `json:"forced,omitempty" doc:"Force delete a network. Network will be marked as 'Destroy' even when commands to shutdown and cleanup to the backend fails."` - _ bool `name:"deleteNetwork" description:"Deletes a network"` -} - -// Response returns the struct to unmarshal -func (DeleteNetwork) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteNetwork) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListNetworks - -// ListNetworks represents a query to a network -type ListNetworks struct { - CanUseForDeploy *bool `json:"canusefordeploy,omitempty" doc:"List networks available for vm deployment"` - ID *UUID `json:"id,omitempty" doc:"List networks by id"` - IsSystem *bool `json:"issystem,omitempty" doc:"true If network is system, false otherwise"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - PhysicalNetworkID *UUID `json:"physicalnetworkid,omitempty" doc:"List networks by physical network id"` - RestartRequired *bool `json:"restartrequired,omitempty" doc:"List networks by restartRequired"` - SpecifyIPRanges *bool `json:"specifyipranges,omitempty" doc:"True if need to list only networks which support specifying ip ranges"` - SupportedServices []Service `json:"supportedservices,omitempty" doc:"List networks supporting certain services"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - TrafficType string `json:"traffictype,omitempty" doc:"Type of the traffic"` - Type string `json:"type,omitempty" doc:"The type of the network. Supported values are: Isolated and Shared"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The Zone ID of the network"` - _ bool `name:"listNetworks" description:"Lists all available networks."` -} - -// ListNetworksResponse represents the list of networks -type ListNetworksResponse struct { - Count int `json:"count"` - Network []Network `json:"network"` -} diff --git a/vendor/github.com/exoscale/egoscale/networks_response.go b/vendor/github.com/exoscale/egoscale/networks_response.go deleted file mode 100644 index 058890624..000000000 --- a/vendor/github.com/exoscale/egoscale/networks_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNetworks) Response() interface{} { - return new(ListNetworksResponse) -} - -// ListRequest returns itself -func (ls *ListNetworks) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNetworks) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNetworks) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNetworks) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNetworksResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNetworksResponse was expected, got %T", resp)) - return - } - - for i := range items.Network { - if !callback(&items.Network[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/nics.go b/vendor/github.com/exoscale/egoscale/nics.go deleted file mode 100644 index 10863113f..000000000 --- a/vendor/github.com/exoscale/egoscale/nics.go +++ /dev/null @@ -1,120 +0,0 @@ -package egoscale - -import ( - "net" -) - -// Nic represents a Network Interface Controller (NIC) -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/networking_and_traffic.html#configuring-multiple-ip-addresses-on-a-single-nic -type Nic struct { - BroadcastURI string `json:"broadcasturi,omitempty" doc:"the broadcast uri of the nic"` - DeviceID *UUID `json:"deviceid,omitempty" doc:"device id for the network when plugged into the virtual machine"` - Gateway net.IP `json:"gateway,omitempty" doc:"the gateway of the nic"` - ID *UUID `json:"id,omitempty" doc:"the ID of the nic"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address of network"` - IP6CIDR *CIDR `json:"ip6cidr,omitempty" doc:"the cidr of IPv6 network"` - IP6Gateway net.IP `json:"ip6gateway,omitempty" doc:"the gateway of IPv6 network"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address of the nic"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if nic is default, false otherwise"` - IsolationURI string `json:"isolationuri,omitempty" doc:"the isolation uri of the nic"` - MACAddress MACAddress `json:"macaddress,omitempty" doc:"true if nic is default, false otherwise"` - Netmask net.IP `json:"netmask,omitempty" doc:"the netmask of the nic"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the corresponding network"` - NetworkName string `json:"networkname,omitempty" doc:"the name of the corresponding network"` - ReverseDNS []ReverseDNS `json:"reversedns,omitempty" doc:"the list of PTR record(s) associated with the virtual machine"` - SecondaryIP []NicSecondaryIP `json:"secondaryip,omitempty" doc:"the Secondary ipv4 addr of nic"` - TrafficType string `json:"traffictype,omitempty" doc:"the traffic type of the nic"` - Type string `json:"type,omitempty" doc:"the type of the nic"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"Id of the vm to which the nic belongs"` -} - -// ListRequest build a ListNics request from the given Nic -func (nic Nic) ListRequest() (ListCommand, error) { - req := &ListNics{ - VirtualMachineID: nic.VirtualMachineID, - NicID: nic.ID, - NetworkID: nic.NetworkID, - } - - return req, nil -} - -// NicSecondaryIP represents a link between NicID and IPAddress -type NicSecondaryIP struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the secondary private IP addr"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP address"` - NetworkID *UUID `json:"networkid,omitempty" doc:"the ID of the network"` - NicID *UUID `json:"nicid,omitempty" doc:"the ID of the nic"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the vm"` -} - -//go:generate go run generate/main.go -interface=Listable ListNics - -// ListNics represents the NIC search -type ListNics struct { - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - NetworkID *UUID `json:"networkid,omitempty" doc:"list nic of the specific vm's network"` - NicID *UUID `json:"nicid,omitempty" doc:"the ID of the nic to to list IPs"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the vm"` - _ bool `name:"listNics" description:"list the vm nics IP to NIC"` -} - -// ListNicsResponse represents a list of templates -type ListNicsResponse struct { - Count int `json:"count"` - Nic []Nic `json:"nic"` -} - -// AddIPToNic (Async) represents the assignation of a secondary IP -type AddIPToNic struct { - NicID *UUID `json:"nicid" doc:"the ID of the nic to which you want to assign private IP"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Secondary IP Address"` - _ bool `name:"addIpToNic" description:"Assigns secondary IP to NIC"` -} - -// Response returns the struct to unmarshal -func (AddIPToNic) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AddIPToNic) AsyncResponse() interface{} { - return new(NicSecondaryIP) -} - -// RemoveIPFromNic (Async) represents a deletion request -type RemoveIPFromNic struct { - ID *UUID `json:"id" doc:"the ID of the secondary ip address to nic"` - _ bool `name:"removeIpFromNic" description:"Removes secondary IP from the NIC."` -} - -// Response returns the struct to unmarshal -func (RemoveIPFromNic) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RemoveIPFromNic) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ActivateIP6 (Async) activates the IP6 on the given NIC -// -// Exoscale specific API: https://community.exoscale.ch/api/compute/#activateip6_GET -type ActivateIP6 struct { - NicID *UUID `json:"nicid" doc:"the ID of the nic to which you want to assign the IPv6"` - _ bool `name:"activateIp6" description:"Activate the IPv6 on the VM's nic"` -} - -// Response returns the struct to unmarshal -func (ActivateIP6) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ActivateIP6) AsyncResponse() interface{} { - return new(Nic) -} diff --git a/vendor/github.com/exoscale/egoscale/nics_response.go b/vendor/github.com/exoscale/egoscale/nics_response.go deleted file mode 100644 index dcf960915..000000000 --- a/vendor/github.com/exoscale/egoscale/nics_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListNics) Response() interface{} { - return new(ListNicsResponse) -} - -// ListRequest returns itself -func (ls *ListNics) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListNics) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListNics) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListNics) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListNicsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListNicsResponse was expected, got %T", resp)) - return - } - - for i := range items.Nic { - if !callback(&items.Nic[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/oscategories_response.go b/vendor/github.com/exoscale/egoscale/oscategories_response.go deleted file mode 100644 index 985f875df..000000000 --- a/vendor/github.com/exoscale/egoscale/oscategories_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListOSCategories) Response() interface{} { - return new(ListOSCategoriesResponse) -} - -// ListRequest returns itself -func (ls *ListOSCategories) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListOSCategories) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListOSCategories) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListOSCategories) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListOSCategoriesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListOSCategoriesResponse was expected, got %T", resp)) - return - } - - for i := range items.OSCategory { - if !callback(&items.OSCategory[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go b/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go deleted file mode 100644 index 2ee92bd7a..000000000 --- a/vendor/github.com/exoscale/egoscale/publicipaddresses_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListPublicIPAddresses) Response() interface{} { - return new(ListPublicIPAddressesResponse) -} - -// ListRequest returns itself -func (ls *ListPublicIPAddresses) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListPublicIPAddresses) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListPublicIPAddresses) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListPublicIPAddresses) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListPublicIPAddressesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListPublicIPAddressesResponse was expected, got %T", resp)) - return - } - - for i := range items.PublicIPAddress { - if !callback(&items.PublicIPAddress[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/record_string.go b/vendor/github.com/exoscale/egoscale/record_string.go deleted file mode 100644 index b84303bb7..000000000 --- a/vendor/github.com/exoscale/egoscale/record_string.go +++ /dev/null @@ -1,16 +0,0 @@ -// Code generated by "stringer -type=Record"; DO NOT EDIT. - -package egoscale - -import "strconv" - -const _Record_name = "AAAAAALIASCNAMEHINFOMXNAPTRNSPOOLSPFSRVSSHFPTXTURL" - -var _Record_index = [...]uint8{0, 1, 5, 10, 15, 20, 22, 27, 29, 33, 36, 39, 44, 47, 50} - -func (i Record) String() string { - if i < 0 || i >= Record(len(_Record_index)-1) { - return "Record(" + strconv.FormatInt(int64(i), 10) + ")" - } - return _Record_name[_Record_index[i]:_Record_index[i+1]] -} diff --git a/vendor/github.com/exoscale/egoscale/request.go b/vendor/github.com/exoscale/egoscale/request.go deleted file mode 100644 index f02971477..000000000 --- a/vendor/github.com/exoscale/egoscale/request.go +++ /dev/null @@ -1,405 +0,0 @@ -package egoscale - -import ( - "bytes" - "context" - "crypto/hmac" - "crypto/sha1" - "encoding/base64" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" -) - -// Error formats a CloudStack error into a standard error -func (e ErrorResponse) Error() string { - return fmt.Sprintf("API error %s %d (%s %d): %s", e.ErrorCode, e.ErrorCode, e.CSErrorCode, e.CSErrorCode, e.ErrorText) -} - -// Error formats a CloudStack job response into a standard error -func (e BooleanResponse) Error() error { - if !e.Success { - return fmt.Errorf("API error: %s", e.DisplayText) - } - - return nil -} - -func responseKey(key string) (string, bool) { - // XXX: addIpToNic, activateIp6, restorevmresponse are kind of special - var responseKeys = map[string]string{ - "addiptonicresponse": "addiptovmnicresponse", - "activateip6response": "activateip6nicresponse", - "restorevirtualmachineresponse": "restorevmresponse", - "updatevmaffinitygroupresponse": "updatevirtualmachineresponse", - } - - k, ok := responseKeys[key] - return k, ok -} - -func (client *Client) parseResponse(resp *http.Response, apiName string) (json.RawMessage, error) { - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - m := map[string]json.RawMessage{} - if err := json.Unmarshal(b, &m); err != nil { - return nil, err - } - - key := fmt.Sprintf("%sresponse", strings.ToLower(apiName)) - response, ok := m[key] - if !ok { - if resp.StatusCode >= 400 { - response, ok = m["errorresponse"] - } - - if !ok { - // try again with the special keys - value, ok := responseKey(key) - if ok { - key = value - } - - response, ok = m[key] - - if !ok { - return nil, fmt.Errorf("malformed JSON response %d, %q was expected.\n%s", resp.StatusCode, key, b) - } - } - } - - if resp.StatusCode >= 400 { - errorResponse := new(ErrorResponse) - if e := json.Unmarshal(response, errorResponse); e != nil && errorResponse.ErrorCode <= 0 { - return nil, fmt.Errorf("%d %s", resp.StatusCode, b) - } - return nil, errorResponse - } - - n := map[string]json.RawMessage{} - if err := json.Unmarshal(response, &n); err != nil { - return nil, err - } - - // list response may contain only one key - if len(n) > 1 || strings.HasPrefix(key, "list") { - return response, nil - } - - if len(n) == 1 { - for k := range n { - // boolean response and asyncjob result may also contain - // only one key - if k == "success" || k == "jobid" { - return response, nil - } - return n[k], nil - } - } - - return response, nil -} - -// asyncRequest perform an asynchronous job with a context -func (client *Client) asyncRequest(ctx context.Context, asyncCommand AsyncCommand) (interface{}, error) { - var err error - - resp := asyncCommand.AsyncResponse() - client.AsyncRequestWithContext( - ctx, - asyncCommand, - func(j *AsyncJobResult, e error) bool { - if e != nil { - err = e - return false - } - if j.JobStatus != Pending { - if r := j.Result(resp); r != nil { - err = r - } - return false - } - return true - }, - ) - return resp, err -} - -// SyncRequestWithContext performs a sync request with a context -func (client *Client) SyncRequestWithContext(ctx context.Context, command Command) (interface{}, error) { - body, err := client.request(ctx, command) - if err != nil { - return nil, err - } - - response := command.Response() - b, ok := response.(*BooleanResponse) - if ok { - m := make(map[string]interface{}) - if errUnmarshal := json.Unmarshal(body, &m); errUnmarshal != nil { - return nil, errUnmarshal - } - - b.DisplayText, _ = m["displaytext"].(string) - - if success, okSuccess := m["success"].(string); okSuccess { - b.Success = success == "true" - } - - if success, okSuccess := m["success"].(bool); okSuccess { - b.Success = success - } - - return b, nil - } - - if err := json.Unmarshal(body, response); err != nil { - errResponse := new(ErrorResponse) - if e := json.Unmarshal(body, errResponse); e == nil && errResponse.ErrorCode > 0 { - return errResponse, nil - } - return nil, err - } - - return response, nil -} - -// BooleanRequest performs the given boolean command -func (client *Client) BooleanRequest(command Command) error { - resp, err := client.Request(command) - if err != nil { - return err - } - - if b, ok := resp.(*BooleanResponse); ok { - return b.Error() - } - - panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp)) -} - -// BooleanRequestWithContext performs the given boolean command -func (client *Client) BooleanRequestWithContext(ctx context.Context, command Command) error { - resp, err := client.RequestWithContext(ctx, command) - if err != nil { - return err - } - - if b, ok := resp.(*BooleanResponse); ok { - return b.Error() - } - - panic(fmt.Errorf("command %q is not a proper boolean response. %#v", client.APIName(command), resp)) -} - -// Request performs the given command -func (client *Client) Request(command Command) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.RequestWithContext(ctx, command) -} - -// RequestWithContext preforms a command with a context -func (client *Client) RequestWithContext(ctx context.Context, command Command) (interface{}, error) { - switch c := command.(type) { - case AsyncCommand: - return client.asyncRequest(ctx, c) - default: - return client.SyncRequestWithContext(ctx, command) - } -} - -// SyncRequest performs the command as is -func (client *Client) SyncRequest(command Command) (interface{}, error) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - return client.SyncRequestWithContext(ctx, command) -} - -// AsyncRequest performs the given command -func (client *Client) AsyncRequest(asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) { - ctx, cancel := context.WithTimeout(context.Background(), client.Timeout) - defer cancel() - - client.AsyncRequestWithContext(ctx, asyncCommand, callback) -} - -// AsyncRequestWithContext preforms a request with a context -func (client *Client) AsyncRequestWithContext(ctx context.Context, asyncCommand AsyncCommand, callback WaitAsyncJobResultFunc) { - result, err := client.SyncRequestWithContext(ctx, asyncCommand) - if err != nil { - if !callback(nil, err) { - return - } - } - - jobResult, ok := result.(*AsyncJobResult) - if !ok { - callback(nil, fmt.Errorf("wrong type, AsyncJobResult was expected instead of %T", result)) - } - - // Successful response - if jobResult.JobID == nil || jobResult.JobStatus != Pending { - callback(jobResult, nil) - // without a JobID, the next requests will only fail - return - } - - for iteration := 0; ; iteration++ { - time.Sleep(client.RetryStrategy(int64(iteration))) - - req := &QueryAsyncJobResult{JobID: jobResult.JobID} - resp, err := client.SyncRequestWithContext(ctx, req) - if err != nil && !callback(nil, err) { - return - } - - result, ok := resp.(*AsyncJobResult) - if !ok { - if !callback(nil, fmt.Errorf("wrong type. AsyncJobResult expected, got %T", resp)) { - return - } - } - - if !callback(result, nil) { - return - } - } -} - -// Payload builds the HTTP request params from the given command -func (client *Client) Payload(command Command) (url.Values, error) { - params, err := prepareValues("", command) - if err != nil { - return nil, err - } - if hookReq, ok := command.(onBeforeHook); ok { - if err := hookReq.onBeforeSend(params); err != nil { - return params, err - } - } - params.Set("apikey", client.APIKey) - params.Set("command", client.APIName(command)) - params.Set("response", "json") - - if params.Get("expires") == "" && client.Expiration >= 0 { - params.Set("signatureversion", "3") - params.Set("expires", time.Now().Add(client.Expiration).Local().Format("2006-01-02T15:04:05-0700")) - } - - return params, nil -} - -// Sign signs the HTTP request and returns the signature as as base64 encoding -func (client *Client) Sign(params url.Values) (string, error) { - query := encodeValues(params) - query = strings.ToLower(query) - mac := hmac.New(sha1.New, []byte(client.apiSecret)) - _, err := mac.Write([]byte(query)) - if err != nil { - return "", err - } - - signature := base64.StdEncoding.EncodeToString(mac.Sum(nil)) - return signature, nil -} - -// request makes a Request while being close to the metal -func (client *Client) request(ctx context.Context, command Command) (json.RawMessage, error) { - params, err := client.Payload(command) - if err != nil { - return nil, err - } - signature, err := client.Sign(params) - if err != nil { - return nil, err - } - params.Add("signature", signature) - - method := "GET" - query := params.Encode() - url := fmt.Sprintf("%s?%s", client.Endpoint, query) - - var body io.Reader - // respect Internet Explorer limit of 2048 - if len(url) > 2048 { - url = client.Endpoint - method = "POST" - body = strings.NewReader(query) - } - - request, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - request = request.WithContext(ctx) - request.Header.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - - if method == "POST" { - request.Header.Add("Content-Type", "application/x-www-form-urlencoded") - request.Header.Add("Content-Length", strconv.Itoa(len(query))) - } - - resp, err := client.HTTPClient.Do(request) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - contentType := resp.Header.Get("content-type") - - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`body content-type response expected "application/json", got %q`, contentType) - } - - text, err := client.parseResponse(resp, client.APIName(command)) - if err != nil { - return nil, err - } - - return text, nil -} - -func encodeValues(params url.Values) string { - // This code is borrowed from net/url/url.go - // The way it's encoded by net/url doesn't match - // how CloudStack works to determine the signature. - // - // CloudStack only encodes the values of the query parameters - // and furthermore doesn't use '+' for whitespaces. Therefore - // after encoding the values all '+' are replaced with '%20'. - if params == nil { - return "" - } - - var buf bytes.Buffer - keys := make([]string, 0, len(params)) - for k := range params { - keys = append(keys, k) - } - - sort.Strings(keys) - for _, k := range keys { - prefix := k + "=" - for _, v := range params[k] { - if buf.Len() > 0 { - buf.WriteByte('&') - } - buf.WriteString(prefix) - buf.WriteString(csEncode(v)) - } - } - return buf.String() -} diff --git a/vendor/github.com/exoscale/egoscale/request_type.go b/vendor/github.com/exoscale/egoscale/request_type.go deleted file mode 100644 index 7394e1ad3..000000000 --- a/vendor/github.com/exoscale/egoscale/request_type.go +++ /dev/null @@ -1,184 +0,0 @@ -package egoscale - -import ( - "net/url" -) - -// Command represents a generic request -type Command interface { - Response() interface{} -} - -// AsyncCommand represents a async request -type AsyncCommand interface { - Command - AsyncResponse() interface{} -} - -// ListCommand represents a listing request -type ListCommand interface { - Listable - Command - // SetPage defines the current pages - SetPage(int) - // SetPageSize defines the size of the page - SetPageSize(int) - // Each reads the data from the response and feeds channels, and returns true if we are on the last page - Each(interface{}, IterateItemFunc) -} - -// onBeforeHook represents an action to be done on the params before sending them -// -// This little took helps with issue of relying on JSON serialization logic only. -// `omitempty` may make sense in some cases but not all the time. -type onBeforeHook interface { - onBeforeSend(params url.Values) error -} - -// CommandInfo represents the meta data related to a Command -type CommandInfo struct { - Name string - Description string - RootOnly bool -} - -// JobStatusType represents the status of a Job -type JobStatusType int - -//go:generate stringer -type JobStatusType -const ( - // Pending represents a job in progress - Pending JobStatusType = iota - // Success represents a successfully completed job - Success - // Failure represents a job that has failed to complete - Failure -) - -// ErrorCode represents the CloudStack ApiErrorCode enum -// -// See: https://github.com/apache/cloudstack/blob/master/api/src/main/java/org/apache/cloudstack/api/ApiErrorCode.java -type ErrorCode int - -//go:generate stringer -type ErrorCode -const ( - // Unauthorized represents ... (TODO) - Unauthorized ErrorCode = 401 - // MethodNotAllowed represents ... (TODO) - MethodNotAllowed ErrorCode = 405 - // UnsupportedActionError represents ... (TODO) - UnsupportedActionError ErrorCode = 422 - // APILimitExceeded represents ... (TODO) - APILimitExceeded ErrorCode = 429 - // MalformedParameterError represents ... (TODO) - MalformedParameterError ErrorCode = 430 - // ParamError represents ... (TODO) - ParamError ErrorCode = 431 - - // InternalError represents a server error - InternalError ErrorCode = 530 - // AccountError represents ... (TODO) - AccountError ErrorCode = 531 - // AccountResourceLimitError represents ... (TODO) - AccountResourceLimitError ErrorCode = 532 - // InsufficientCapacityError represents ... (TODO) - InsufficientCapacityError ErrorCode = 533 - // ResourceUnavailableError represents ... (TODO) - ResourceUnavailableError ErrorCode = 534 - // ResourceAllocationError represents ... (TODO) - ResourceAllocationError ErrorCode = 535 - // ResourceInUseError represents ... (TODO) - ResourceInUseError ErrorCode = 536 - // NetworkRuleConflictError represents ... (TODO) - NetworkRuleConflictError ErrorCode = 537 -) - -// CSErrorCode represents the CloudStack CSExceptionErrorCode enum -// -// See: https://github.com/apache/cloudstack/blob/master/utils/src/main/java/com/cloud/utils/exception/CSExceptionErrorCode.java -type CSErrorCode int - -//go:generate stringer -type CSErrorCode -const ( - // CloudRuntimeException ... (TODO) - CloudRuntimeException CSErrorCode = 4250 - // ExecutionException ... (TODO) - ExecutionException CSErrorCode = 4260 - // HypervisorVersionChangedException ... (TODO) - HypervisorVersionChangedException CSErrorCode = 4265 - // CloudException ... (TODO) - CloudException CSErrorCode = 4275 - // AccountLimitException ... (TODO) - AccountLimitException CSErrorCode = 4280 - // AgentUnavailableException ... (TODO) - AgentUnavailableException CSErrorCode = 4285 - // CloudAuthenticationException ... (TODO) - CloudAuthenticationException CSErrorCode = 4290 - // ConcurrentOperationException ... (TODO) - ConcurrentOperationException CSErrorCode = 4300 - // ConflictingNetworksException ... (TODO) - ConflictingNetworkSettingsException CSErrorCode = 4305 - // DiscoveredWithErrorException ... (TODO) - DiscoveredWithErrorException CSErrorCode = 4310 - // HAStateException ... (TODO) - HAStateException CSErrorCode = 4315 - // InsufficientAddressCapacityException ... (TODO) - InsufficientAddressCapacityException CSErrorCode = 4320 - // InsufficientCapacityException ... (TODO) - InsufficientCapacityException CSErrorCode = 4325 - // InsufficientNetworkCapacityException ... (TODO) - InsufficientNetworkCapacityException CSErrorCode = 4330 - // InsufficientServerCapaticyException ... (TODO) - InsufficientServerCapacityException CSErrorCode = 4335 - // InsufficientStorageCapacityException ... (TODO) - InsufficientStorageCapacityException CSErrorCode = 4340 - // InternalErrorException ... (TODO) - InternalErrorException CSErrorCode = 4345 - // InvalidParameterValueException ... (TODO) - InvalidParameterValueException CSErrorCode = 4350 - // ManagementServerException ... (TODO) - ManagementServerException CSErrorCode = 4355 - // NetworkRuleConflictException ... (TODO) - NetworkRuleConflictException CSErrorCode = 4360 - // PermissionDeniedException ... (TODO) - PermissionDeniedException CSErrorCode = 4365 - // ResourceAllocationException ... (TODO) - ResourceAllocationException CSErrorCode = 4370 - // ResourceInUseException ... (TODO) - ResourceInUseException CSErrorCode = 4375 - // ResourceUnavailableException ... (TODO) - ResourceUnavailableException CSErrorCode = 4380 - // StorageUnavailableException ... (TODO) - StorageUnavailableException CSErrorCode = 4385 - // UnsupportedServiceException ... (TODO) - UnsupportedServiceException CSErrorCode = 4390 - // VirtualMachineMigrationException ... (TODO) - VirtualMachineMigrationException CSErrorCode = 4395 - // AsyncCommandQueued ... (TODO) - AsyncCommandQueued CSErrorCode = 4540 - // RequestLimitException ... (TODO) - RequestLimitException CSErrorCode = 4545 - // ServerAPIException ... (TODO) - ServerAPIException CSErrorCode = 9999 -) - -// ErrorResponse represents the standard error response -type ErrorResponse struct { - CSErrorCode CSErrorCode `json:"cserrorcode"` - ErrorCode ErrorCode `json:"errorcode"` - ErrorText string `json:"errortext"` - UUIDList []UUIDItem `json:"uuidList,omitempty"` // uuid*L*ist is not a typo -} - -// UUIDItem represents an item of the UUIDList part of an ErrorResponse -type UUIDItem struct { - Description string `json:"description,omitempty"` - SerialVersionUID int64 `json:"serialVersionUID,omitempty"` - UUID string `json:"uuid"` -} - -// BooleanResponse represents a boolean response (usually after a deletion) -type BooleanResponse struct { - DisplayText string `json:"displaytext,omitempty"` - Success bool `json:"success"` -} diff --git a/vendor/github.com/exoscale/egoscale/resource_limits.go b/vendor/github.com/exoscale/egoscale/resource_limits.go deleted file mode 100644 index 56011dc66..000000000 --- a/vendor/github.com/exoscale/egoscale/resource_limits.go +++ /dev/null @@ -1,100 +0,0 @@ -package egoscale - -// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/configuration/Resource.java - -// ResourceTypeName represents the name of a resource type (for limits) -type ResourceTypeName string - -const ( - // VirtualMachineTypeName is the resource type name of a VM - VirtualMachineTypeName ResourceTypeName = "user_vm" - // IPAddressTypeName is the resource type name of an IP address - IPAddressTypeName ResourceTypeName = "public_ip" - // VolumeTypeName is the resource type name of a volume - VolumeTypeName ResourceTypeName = "volume" - // SnapshotTypeName is the resource type name of a snapshot - SnapshotTypeName ResourceTypeName = "snapshot" - // TemplateTypeName is the resource type name of a template - TemplateTypeName ResourceTypeName = "template" - // ProjectTypeName is the resource type name of a project - ProjectTypeName ResourceTypeName = "project" - // NetworkTypeName is the resource type name of a network - NetworkTypeName ResourceTypeName = "network" - // VPCTypeName is the resource type name of a VPC - VPCTypeName ResourceTypeName = "vpc" - // CPUTypeName is the resource type name of a CPU - CPUTypeName ResourceTypeName = "cpu" - // MemoryTypeName is the resource type name of Memory - MemoryTypeName ResourceTypeName = "memory" - // PrimaryStorageTypeName is the resource type name of primary storage - PrimaryStorageTypeName ResourceTypeName = "primary_storage" - // SecondaryStorageTypeName is the resource type name of secondary storage - SecondaryStorageTypeName ResourceTypeName = "secondary_storage" -) - -// ResourceType represents the ID of a resource type (for limits) -type ResourceType string - -const ( - // VirtualMachineType is the resource type ID of a VM - VirtualMachineType ResourceType = "0" - // IPAddressType is the resource type ID of an IP address - IPAddressType ResourceType = "1" - // VolumeType is the resource type ID of a volume - VolumeType ResourceType = "2" - // SnapshotType is the resource type ID of a snapshot - SnapshotType ResourceType = "3" - // TemplateType is the resource type ID of a template - TemplateType ResourceType = "4" - // ProjectType is the resource type ID of a project - ProjectType ResourceType = "5" - // NetworkType is the resource type ID of a network - NetworkType ResourceType = "6" - // VPCType is the resource type ID of a VPC - VPCType ResourceType = "7" - // CPUType is the resource type ID of a CPU - CPUType ResourceType = "8" - // MemoryType is the resource type ID of Memory - MemoryType ResourceType = "9" - // PrimaryStorageType is the resource type ID of primary storage - PrimaryStorageType ResourceType = "10" - // SecondaryStorageType is the resource type ID of secondary storage - SecondaryStorageType ResourceType = "11" -) - -// ResourceLimit represents the limit on a particular resource -type ResourceLimit struct { - Max int64 `json:"max,omitempty" doc:"the maximum number of the resource. A -1 means the resource currently has no limit."` - ResourceType ResourceType `json:"resourcetype,omitempty" doc:"resource type. Values include 0, 1, 2, 3, 4, 6, 7, 8, 9, 10, 11. See the resourceType parameter for more information on these values."` - ResourceTypeName string `json:"resourcetypename,omitempty" doc:"resource type name. Values include user_vm, public_ip, volume, snapshot, template, network, cpu, memory, primary_storage, secondary_storage."` -} - -// ListRequest builds the ListResourceLimits request -func (limit ResourceLimit) ListRequest() (ListCommand, error) { - req := &ListResourceLimits{ - ResourceType: limit.ResourceType, - ResourceTypeName: limit.ResourceTypeName, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListResourceLimits - -// ListResourceLimits lists the resource limits -type ListResourceLimits struct { - ID int64 `json:"id,omitempty" doc:"Lists resource limits by ID."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceType ResourceType `json:"resourcetype,omitempty" doc:"Type of resource. Values are 0, 1, 2, 3, 4, 6, 8, 9, 10, 11, 12, and 13. 0 - Instance. Number of instances a user can create. 1 - IP. Number of public IP addresses an account can own. 2 - Volume. Number of disk volumes an account can own. 3 - Snapshot. Number of snapshots an account can own. 4 - Template. Number of templates an account can register/create. 6 - Network. Number of networks an account can own. 8 - CPU. Number of CPU an account can allocate for his resources. 9 - Memory. Amount of RAM an account can allocate for his resources. 10 - PrimaryStorage. Total primary storage space (in GiB) a user can use. 11 - SecondaryStorage. Total secondary storage space (in GiB) a user can use. 12 - Elastic IP. Number of public elastic IP addresses an account can own. 13 - SMTP. If the account is allowed SMTP outbound traffic."` - ResourceTypeName string `json:"resourcetypename,omitempty" doc:"Type of resource (wins over resourceType if both are provided). Values are: user_vm - Instance. Number of instances a user can create. public_ip - IP. Number of public IP addresses an account can own. volume - Volume. Number of disk volumes an account can own. snapshot - Snapshot. Number of snapshots an account can own. template - Template. Number of templates an account can register/create. network - Network. Number of networks an account can own. cpu - CPU. Number of CPU an account can allocate for his resources. memory - Memory. Amount of RAM an account can allocate for his resources. primary_storage - PrimaryStorage. Total primary storage space (in GiB) a user can use. secondary_storage - SecondaryStorage. Total secondary storage space (in GiB) a user can use. public_elastic_ip - IP. Number of public elastic IP addresses an account can own. smtp - SG. If the account is allowed SMTP outbound traffic."` - - _ bool `name:"listResourceLimits" description:"Lists resource limits."` -} - -// ListResourceLimitsResponse represents a list of resource limits -type ListResourceLimitsResponse struct { - Count int `json:"count"` - ResourceLimit []ResourceLimit `json:"resourcelimit"` -} diff --git a/vendor/github.com/exoscale/egoscale/resource_metadata.go b/vendor/github.com/exoscale/egoscale/resource_metadata.go deleted file mode 100644 index 52c5ee8b0..000000000 --- a/vendor/github.com/exoscale/egoscale/resource_metadata.go +++ /dev/null @@ -1,41 +0,0 @@ -package egoscale - -import "fmt" - -// ResourceDetail represents extra details -type ResourceDetail ResourceTag - -// ListRequest builds the ListResourceDetails request -func (detail ResourceDetail) ListRequest() (ListCommand, error) { - if detail.ResourceType == "" { - return nil, fmt.Errorf("the resourcetype parameter is required") - } - - req := &ListResourceDetails{ - ResourceType: detail.ResourceType, - ResourceID: detail.ResourceID, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListResourceDetails - -// ListResourceDetails lists the resource tag(s) (but different from listTags...) -type ListResourceDetails struct { - ResourceType string `json:"resourcetype" doc:"list by resource type"` - ForDisplay bool `json:"fordisplay,omitempty" doc:"if set to true, only details marked with display=true, are returned. False by default"` - Key string `json:"key,omitempty" doc:"list by key"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"list by resource id"` - Value string `json:"value,omitempty" doc:"list by key, value. Needs to be passed only along with key"` - _ bool `name:"listResourceDetails" description:"List resource detail(s)"` -} - -// ListResourceDetailsResponse represents a list of resource details -type ListResourceDetailsResponse struct { - Count int `json:"count"` - ResourceDetail []ResourceTag `json:"resourcedetail"` -} diff --git a/vendor/github.com/exoscale/egoscale/resourcedetails_response.go b/vendor/github.com/exoscale/egoscale/resourcedetails_response.go deleted file mode 100644 index 2a08cd825..000000000 --- a/vendor/github.com/exoscale/egoscale/resourcedetails_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListResourceDetails) Response() interface{} { - return new(ListResourceDetailsResponse) -} - -// ListRequest returns itself -func (ls *ListResourceDetails) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListResourceDetails) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListResourceDetails) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListResourceDetails) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListResourceDetailsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListResourceDetailsResponse was expected, got %T", resp)) - return - } - - for i := range items.ResourceDetail { - if !callback(&items.ResourceDetail[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/resourcelimits_response.go b/vendor/github.com/exoscale/egoscale/resourcelimits_response.go deleted file mode 100644 index 656febfc9..000000000 --- a/vendor/github.com/exoscale/egoscale/resourcelimits_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListResourceLimits) Response() interface{} { - return new(ListResourceLimitsResponse) -} - -// ListRequest returns itself -func (ls *ListResourceLimits) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListResourceLimits) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListResourceLimits) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListResourceLimits) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListResourceLimitsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListResourceLimitsResponse was expected, got %T", resp)) - return - } - - for i := range items.ResourceLimit { - if !callback(&items.ResourceLimit[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/reversedns.go b/vendor/github.com/exoscale/egoscale/reversedns.go deleted file mode 100644 index e8bd124ce..000000000 --- a/vendor/github.com/exoscale/egoscale/reversedns.go +++ /dev/null @@ -1,83 +0,0 @@ -package egoscale - -import ( - "net" -) - -// ReverseDNS represents the PTR record linked with an IPAddress or IP6Address belonging to a Virtual Machine or a Public IP Address (Elastic IP) instance -type ReverseDNS struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name of the PTR record"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the IPv6 address linked with the PTR record (mutually exclusive with ipaddress)"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the IPv4 address linked with the PTR record (mutually exclusive with ip6address)"` - NicID *UUID `json:"nicid,omitempty" doc:"the virtual machine default NIC ID"` - PublicIPID *UUID `json:"publicipid,omitempty" doc:"the public IP address ID"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the virtual machine ID"` -} - -// DeleteReverseDNSFromPublicIPAddress is a command to create/delete the PTR record of a public IP address -type DeleteReverseDNSFromPublicIPAddress struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"deleteReverseDnsFromPublicIpAddress" description:"delete the PTR DNS record from the public IP address"` -} - -// Response returns the struct to unmarshal -func (*DeleteReverseDNSFromPublicIPAddress) Response() interface{} { - return new(BooleanResponse) -} - -// DeleteReverseDNSFromVirtualMachine is a command to create/delete the PTR record(s) of a virtual machine -type DeleteReverseDNSFromVirtualMachine struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"deleteReverseDnsFromVirtualMachine" description:"Delete the PTR DNS record(s) from the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*DeleteReverseDNSFromVirtualMachine) Response() interface{} { - return new(BooleanResponse) -} - -// QueryReverseDNSForPublicIPAddress is a command to create/query the PTR record of a public IP address -type QueryReverseDNSForPublicIPAddress struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"queryReverseDnsForPublicIpAddress" description:"Query the PTR DNS record for the public IP address"` -} - -// Response returns the struct to unmarshal -func (*QueryReverseDNSForPublicIPAddress) Response() interface{} { - return new(IPAddress) -} - -// QueryReverseDNSForVirtualMachine is a command to create/query the PTR record(s) of a virtual machine -type QueryReverseDNSForVirtualMachine struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"queryReverseDnsForVirtualMachine" description:"Query the PTR DNS record(s) for the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*QueryReverseDNSForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// UpdateReverseDNSForPublicIPAddress is a command to create/update the PTR record of a public IP address -type UpdateReverseDNSForPublicIPAddress struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record. It must have a valid TLD"` - ID *UUID `json:"id,omitempty" doc:"the ID of the public IP address"` - _ bool `name:"updateReverseDnsForPublicIpAddress" description:"Update/create the PTR DNS record for the public IP address"` -} - -// Response returns the struct to unmarshal -func (*UpdateReverseDNSForPublicIPAddress) Response() interface{} { - return new(IPAddress) -} - -// UpdateReverseDNSForVirtualMachine is a command to create/update the PTR record(s) of a virtual machine -type UpdateReverseDNSForVirtualMachine struct { - DomainName string `json:"domainname,omitempty" doc:"the domain name for the PTR record(s). It must have a valid TLD"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - _ bool `name:"updateReverseDnsForVirtualMachine" description:"Update/create the PTR DNS record(s) for the virtual machine"` -} - -// Response returns the struct to unmarshal -func (*UpdateReverseDNSForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus.go b/vendor/github.com/exoscale/egoscale/runstatus.go deleted file mode 100644 index 268e36eaa..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus.go +++ /dev/null @@ -1,131 +0,0 @@ -package egoscale - -import ( - "context" - "crypto/hmac" - "crypto/sha256" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - "time" -) - -// RunstatusValidationErrorResponse represents an error in the API -type RunstatusValidationErrorResponse map[string][]string - -// RunstatusErrorResponse represents the default errors -type RunstatusErrorResponse struct { - Detail string `json:"detail"` -} - -// runstatusPagesURL is the only URL that cannot be guessed -const runstatusPagesURL = "/pages" - -// Error formats the DNSerror into a string -func (req RunstatusErrorResponse) Error() string { - return fmt.Sprintf("Runstatus error: %s", req.Detail) -} - -// Error formats the DNSerror into a string -func (req RunstatusValidationErrorResponse) Error() string { - if len(req) > 0 { - errs := []string{} - for name, ss := range req { - if len(ss) > 0 { - errs = append(errs, fmt.Sprintf("%s: %s", name, strings.Join(ss, ", "))) - } - } - return fmt.Sprintf("Runstatus error: %s", strings.Join(errs, "; ")) - } - return fmt.Sprintf("Runstatus error") -} - -func (client *Client) runstatusRequest(ctx context.Context, uri string, structParam interface{}, method string) (json.RawMessage, error) { - reqURL, err := url.Parse(uri) - if err != nil { - return nil, err - } - if reqURL.Scheme == "" { - return nil, fmt.Errorf("only absolute URI are considered valid, got %q", uri) - } - - var params string - if structParam != nil { - m, err := json.Marshal(structParam) - if err != nil { - return nil, err - } - params = string(m) - } - - req, err := http.NewRequest(method, reqURL.String(), strings.NewReader(params)) - if err != nil { - return nil, err - } - - time := time.Now().Local().Format("2006-01-02T15:04:05-0700") - - payload := fmt.Sprintf("%s%s%s", req.URL.String(), time, params) - - mac := hmac.New(sha256.New, []byte(client.apiSecret)) - _, err = mac.Write([]byte(payload)) - if err != nil { - return nil, err - } - signature := hex.EncodeToString(mac.Sum(nil)) - - var hdr = make(http.Header) - - hdr.Add("Authorization", fmt.Sprintf("Exoscale-HMAC-SHA256 %s:%s", client.APIKey, signature)) - hdr.Add("Exoscale-Date", time) - hdr.Add("User-Agent", fmt.Sprintf("exoscale/egoscale (%v)", Version)) - hdr.Add("Accept", "application/json") - if params != "" { - hdr.Add("Content-Type", "application/json") - } - req.Header = hdr - - req = req.WithContext(ctx) - - resp, err := client.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() // nolint: errcheck - - if resp.StatusCode == 204 { - if method != "DELETE" { - return nil, fmt.Errorf("only DELETE is expected to produce 204, was %q", method) - } - return nil, nil - } - - contentType := resp.Header.Get("content-type") - if !strings.Contains(contentType, "application/json") { - return nil, fmt.Errorf(`response %d content-type expected to be "application/json", got %q`, resp.StatusCode, contentType) - } - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - rerr := new(RunstatusValidationErrorResponse) - if err := json.Unmarshal(b, rerr); err == nil { - return nil, rerr - } - rverr := new(RunstatusErrorResponse) - if err := json.Unmarshal(b, rverr); err != nil { - return nil, err - } - - return nil, rverr - } - - return b, nil -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus_event.go b/vendor/github.com/exoscale/egoscale/runstatus_event.go deleted file mode 100644 index 2c698788b..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus_event.go +++ /dev/null @@ -1,37 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "time" -) - -//RunstatusEvent is a runstatus event -type RunstatusEvent struct { - Created *time.Time `json:"created,omitempty"` - State string `json:"state,omitempty"` - Status string `json:"status"` - Text string `json:"text"` -} - -// UpdateRunstatusIncident create runstatus incident event -// Events can be updates or final message with status completed. -func (client *Client) UpdateRunstatusIncident(ctx context.Context, incident RunstatusIncident, event RunstatusEvent) error { - if incident.EventsURL == "" { - return fmt.Errorf("empty Events URL for %#v", incident) - } - - _, err := client.runstatusRequest(ctx, incident.EventsURL, event, "POST") - return err -} - -// UpdateRunstatusMaintenance adds a event to a maintenance. -// Events can be updates or final message with status completed. -func (client *Client) UpdateRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance, event RunstatusEvent) error { - if maintenance.EventsURL == "" { - return fmt.Errorf("empty Events URL for %#v", maintenance) - } - - _, err := client.runstatusRequest(ctx, maintenance.EventsURL, event, "POST") - return err -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus_incident.go b/vendor/github.com/exoscale/egoscale/runstatus_incident.go deleted file mode 100644 index 57d20c81b..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus_incident.go +++ /dev/null @@ -1,175 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "time" -) - -//RunstatusIncident is a runstatus incident -type RunstatusIncident struct { - EndDate *time.Time `json:"end_date,omitempty"` - Events []RunstatusEvent `json:"events,omitempty"` - EventsURL string `json:"events_url,omitempty"` - ID int `json:"id,omitempty"` - PageURL string `json:"page_url,omitempty"` // fake field - PostMortem string `json:"post_mortem,omitempty"` - RealTime bool `json:"real_time,omitempty"` - Services []string `json:"services"` - StartDate *time.Time `json:"start_date,omitempty"` - State string `json:"state"` - Status string `json:"status"` - StatusText string `json:"status_text"` - Title string `json:"title"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other incident has got similarities with itself -func (incident RunstatusIncident) Match(other RunstatusIncident) bool { - if other.Title != "" && incident.Title == other.Title { - return true - } - - if other.ID > 0 && incident.ID == other.ID { - return true - } - - return false -} - -//RunstatusIncidentList is a list of incident -type RunstatusIncidentList struct { - Next string `json:"next"` - Previous string `json:"previous"` - Incidents []RunstatusIncident `json:"results"` -} - -// GetRunstatusIncident retrieves the details of a specific incident. -func (client *Client) GetRunstatusIncident(ctx context.Context, incident RunstatusIncident) (*RunstatusIncident, error) { - if incident.URL != "" { - return client.getRunstatusIncident(ctx, incident.URL) - } - - if incident.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", incident) - } - - page, err := client.getRunstatusPage(ctx, incident.PageURL) - if err != nil { - return nil, err - } - - for i := range page.Incidents { - j := &page.Incidents[i] - if j.Match(incident) { - return j, nil - } - } - - return nil, fmt.Errorf("%#v not found", incident) -} - -func (client *Client) getRunstatusIncident(ctx context.Context, incidentURL string) (*RunstatusIncident, error) { - resp, err := client.runstatusRequest(ctx, incidentURL, nil, "GET") - if err != nil { - return nil, err - } - - i := new(RunstatusIncident) - if err := json.Unmarshal(resp, i); err != nil { - return nil, err - } - return i, nil -} - -// ListRunstatusIncidents lists the incidents for a specific page. -func (client *Client) ListRunstatusIncidents(ctx context.Context, page RunstatusPage) ([]RunstatusIncident, error) { - if page.IncidentsURL == "" { - return nil, fmt.Errorf("empty Incidents URL for %#v", page) - } - - results := make([]RunstatusIncident, 0) - - var err error - client.PaginateRunstatusIncidents(ctx, page, func(incident *RunstatusIncident, e error) bool { - if e != nil { - err = e - return false - } - - results = append(results, *incident) - return true - }) - - return results, err -} - -// PaginateRunstatusIncidents paginate Incidents -func (client *Client) PaginateRunstatusIncidents(ctx context.Context, page RunstatusPage, callback func(*RunstatusIncident, error) bool) { - if page.IncidentsURL == "" { - callback(nil, fmt.Errorf("empty Incidents URL for %#v", page)) - return - } - - incidentsURL := page.IncidentsURL - for incidentsURL != "" { - resp, err := client.runstatusRequest(ctx, incidentsURL, nil, "GET") - if err != nil { - callback(nil, err) - return - } - - var is *RunstatusIncidentList - if err := json.Unmarshal(resp, &is); err != nil { - callback(nil, err) - return - } - - for i := range is.Incidents { - if cont := callback(&is.Incidents[i], nil); !cont { - return - } - } - - incidentsURL = is.Next - } -} - -// CreateRunstatusIncident create runstatus incident -func (client *Client) CreateRunstatusIncident(ctx context.Context, incident RunstatusIncident) (*RunstatusIncident, error) { - if incident.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", incident) - } - - page, err := client.getRunstatusPage(ctx, incident.PageURL) - if err != nil { - return nil, err - } - - if page.IncidentsURL == "" { - return nil, fmt.Errorf("empty Incidents URL for %#v", page) - } - - resp, err := client.runstatusRequest(ctx, page.IncidentsURL, incident, "POST") - if err != nil { - return nil, err - } - - i := &RunstatusIncident{} - if err := json.Unmarshal(resp, &i); err != nil { - return nil, err - } - - return i, nil -} - -// DeleteRunstatusIncident delete runstatus incident -func (client *Client) DeleteRunstatusIncident(ctx context.Context, incident RunstatusIncident) error { - if incident.URL == "" { - return fmt.Errorf("empty URL for %#v", incident) - } - - _, err := client.runstatusRequest(ctx, incident.URL, nil, "DELETE") - return err -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go b/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go deleted file mode 100644 index 44501f9b7..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus_maintenance.go +++ /dev/null @@ -1,208 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "log" - "net/url" - "path" - "strconv" - "time" -) - -// RunstatusMaintenance is a runstatus maintenance -type RunstatusMaintenance struct { - Created *time.Time `json:"created,omitempty"` - Description string `json:"description,omitempty"` - EndDate *time.Time `json:"end_date"` - Events []RunstatusEvent `json:"events,omitempty"` - EventsURL string `json:"events_url,omitempty"` - ID int `json:"id,omitempty"` // missing field - PageURL string `json:"page_url,omitempty"` // fake field - RealTime bool `json:"real_time,omitempty"` - Services []string `json:"services"` - StartDate *time.Time `json:"start_date"` - Status string `json:"status"` - Title string `json:"title"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other maintenance has got similarities with itself -func (maintenance RunstatusMaintenance) Match(other RunstatusMaintenance) bool { - if other.Title != "" && maintenance.Title == other.Title { - return true - } - - if other.ID > 0 && maintenance.ID == other.ID { - return true - } - - return false -} - -// FakeID fills up the ID field as it's currently missing -func (maintenance *RunstatusMaintenance) FakeID() error { - if maintenance.ID > 0 { - return nil - } - - if maintenance.URL == "" { - return fmt.Errorf("empty URL for %#v", maintenance) - } - - u, err := url.Parse(maintenance.URL) - if err != nil { - return err - } - - s := path.Base(u.Path) - id, err := strconv.Atoi(s) - if err != nil { - return err - } - maintenance.ID = id - return nil -} - -// RunstatusMaintenanceList is a list of incident -type RunstatusMaintenanceList struct { - Next string `json:"next"` - Previous string `json:"previous"` - Maintenances []RunstatusMaintenance `json:"results"` -} - -// GetRunstatusMaintenance retrieves the details of a specific maintenance. -func (client *Client) GetRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) (*RunstatusMaintenance, error) { - if maintenance.URL != "" { - return client.getRunstatusMaintenance(ctx, maintenance.URL) - } - - if maintenance.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", maintenance) - } - - page, err := client.getRunstatusPage(ctx, maintenance.PageURL) - if err != nil { - return nil, err - } - - for i := range page.Maintenances { - m := &page.Maintenances[i] - if m.Match(maintenance) { - if err := m.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", m, err) - } - return m, nil - } - } - - return nil, fmt.Errorf("%#v not found", maintenance) -} - -func (client *Client) getRunstatusMaintenance(ctx context.Context, maintenanceURL string) (*RunstatusMaintenance, error) { - resp, err := client.runstatusRequest(ctx, maintenanceURL, nil, "GET") - if err != nil { - return nil, err - } - - m := new(RunstatusMaintenance) - if err := json.Unmarshal(resp, m); err != nil { - return nil, err - } - return m, nil -} - -// ListRunstatusMaintenances returns the list of maintenances for the page. -func (client *Client) ListRunstatusMaintenances(ctx context.Context, page RunstatusPage) ([]RunstatusMaintenance, error) { - if page.MaintenancesURL == "" { - return nil, fmt.Errorf("empty Maintenances URL for %#v", page) - } - - results := make([]RunstatusMaintenance, 0) - - var err error - client.PaginateRunstatusMaintenances(ctx, page, func(maintenance *RunstatusMaintenance, e error) bool { - if e != nil { - err = e - return false - } - - results = append(results, *maintenance) - return true - }) - - return results, err -} - -// PaginateRunstatusMaintenances paginate Maintenances -func (client *Client) PaginateRunstatusMaintenances(ctx context.Context, page RunstatusPage, callback func(*RunstatusMaintenance, error) bool) { // nolint: dupl - if page.MaintenancesURL == "" { - callback(nil, fmt.Errorf("empty Maintenances URL for %#v", page)) - return - } - - maintenancesURL := page.MaintenancesURL - for maintenancesURL != "" { - resp, err := client.runstatusRequest(ctx, maintenancesURL, nil, "GET") - if err != nil { - callback(nil, err) - return - } - - var ms *RunstatusMaintenanceList - if err := json.Unmarshal(resp, &ms); err != nil { - callback(nil, err) - return - } - - for i := range ms.Maintenances { - if err := ms.Maintenances[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", ms.Maintenances[i], err) - } - if cont := callback(&ms.Maintenances[i], nil); !cont { - return - } - } - - maintenancesURL = ms.Next - } -} - -// CreateRunstatusMaintenance create runstatus Maintenance -func (client *Client) CreateRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) (*RunstatusMaintenance, error) { - if maintenance.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", maintenance) - } - - page, err := client.getRunstatusPage(ctx, maintenance.PageURL) - if err != nil { - return nil, err - } - - resp, err := client.runstatusRequest(ctx, page.MaintenancesURL, maintenance, "POST") - if err != nil { - return nil, err - } - - m := &RunstatusMaintenance{} - if err := json.Unmarshal(resp, &m); err != nil { - return nil, err - } - - if err := m.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", m, err) - } - - return m, nil -} - -// DeleteRunstatusMaintenance delete runstatus Maintenance -func (client *Client) DeleteRunstatusMaintenance(ctx context.Context, maintenance RunstatusMaintenance) error { - if maintenance.URL == "" { - return fmt.Errorf("empty URL for %#v", maintenance) - } - - _, err := client.runstatusRequest(ctx, maintenance.URL, nil, "DELETE") - return err -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus_page.go b/vendor/github.com/exoscale/egoscale/runstatus_page.go deleted file mode 100644 index 01b6b8c77..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus_page.go +++ /dev/null @@ -1,168 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "log" - "time" -) - -// RunstatusPage runstatus page -type RunstatusPage struct { - Created *time.Time `json:"created,omitempty"` - DarkTheme bool `json:"dark_theme,omitempty"` - Domain string `json:"domain,omitempty"` - GradientEnd string `json:"gradient_end,omitempty"` - GradientStart string `json:"gradient_start,omitempty"` - HeaderBackground string `json:"header_background,omitempty"` - ID int `json:"id,omitempty"` - Incidents []RunstatusIncident `json:"incidents,omitempty"` - IncidentsURL string `json:"incidents_url,omitempty"` - Logo string `json:"logo,omitempty"` - Maintenances []RunstatusMaintenance `json:"maintenances,omitempty"` - MaintenancesURL string `json:"maintenances_url,omitempty"` - Name string `json:"name"` //fake field (used to post a new runstatus page) - OkText string `json:"ok_text,omitempty"` - Plan string `json:"plan,omitempty"` - PublicURL string `json:"public_url,omitempty"` - Services []RunstatusService `json:"services,omitempty"` - ServicesURL string `json:"services_url,omitempty"` - State string `json:"state,omitempty"` - Subdomain string `json:"subdomain"` - SupportEmail string `json:"support_email,omitempty"` - TimeZone string `json:"time_zone,omitempty"` - Title string `json:"title,omitempty"` - TitleColor string `json:"title_color,omitempty"` - TwitterUsername string `json:"twitter_username,omitempty"` - URL string `json:"url,omitempty"` -} - -// Match returns true if the other page has got similarities with itself -func (page RunstatusPage) Match(other RunstatusPage) bool { - if other.Subdomain != "" && page.Subdomain == other.Subdomain { - return true - } - - if other.ID > 0 && page.ID == other.ID { - return true - } - - return false -} - -// RunstatusPageList runstatus page list -type RunstatusPageList struct { - Next string `json:"next"` - Previous string `json:"previous"` - Pages []RunstatusPage `json:"results"` -} - -// CreateRunstatusPage create runstatus page -func (client *Client) CreateRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, page, "POST") - if err != nil { - return nil, err - } - - var p *RunstatusPage - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - return p, nil -} - -// DeleteRunstatusPage delete runstatus page -func (client *Client) DeleteRunstatusPage(ctx context.Context, page RunstatusPage) error { - if page.URL == "" { - return fmt.Errorf("empty URL for %#v", page) - } - _, err := client.runstatusRequest(ctx, page.URL, nil, "DELETE") - return err -} - -// GetRunstatusPage fetches the runstatus page -func (client *Client) GetRunstatusPage(ctx context.Context, page RunstatusPage) (*RunstatusPage, error) { - if page.URL != "" { - return client.getRunstatusPage(ctx, page.URL) - } - - ps, err := client.ListRunstatusPages(ctx) - if err != nil { - return nil, err - } - - for i := range ps { - if ps[i].Match(page) { - return client.getRunstatusPage(ctx, ps[i].URL) - } - } - - return nil, fmt.Errorf("%#v not found", page) -} - -func (client *Client) getRunstatusPage(ctx context.Context, pageURL string) (*RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, pageURL, nil, "GET") - if err != nil { - return nil, err - } - - p := new(RunstatusPage) - if err := json.Unmarshal(resp, p); err != nil { - return nil, err - } - - // NOTE: fix the missing IDs - for i := range p.Maintenances { - if err := p.Maintenances[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", p.Maintenances[i], err) - } - } - for i := range p.Services { - if err := p.Services[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", p.Services[i], err) - } - } - - return p, nil -} - -// ListRunstatusPages list all the runstatus pages -func (client *Client) ListRunstatusPages(ctx context.Context) ([]RunstatusPage, error) { - resp, err := client.runstatusRequest(ctx, client.Endpoint+runstatusPagesURL, nil, "GET") - if err != nil { - return nil, err - } - - var p *RunstatusPageList - if err := json.Unmarshal(resp, &p); err != nil { - return nil, err - } - - return p.Pages, nil -} - -//PaginateRunstatusPages paginate on runstatus pages -func (client *Client) PaginateRunstatusPages(ctx context.Context, callback func(pages []RunstatusPage, e error) bool) { - pageURL := client.Endpoint + runstatusPagesURL - for pageURL != "" { - resp, err := client.runstatusRequest(ctx, pageURL, nil, "GET") - if err != nil { - callback(nil, err) - return - } - - var p *RunstatusPageList - if err := json.Unmarshal(resp, &p); err != nil { - callback(nil, err) - return - } - - if ok := callback(p.Pages, nil); ok { - return - } - - pageURL = p.Next - } -} diff --git a/vendor/github.com/exoscale/egoscale/runstatus_service.go b/vendor/github.com/exoscale/egoscale/runstatus_service.go deleted file mode 100644 index 456d92fcf..000000000 --- a/vendor/github.com/exoscale/egoscale/runstatus_service.go +++ /dev/null @@ -1,201 +0,0 @@ -package egoscale - -import ( - "context" - "encoding/json" - "fmt" - "log" - "net/url" - "path" - "strconv" -) - -// RunstatusService is a runstatus service -type RunstatusService struct { - ID int `json:"id"` // missing field - Name string `json:"name"` - PageURL string `json:"page_url,omitempty"` // fake field - State string `json:"state,omitempty"` - URL string `json:"url,omitempty"` -} - -// FakeID fills up the ID field as it's currently missing -func (service *RunstatusService) FakeID() error { - if service.ID > 0 { - return nil - } - - if service.URL == "" { - return fmt.Errorf("empty URL for %#v", service) - } - - u, err := url.Parse(service.URL) - if err != nil { - return err - } - - s := path.Base(u.Path) - id, err := strconv.Atoi(s) - if err != nil { - return err - } - service.ID = id - return nil -} - -// Match returns true if the other service has got similarities with itself -func (service RunstatusService) Match(other RunstatusService) bool { - if other.Name != "" && service.Name == other.Name { - return true - } - - if other.ID > 0 && service.ID == other.ID { - return true - } - - return false -} - -// RunstatusServiceList service list -type RunstatusServiceList struct { - Next string `json:"next"` - Previous string `json:"previous"` - Services []RunstatusService `json:"results"` -} - -// DeleteRunstatusService delete runstatus service -func (client *Client) DeleteRunstatusService(ctx context.Context, service RunstatusService) error { - if service.URL == "" { - return fmt.Errorf("empty URL for %#v", service) - } - - _, err := client.runstatusRequest(ctx, service.URL, nil, "DELETE") - return err -} - -// CreateRunstatusService create runstatus service -func (client *Client) CreateRunstatusService(ctx context.Context, service RunstatusService) (*RunstatusService, error) { - if service.PageURL == "" { - return nil, fmt.Errorf("empty Page URL for %#v", service) - } - - page, err := client.GetRunstatusPage(ctx, RunstatusPage{URL: service.PageURL}) - if err != nil { - return nil, err - } - - resp, err := client.runstatusRequest(ctx, page.ServicesURL, service, "POST") - if err != nil { - return nil, err - } - - s := &RunstatusService{} - if err := json.Unmarshal(resp, s); err != nil { - return nil, err - } - - return s, nil -} - -// GetRunstatusService displays service detail. -func (client *Client) GetRunstatusService(ctx context.Context, service RunstatusService) (*RunstatusService, error) { - if service.URL != "" { - return client.getRunstatusService(ctx, service.URL) - } - - if service.PageURL == "" { - return nil, fmt.Errorf("empty Page URL in %#v", service) - } - - page, err := client.getRunstatusPage(ctx, service.PageURL) - if err != nil { - return nil, err - } - - for i := range page.Services { - s := &page.Services[i] - if s.Match(service) { - if err := s.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", s, err) - } - return s, nil - } - } - - return nil, fmt.Errorf("%#v not found", service) -} - -func (client *Client) getRunstatusService(ctx context.Context, serviceURL string) (*RunstatusService, error) { - resp, err := client.runstatusRequest(ctx, serviceURL, nil, "GET") - if err != nil { - return nil, err - } - - s := &RunstatusService{} - if err := json.Unmarshal(resp, &s); err != nil { - return nil, err - } - - if err := s.FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", s, err) - } - - return s, nil -} - -// ListRunstatusServices displays the list of services. -func (client *Client) ListRunstatusServices(ctx context.Context, page RunstatusPage) ([]RunstatusService, error) { - if page.ServicesURL == "" { - return nil, fmt.Errorf("empty Services URL for %#v", page) - } - - results := make([]RunstatusService, 0) - - var err error - client.PaginateRunstatusServices(ctx, page, func(service *RunstatusService, e error) bool { - if e != nil { - err = e - return false - } - - results = append(results, *service) - return true - }) - - return results, err -} - -// PaginateRunstatusServices paginates Services -func (client *Client) PaginateRunstatusServices(ctx context.Context, page RunstatusPage, callback func(*RunstatusService, error) bool) { // nolint: dupl - if page.ServicesURL == "" { - callback(nil, fmt.Errorf("empty Services URL for %#v", page)) - return - } - - servicesURL := page.ServicesURL - for servicesURL != "" { - resp, err := client.runstatusRequest(ctx, servicesURL, nil, "GET") - if err != nil { - callback(nil, err) - return - } - - var ss *RunstatusServiceList - if err := json.Unmarshal(resp, &ss); err != nil { - callback(nil, err) - return - } - - for i := range ss.Services { - if err := ss.Services[i].FakeID(); err != nil { - log.Printf("bad fake ID for %#v, %s", ss.Services[i], err) - } - - if cont := callback(&ss.Services[i], nil); !cont { - return - } - } - - servicesURL = ss.Next - } -} diff --git a/vendor/github.com/exoscale/egoscale/security_groups.go b/vendor/github.com/exoscale/egoscale/security_groups.go deleted file mode 100644 index a11e53a4f..000000000 --- a/vendor/github.com/exoscale/egoscale/security_groups.go +++ /dev/null @@ -1,226 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" - "net/url" - "strconv" - "strings" -) - -// SecurityGroup represent a firewalling set of rules -type SecurityGroup struct { - Account string `json:"account,omitempty" doc:"the account owning the security group"` - Description string `json:"description,omitempty" doc:"the description of the security group"` - EgressRule []EgressRule `json:"egressrule,omitempty" doc:"the list of egress rules associated with the security group"` - ID *UUID `json:"id" doc:"the ID of the security group"` - IngressRule []IngressRule `json:"ingressrule,omitempty" doc:"the list of ingress rules associated with the security group"` - Name string `json:"name,omitempty" doc:"the name of the security group"` -} - -// UserSecurityGroup converts a SecurityGroup to a UserSecurityGroup -func (sg SecurityGroup) UserSecurityGroup() UserSecurityGroup { - return UserSecurityGroup{ - Group: sg.Name, - } -} - -// ListRequest builds the ListSecurityGroups request -func (sg SecurityGroup) ListRequest() (ListCommand, error) { - req := &ListSecurityGroups{ - ID: sg.ID, - SecurityGroupName: sg.Name, - } - - return req, nil -} - -// Delete deletes the given Security Group -func (sg SecurityGroup) Delete(ctx context.Context, client *Client) error { - if sg.ID == nil && sg.Name == "" { - return fmt.Errorf("a SecurityGroup may only be deleted using ID or Name") - } - - req := &DeleteSecurityGroup{} - - if sg.ID != nil { - req.ID = sg.ID - } else { - req.Name = sg.Name - } - - return client.BooleanRequestWithContext(ctx, req) -} - -// RuleByID returns IngressRule or EgressRule by a rule ID -func (sg SecurityGroup) RuleByID(ruleID UUID) (*IngressRule, *EgressRule) { - for i, in := range sg.IngressRule { - if in.RuleID.Equal(ruleID) { - return &sg.IngressRule[i], nil - } - } - - for i, out := range sg.EgressRule { - if out.RuleID.Equal(ruleID) { - return nil, &sg.EgressRule[i] - } - } - - return nil, nil -} - -// IngressRule represents the ingress rule -type IngressRule struct { - CIDR *CIDR `json:"cidr,omitempty" doc:"the CIDR notation for the base IP address of the security group rule"` - Description string `json:"description,omitempty" doc:"description of the security group rule"` - EndPort uint16 `json:"endport,omitempty" doc:"the ending port of the security group rule "` - IcmpCode uint8 `json:"icmpcode,omitempty" doc:"the code for the ICMP message response"` - IcmpType uint8 `json:"icmptype,omitempty" doc:"the type of the ICMP message response"` - Protocol string `json:"protocol,omitempty" doc:"the protocol of the security group rule"` - RuleID *UUID `json:"ruleid" doc:"the id of the security group rule"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"security group name"` - StartPort uint16 `json:"startport,omitempty" doc:"the starting port of the security group rule"` -} - -// EgressRule represents the ingress rule -type EgressRule IngressRule - -// UserSecurityGroup represents the traffic of another security group -type UserSecurityGroup struct { - Group string `json:"group,omitempty"` -} - -// String gives the UserSecurityGroup name -func (usg UserSecurityGroup) String() string { - return usg.Group -} - -// CreateSecurityGroup represents a security group creation -type CreateSecurityGroup struct { - Name string `json:"name" doc:"name of the security group"` - Description string `json:"description,omitempty" doc:"the description of the security group"` - _ bool `name:"createSecurityGroup" description:"Creates a security group"` -} - -// Response returns the struct to unmarshal -func (CreateSecurityGroup) Response() interface{} { - return new(SecurityGroup) -} - -// DeleteSecurityGroup represents a security group deletion -type DeleteSecurityGroup struct { - ID *UUID `json:"id,omitempty" doc:"The ID of the security group. Mutually exclusive with name parameter"` - Name string `json:"name,omitempty" doc:"The ID of the security group. Mutually exclusive with id parameter"` - _ bool `name:"deleteSecurityGroup" description:"Deletes security group"` -} - -// Response returns the struct to unmarshal -func (DeleteSecurityGroup) Response() interface{} { - return new(BooleanResponse) -} - -// AuthorizeSecurityGroupIngress (Async) represents the ingress rule creation -type AuthorizeSecurityGroupIngress struct { - CIDRList []CIDR `json:"cidrlist,omitempty" doc:"the cidr list associated"` - Description string `json:"description,omitempty" doc:"the description of the ingress/egress rule"` - EndPort uint16 `json:"endport,omitempty" doc:"end port for this ingress/egress rule"` - IcmpCode uint8 `json:"icmpcode,omitempty" doc:"error code for this icmp message"` - IcmpType uint8 `json:"icmptype,omitempty" doc:"type of the icmp message being sent"` - Protocol string `json:"protocol,omitempty" doc:"TCP is default. UDP, ICMP, ICMPv6, AH, ESP, GRE, IPIP are the other supported protocols"` - SecurityGroupID *UUID `json:"securitygroupid,omitempty" doc:"The ID of the security group. Mutually exclusive with securitygroupname parameter"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"The name of the security group. Mutually exclusive with securitygroupid parameter"` - StartPort uint16 `json:"startport,omitempty" doc:"start port for this ingress/egress rule"` - UserSecurityGroupList []UserSecurityGroup `json:"usersecuritygrouplist,omitempty" doc:"user to security group mapping"` - _ bool `name:"authorizeSecurityGroupIngress" description:"Authorize a particular ingress/egress rule for this security group"` -} - -// Response returns the struct to unmarshal -func (AuthorizeSecurityGroupIngress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AuthorizeSecurityGroupIngress) AsyncResponse() interface{} { - return new(SecurityGroup) -} - -func (req AuthorizeSecurityGroupIngress) onBeforeSend(params url.Values) error { - // ICMP code and type may be zero but can also be omitted... - if strings.HasPrefix(strings.ToLower(req.Protocol), "icmp") { - params.Set("icmpcode", strconv.FormatInt(int64(req.IcmpCode), 10)) - params.Set("icmptype", strconv.FormatInt(int64(req.IcmpType), 10)) - } - // StartPort may be zero but can also be omitted... - if req.EndPort != 0 && req.StartPort == 0 { - params.Set("startport", "0") - } - return nil -} - -// AuthorizeSecurityGroupEgress (Async) represents the egress rule creation -type AuthorizeSecurityGroupEgress AuthorizeSecurityGroupIngress - -// Response returns the struct to unmarshal -func (AuthorizeSecurityGroupEgress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AuthorizeSecurityGroupEgress) AsyncResponse() interface{} { - return new(SecurityGroup) -} - -func (req AuthorizeSecurityGroupEgress) onBeforeSend(params url.Values) error { - return (AuthorizeSecurityGroupIngress)(req).onBeforeSend(params) -} - -// RevokeSecurityGroupIngress (Async) represents the ingress/egress rule deletion -type RevokeSecurityGroupIngress struct { - ID *UUID `json:"id" doc:"The ID of the ingress rule"` - _ bool `name:"revokeSecurityGroupIngress" description:"Deletes a particular ingress rule from this security group"` -} - -// Response returns the struct to unmarshal -func (RevokeSecurityGroupIngress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevokeSecurityGroupIngress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// RevokeSecurityGroupEgress (Async) represents the ingress/egress rule deletion -type RevokeSecurityGroupEgress struct { - ID *UUID `json:"id" doc:"The ID of the egress rule"` - _ bool `name:"revokeSecurityGroupEgress" description:"Deletes a particular egress rule from this security group"` -} - -// Response returns the struct to unmarshal -func (RevokeSecurityGroupEgress) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevokeSecurityGroupEgress) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListSecurityGroups - -// ListSecurityGroups represents a search for security groups -type ListSecurityGroups struct { - ID *UUID `json:"id,omitempty" doc:"list the security group by the id provided"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SecurityGroupName string `json:"securitygroupname,omitempty" doc:"lists security groups by name"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"lists security groups by virtual machine id"` - _ bool `name:"listSecurityGroups" description:"Lists security groups"` -} - -// ListSecurityGroupsResponse represents a list of security groups -type ListSecurityGroupsResponse struct { - Count int `json:"count"` - SecurityGroup []SecurityGroup `json:"securitygroup"` -} diff --git a/vendor/github.com/exoscale/egoscale/securitygroups_response.go b/vendor/github.com/exoscale/egoscale/securitygroups_response.go deleted file mode 100644 index ff08f333c..000000000 --- a/vendor/github.com/exoscale/egoscale/securitygroups_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSecurityGroups) Response() interface{} { - return new(ListSecurityGroupsResponse) -} - -// ListRequest returns itself -func (ls *ListSecurityGroups) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSecurityGroups) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSecurityGroups) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSecurityGroups) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSecurityGroupsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSecurityGroupsResponse was expected, got %T", resp)) - return - } - - for i := range items.SecurityGroup { - if !callback(&items.SecurityGroup[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/serialization.go b/vendor/github.com/exoscale/egoscale/serialization.go deleted file mode 100644 index 24a0c123f..000000000 --- a/vendor/github.com/exoscale/egoscale/serialization.go +++ /dev/null @@ -1,402 +0,0 @@ -package egoscale - -import ( - "encoding/base64" - "fmt" - "log" - "net" - "net/url" - "reflect" - "strconv" - "strings" -) - -func csQuotePlus(s string) string { - s = strings.Replace(s, "+", "%20", -1) - return s -} - -func csEncode(s string) string { - return csQuotePlus(url.QueryEscape(s)) -} - -// info returns the meta info of a command -// -// command is not a Command so it's easier to Test -func info(command interface{}) (*CommandInfo, error) { - typeof := reflect.TypeOf(command) - - // Going up the pointer chain to find the underlying struct - for typeof.Kind() == reflect.Ptr { - typeof = typeof.Elem() - } - - field, ok := typeof.FieldByName("_") - if !ok { - return nil, fmt.Errorf(`missing meta ("_") field in %#v`, command) - } - - name, nameOk := field.Tag.Lookup("name") - description, _ := field.Tag.Lookup("description") - - if !nameOk { - return nil, fmt.Errorf(`missing "name" key in the tag string of %#v`, command) - } - - info := &CommandInfo{ - Name: name, - Description: description, - } - - return info, nil -} - -// prepareValues uses a command to build a POST request -// -// command is not a Command so it's easier to Test -func prepareValues(prefix string, command interface{}) (url.Values, error) { - params := url.Values{} - - value := reflect.ValueOf(command) - typeof := reflect.TypeOf(command) - - // Going up the pointer chain to find the underlying struct - for typeof.Kind() == reflect.Ptr { - typeof = typeof.Elem() - value = value.Elem() - } - - // Checking for nil commands - if !value.IsValid() { - return nil, fmt.Errorf("cannot serialize the invalid value %#v", command) - } - - for i := 0; i < typeof.NumField(); i++ { - field := typeof.Field(i) - if field.Name == "_" { - continue - } - - val := value.Field(i) - tag := field.Tag - - var err error - var name string - var value interface{} - - if json, ok := tag.Lookup("json"); ok { - n, required := ExtractJSONTag(field.Name, json) - name = prefix + n - - switch val.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - value, err = prepareInt(val.Int(), required) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - value, err = prepareUint(val.Uint(), required) - - case reflect.Float32, reflect.Float64: - value, err = prepareFloat(val.Float(), required) - - case reflect.String: - value, err = prepareString(val.String(), required) - - case reflect.Bool: - value, err = prepareBool(val.Bool(), required) - - case reflect.Map: - if val.Len() == 0 { - if required { - err = fmt.Errorf("field is required, got empty map") - } - } else { - value, err = prepareMap(name, val.Interface()) - } - - case reflect.Ptr: - value, err = preparePtr(field.Type.Elem().Kind(), val, required) - - case reflect.Slice: - value, err = prepareSlice(name, field.Type, val, required) - - case reflect.Struct: - value, err = prepareStruct(val.Interface(), required) - - default: - if required { - err = fmt.Errorf("unsupported type") - } - } - } else { - switch val.Kind() { - case reflect.Struct: - value, err = prepareEmbedStruct(val.Interface()) - default: - log.Printf("[SKIP] %s.%s no json label found", typeof.Name(), field.Name) - } - } - - if err != nil { - return nil, fmt.Errorf("%s.%s (%v) %s", typeof.Name(), field.Name, val.Kind(), err) - } - - switch v := value.(type) { - case *string: - if name != "" && v != nil { - params.Set(name, *v) - } - case url.Values: - for k, xs := range v { - for _, x := range xs { - params.Add(k, x) - } - } - } - } - - return params, nil -} - -func prepareInt(v int64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %d", v) - } - return nil, nil - } - value := strconv.FormatInt(v, 10) - return &value, nil -} - -func prepareUint(v uint64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %d", v) - } - return nil, nil - } - - value := strconv.FormatUint(v, 10) - return &value, nil -} - -func prepareFloat(v float64, required bool) (*string, error) { - if v == 0 { - if required { - return nil, fmt.Errorf("field is required, got %f", v) - } - return nil, nil - } - value := strconv.FormatFloat(v, 'f', -1, 64) - return &value, nil -} - -func prepareString(v string, required bool) (*string, error) { - if v == "" { - if required { - return nil, fmt.Errorf("field is required, got %q", v) - } - return nil, nil - } - return &v, nil -} - -func prepareBool(v bool, required bool) (*string, error) { - value := strconv.FormatBool(v) - if !v { - if required { - return &value, nil - } - return nil, nil - } - - return &value, nil -} - -func prepareList(prefix string, slice interface{}) (url.Values, error) { - params := url.Values{} - value := reflect.ValueOf(slice) - - for i := 0; i < value.Len(); i++ { - ps, err := prepareValues(fmt.Sprintf("%s[%d].", prefix, i), value.Index(i).Interface()) - if err != nil { - return nil, err - } - - for k, xs := range ps { - for _, x := range xs { - params.Add(k, x) - } - } - } - - return params, nil -} - -func prepareMap(prefix string, m interface{}) (url.Values, error) { - value := url.Values{} - v := reflect.ValueOf(m) - - for i, key := range v.MapKeys() { - var keyName string - var keyValue string - - switch key.Kind() { - case reflect.String: - keyName = key.String() - default: - return value, fmt.Errorf("only map[string]string are supported (XXX)") - } - - val := v.MapIndex(key) - switch val.Kind() { - case reflect.String: - keyValue = val.String() - default: - return value, fmt.Errorf("only map[string]string are supported (XXX)") - } - - value.Set(fmt.Sprintf("%s[%d].%s", prefix, i, keyName), keyValue) - } - - return value, nil -} - -func preparePtr(kind reflect.Kind, val reflect.Value, required bool) (*string, error) { - if val.IsNil() { - if required { - return nil, fmt.Errorf("field is required, got empty ptr") - } - return nil, nil - } - - switch kind { - case reflect.Bool: - return prepareBool(val.Elem().Bool(), true) - case reflect.Struct: - return prepareStruct(val.Interface(), required) - default: - return nil, fmt.Errorf("kind %v is not supported as a ptr", kind) - } -} - -func prepareSlice(name string, fieldType reflect.Type, val reflect.Value, required bool) (interface{}, error) { - switch fieldType.Elem().Kind() { - case reflect.Uint8: - switch fieldType { - case reflect.TypeOf(net.IPv4zero): - ip := (net.IP)(val.Bytes()) - if ip == nil || ip.Equal(net.IP{}) { - if required { - return nil, fmt.Errorf("field is required, got zero IPv4 address") - } - } else { - value := ip.String() - return &value, nil - } - - case reflect.TypeOf(MAC48(0, 0, 0, 0, 0, 0)): - mac := val.Interface().(MACAddress) - s := mac.String() - if s == "" { - if required { - return nil, fmt.Errorf("field is required, got empty MAC address") - } - } else { - return &s, nil - } - default: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - value := base64.StdEncoding.EncodeToString(val.Bytes()) - return &value, nil - } - } - case reflect.String: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - elems := make([]string, 0, val.Len()) - for i := 0; i < val.Len(); i++ { - // XXX what if the value contains a comma? Double encode? - s := val.Index(i).String() - elems = append(elems, s) - } - value := strings.Join(elems, ",") - return &value, nil - } - default: - switch fieldType.Elem() { - case reflect.TypeOf(CIDR{}), reflect.TypeOf(UUID{}): - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - v := reflect.ValueOf(val.Interface()) - ss := make([]string, val.Len()) - for i := 0; i < v.Len(); i++ { - e := v.Index(i).Interface() - s, ok := e.(fmt.Stringer) - if !ok { - return nil, fmt.Errorf("not a String, %T", e) - } - ss[i] = s.String() - } - value := strings.Join(ss, ",") - return &value, nil - } - default: - if val.Len() == 0 { - if required { - return nil, fmt.Errorf("field is required, got empty slice") - } - } else { - return prepareList(name, val.Interface()) - } - } - } - - return nil, nil -} - -func prepareStruct(i interface{}, required bool) (*string, error) { - s, ok := i.(fmt.Stringer) - if !ok { - return nil, fmt.Errorf("struct field not a Stringer") - } - - if s == nil { - if required { - return nil, fmt.Errorf("field is required, got %#v", s) - } - } - - return prepareString(s.String(), required) -} - -func prepareEmbedStruct(i interface{}) (url.Values, error) { - return prepareValues("", i) -} - -// ExtractJSONTag returns the variable name or defaultName as well as if the field is required (!omitempty) -func ExtractJSONTag(defaultName, jsonTag string) (string, bool) { - tags := strings.Split(jsonTag, ",") - name := tags[0] - required := true - for _, tag := range tags { - if tag == "omitempty" { - required = false - } - } - - if name == "" || name == "omitempty" { - name = defaultName - } - return name, required -} diff --git a/vendor/github.com/exoscale/egoscale/service_offerings.go b/vendor/github.com/exoscale/egoscale/service_offerings.go deleted file mode 100644 index 8d3551467..000000000 --- a/vendor/github.com/exoscale/egoscale/service_offerings.go +++ /dev/null @@ -1,77 +0,0 @@ -package egoscale - -// ServiceOffering corresponds to the Compute Offerings -// -// A service offering correspond to some hardware features (CPU, RAM). -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/latest/service_offerings.html -type ServiceOffering struct { - Authorized bool `json:"authorized,omitempty" doc:"is the account/domain authorized to use this service offering"` - CPUNumber int `json:"cpunumber,omitempty" doc:"the number of CPU"` - CPUSpeed int `json:"cpuspeed,omitempty" doc:"the clock rate CPU speed in Mhz"` - Created string `json:"created,omitempty" doc:"the date this service offering was created"` - DefaultUse bool `json:"defaultuse,omitempty" doc:"is this a default system vm offering"` - DeploymentPlanner string `json:"deploymentplanner,omitempty" doc:"deployment strategy used to deploy VM."` - DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the service offering"` - DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the service offering"` - DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the service offering"` - DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the service offering"` - Displaytext string `json:"displaytext,omitempty" doc:"an alternate display text of the service offering."` - HostTags string `json:"hosttags,omitempty" doc:"the host tag for the service offering"` - HypervisorSnapshotReserve int `json:"hypervisorsnapshotreserve,omitempty" doc:"Hypervisor snapshot reserve space as a percent of a volume (for managed storage using Xen or VMware)"` - ID *UUID `json:"id" doc:"the id of the service offering"` - IsCustomized bool `json:"iscustomized,omitempty" doc:"is true if the offering is customized"` - IsCustomizedIops bool `json:"iscustomizediops,omitempty" doc:"true if disk offering uses custom iops, false otherwise"` - IsSystem bool `json:"issystem,omitempty" doc:"is this a system vm offering"` - IsVolatile bool `json:"isvolatile,omitempty" doc:"true if the vm needs to be volatile, i.e., on every reboot of vm from API root disk is discarded and creates a new root disk"` - LimitCPUUse bool `json:"limitcpuuse,omitempty" doc:"restrict the CPU usage to committed service offering"` - MaxIops int64 `json:"maxiops,omitempty" doc:"the max iops of the disk offering"` - Memory int `json:"memory,omitempty" doc:"the memory in MB"` - MinIops int64 `json:"miniops,omitempty" doc:"the min iops of the disk offering"` - Name string `json:"name,omitempty" doc:"the name of the service offering"` - NetworkRate int `json:"networkrate,omitempty" doc:"data transfer rate in megabits per second allowed."` - OfferHA bool `json:"offerha,omitempty" doc:"the ha support in the service offering"` - Restricted bool `json:"restricted,omitempty" doc:"is this offering restricted"` - ServiceOfferingDetails map[string]string `json:"serviceofferingdetails,omitempty" doc:"additional key/value details tied with this service offering"` - StorageType string `json:"storagetype,omitempty" doc:"the storage type for this service offering"` - SystemVMType string `json:"systemvmtype,omitempty" doc:"is this a the systemvm type for system vm offering"` - Tags string `json:"tags,omitempty" doc:"the tags for the service offering"` -} - -// ListRequest builds the ListSecurityGroups request -func (so ServiceOffering) ListRequest() (ListCommand, error) { - // Restricted cannot be applied here because it really has three states - req := &ListServiceOfferings{ - ID: so.ID, - Name: so.Name, - SystemVMType: so.SystemVMType, - } - - if so.IsSystem { - req.IsSystem = &so.IsSystem - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListServiceOfferings - -// ListServiceOfferings represents a query for service offerings -type ListServiceOfferings struct { - ID *UUID `json:"id,omitempty" doc:"ID of the service offering"` - IsSystem *bool `json:"issystem,omitempty" doc:"is this a system vm offering"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"name of the service offering"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Restricted *bool `json:"restricted,omitempty" doc:"filter by the restriction flag: true to list only the restricted service offerings, false to list non-restricted service offerings, or nothing for all."` - SystemVMType string `json:"systemvmtype,omitempty" doc:"the system VM type. Possible types are \"consoleproxy\", \"secondarystoragevm\" or \"domainrouter\"."` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"the ID of the virtual machine. Pass this in if you want to see the available service offering that a virtual machine can be changed to."` - _ bool `name:"listServiceOfferings" description:"Lists all available service offerings."` -} - -// ListServiceOfferingsResponse represents a list of service offerings -type ListServiceOfferingsResponse struct { - Count int `json:"count"` - ServiceOffering []ServiceOffering `json:"serviceoffering"` -} diff --git a/vendor/github.com/exoscale/egoscale/serviceofferings_response.go b/vendor/github.com/exoscale/egoscale/serviceofferings_response.go deleted file mode 100644 index a01d4aaf4..000000000 --- a/vendor/github.com/exoscale/egoscale/serviceofferings_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListServiceOfferings) Response() interface{} { - return new(ListServiceOfferingsResponse) -} - -// ListRequest returns itself -func (ls *ListServiceOfferings) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListServiceOfferings) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListServiceOfferings) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListServiceOfferings) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListServiceOfferingsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListServiceOfferingsResponse was expected, got %T", resp)) - return - } - - for i := range items.ServiceOffering { - if !callback(&items.ServiceOffering[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/snapshots.go b/vendor/github.com/exoscale/egoscale/snapshots.go deleted file mode 100644 index 191f4a0f7..000000000 --- a/vendor/github.com/exoscale/egoscale/snapshots.go +++ /dev/null @@ -1,139 +0,0 @@ -package egoscale - -// SnapshotState represents the Snapshot.State enum -// -// See: https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/storage/Snapshot.java -type SnapshotState string - -const ( - // Allocated ... (TODO) - Allocated SnapshotState = "Allocated" - // Creating ... (TODO) - Creating SnapshotState = "Creating" - // CreatedOnPrimary ... (TODO) - CreatedOnPrimary SnapshotState = "CreatedOnPrimary" - // BackingUp ... (TODO) - BackingUp SnapshotState = "BackingUp" - // BackedUp ... (TODO) - BackedUp SnapshotState = "BackedUp" - // Copying ... (TODO) - Copying SnapshotState = "Copying" - // Destroying ... (TODO) - Destroying SnapshotState = "Destroying" - // Destroyed ... (TODO) - Destroyed SnapshotState = "Destroyed" - // Error is a state where the user can't see the snapshot while the snapshot may still exist on the storage - Error SnapshotState = "Error" -) - -// Snapshot represents a volume snapshot -type Snapshot struct { - Account string `json:"account,omitempty" doc:"the account associated with the snapshot"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID associated with the snapshot"` - Created string `json:"created,omitempty" doc:"the date the snapshot was created"` - ID *UUID `json:"id,omitempty" doc:"ID of the snapshot"` - IntervalType string `json:"intervaltype,omitempty" doc:"valid types are hourly, daily, weekly, monthy, template, and none."` - Name string `json:"name,omitempty" doc:"name of the snapshot"` - PhysicalSize int64 `json:"physicalsize,omitempty" doc:"physical size of the snapshot on image store"` - Revertable *bool `json:"revertable,omitempty" doc:"indicates whether the underlying storage supports reverting the volume to this snapshot"` - Size int64 `json:"size,omitempty" doc:"the size of original volume"` - SnapshotType string `json:"snapshottype,omitempty" doc:"the type of the snapshot"` - State string `json:"state,omitempty" doc:"the state of the snapshot. BackedUp means that snapshot is ready to be used; Creating - the snapshot is being allocated on the primary storage; BackingUp - the snapshot is being backed up on secondary storage"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with snapshot"` - VolumeID *UUID `json:"volumeid,omitempty" doc:"ID of the disk volume"` - VolumeName string `json:"volumename,omitempty" doc:"name of the disk volume"` - VolumeType string `json:"volumetype,omitempty" doc:"type of the disk volume"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"id of the availability zone"` -} - -// ResourceType returns the type of the resource -func (Snapshot) ResourceType() string { - return "Snapshot" -} - -// CreateSnapshot (Async) creates an instant snapshot of a volume -type CreateSnapshot struct { - VolumeID *UUID `json:"volumeid" doc:"The ID of the disk volume"` - QuiesceVM *bool `json:"quiescevm,omitempty" doc:"quiesce vm if true"` - _ bool `name:"createSnapshot" description:"Creates an instant snapshot of a volume."` -} - -// Response returns the struct to unmarshal -func (CreateSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateSnapshot) AsyncResponse() interface{} { - return new(Snapshot) -} - -// ListRequest builds the ListSnapshot request -func (ss Snapshot) ListRequest() (ListCommand, error) { - // Restricted cannot be applied here because it really has three states - req := &ListSnapshots{ - ID: ss.ID, - Name: ss.Name, - VolumeID: ss.VolumeID, - SnapshotType: ss.SnapshotType, - ZoneID: ss.ZoneID, - // TODO: tags - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListSnapshots - -// ListSnapshots lists the volume snapshots -type ListSnapshots struct { - ID *UUID `json:"id,omitempty" doc:"lists snapshot by snapshot ID"` - IntervalType string `json:"intervaltype,omitempty" doc:"valid values are HOURLY, DAILY, WEEKLY, and MONTHLY."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"lists snapshot by snapshot name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - SnapshotType string `json:"snapshottype,omitempty" doc:"valid values are MANUAL or RECURRING."` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - VolumeID *UUID `json:"volumeid,omitempty" doc:"the ID of the disk volume"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list snapshots by zone id"` - _ bool `name:"listSnapshots" description:"Lists all available snapshots for the account."` -} - -// ListSnapshotsResponse represents a list of volume snapshots -type ListSnapshotsResponse struct { - Count int `json:"count"` - Snapshot []Snapshot `json:"snapshot"` -} - -// DeleteSnapshot (Async) deletes a snapshot of a disk volume -type DeleteSnapshot struct { - ID *UUID `json:"id" doc:"The ID of the snapshot"` - _ bool `name:"deleteSnapshot" description:"Deletes a snapshot of a disk volume."` -} - -// Response returns the struct to unmarshal -func (DeleteSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteSnapshot) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// RevertSnapshot (Async) reverts a volume snapshot -type RevertSnapshot struct { - ID *UUID `json:"id" doc:"The ID of the snapshot"` - _ bool `name:"revertSnapshot" description:"revert a volume snapshot."` -} - -// Response returns the struct to unmarshal -func (RevertSnapshot) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RevertSnapshot) AsyncResponse() interface{} { - return new(BooleanResponse) -} diff --git a/vendor/github.com/exoscale/egoscale/snapshots_response.go b/vendor/github.com/exoscale/egoscale/snapshots_response.go deleted file mode 100644 index 2ca9cff5a..000000000 --- a/vendor/github.com/exoscale/egoscale/snapshots_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSnapshots) Response() interface{} { - return new(ListSnapshotsResponse) -} - -// ListRequest returns itself -func (ls *ListSnapshots) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSnapshots) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSnapshots) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSnapshots) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSnapshotsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSnapshotsResponse was expected, got %T", resp)) - return - } - - for i := range items.Snapshot { - if !callback(&items.Snapshot[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/ssh_keypairs.go b/vendor/github.com/exoscale/egoscale/ssh_keypairs.go deleted file mode 100644 index 9f2bedca0..000000000 --- a/vendor/github.com/exoscale/egoscale/ssh_keypairs.go +++ /dev/null @@ -1,105 +0,0 @@ -package egoscale - -import ( - "context" - "fmt" -) - -// SSHKeyPair represents an SSH key pair -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html#creating-the-ssh-keypair -type SSHKeyPair struct { - Fingerprint string `json:"fingerprint,omitempty" doc:"Fingerprint of the public key"` - Name string `json:"name,omitempty" doc:"Name of the keypair"` - PrivateKey string `json:"privatekey,omitempty" doc:"Private key"` -} - -// Delete removes the given SSH key, by Name -func (ssh SSHKeyPair) Delete(ctx context.Context, client *Client) error { - if ssh.Name == "" { - return fmt.Errorf("an SSH Key Pair may only be deleted using Name") - } - - return client.BooleanRequestWithContext(ctx, &DeleteSSHKeyPair{ - Name: ssh.Name, - }) -} - -// ListRequest builds the ListSSHKeyPairs request -func (ssh SSHKeyPair) ListRequest() (ListCommand, error) { - req := &ListSSHKeyPairs{ - Fingerprint: ssh.Fingerprint, - Name: ssh.Name, - } - - return req, nil -} - -// CreateSSHKeyPair represents a new keypair to be created -type CreateSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - _ bool `name:"createSSHKeyPair" description:"Create a new keypair and returns the private key"` -} - -// Response returns the struct to unmarshal -func (CreateSSHKeyPair) Response() interface{} { - return new(SSHKeyPair) -} - -// DeleteSSHKeyPair represents a new keypair to be created -type DeleteSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - _ bool `name:"deleteSSHKeyPair" description:"Deletes a keypair by name"` -} - -// Response returns the struct to unmarshal -func (DeleteSSHKeyPair) Response() interface{} { - return new(BooleanResponse) -} - -// RegisterSSHKeyPair represents a new registration of a public key in a keypair -type RegisterSSHKeyPair struct { - Name string `json:"name" doc:"Name of the keypair"` - PublicKey string `json:"publickey" doc:"Public key material of the keypair"` - _ bool `name:"registerSSHKeyPair" description:"Register a public key in a keypair under a certain name"` -} - -// Response returns the struct to unmarshal -func (RegisterSSHKeyPair) Response() interface{} { - return new(SSHKeyPair) -} - -//go:generate go run generate/main.go -interface=Listable ListSSHKeyPairs - -// ListSSHKeyPairs represents a query for a list of SSH KeyPairs -type ListSSHKeyPairs struct { - Fingerprint string `json:"fingerprint,omitempty" doc:"A public key fingerprint to look for"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"A key pair name to look for"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listSSHKeyPairs" description:"List registered keypairs"` -} - -// ListSSHKeyPairsResponse represents a list of SSH key pairs -type ListSSHKeyPairsResponse struct { - Count int `json:"count"` - SSHKeyPair []SSHKeyPair `json:"sshkeypair"` -} - -// ResetSSHKeyForVirtualMachine (Async) represents a change for the key pairs -type ResetSSHKeyForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - KeyPair string `json:"keypair" doc:"Name of the ssh key pair used to login to the virtual machine"` - _ bool `name:"resetSSHKeyForVirtualMachine" description:"Resets the SSH Key for virtual machine. The virtual machine must be in a \"Stopped\" state."` -} - -// Response returns the struct to unmarshal -func (ResetSSHKeyForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResetSSHKeyForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go b/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go deleted file mode 100644 index 31c471df2..000000000 --- a/vendor/github.com/exoscale/egoscale/sshkeypairs_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListSSHKeyPairs) Response() interface{} { - return new(ListSSHKeyPairsResponse) -} - -// ListRequest returns itself -func (ls *ListSSHKeyPairs) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListSSHKeyPairs) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListSSHKeyPairs) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListSSHKeyPairs) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListSSHKeyPairsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListSSHKeyPairsResponse was expected, got %T", resp)) - return - } - - for i := range items.SSHKeyPair { - if !callback(&items.SSHKeyPair[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/tags.go b/vendor/github.com/exoscale/egoscale/tags.go deleted file mode 100644 index 56e014850..000000000 --- a/vendor/github.com/exoscale/egoscale/tags.go +++ /dev/null @@ -1,84 +0,0 @@ -package egoscale - -// ResourceTag is a tag associated with a resource -// -// https://community.exoscale.com/documentation/compute/instance-tags/ -type ResourceTag struct { - Account string `json:"account,omitempty" doc:"the account associated with the tag"` - Customer string `json:"customer,omitempty" doc:"customer associated with the tag"` - Key string `json:"key,omitempty" doc:"tag key name"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"id of the resource"` - ResourceType string `json:"resourcetype,omitempty" doc:"resource type"` - Value string `json:"value,omitempty" doc:"tag value"` -} - -// ListRequest builds the ListZones request -func (tag ResourceTag) ListRequest() (ListCommand, error) { - req := &ListTags{ - Customer: tag.Customer, - Key: tag.Key, - ResourceID: tag.ResourceID, - ResourceType: tag.ResourceType, - Value: tag.Value, - } - - return req, nil -} - -// CreateTags (Async) creates resource tag(s) -type CreateTags struct { - ResourceIDs []UUID `json:"resourceids" doc:"list of resources to create the tags for"` - ResourceType string `json:"resourcetype" doc:"type of the resource"` - Tags []ResourceTag `json:"tags" doc:"Map of tags (key/value pairs)"` - Customer string `json:"customer,omitempty" doc:"identifies client specific tag. When the value is not null, the tag can't be used by cloudStack code internally"` - _ bool `name:"createTags" description:"Creates resource tag(s)"` -} - -// Response returns the struct to unmarshal -func (CreateTags) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (CreateTags) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// DeleteTags (Async) deletes the resource tag(s) -type DeleteTags struct { - ResourceIDs []UUID `json:"resourceids" doc:"Delete tags for resource id(s)"` - ResourceType string `json:"resourcetype" doc:"Delete tag by resource type"` - Tags []ResourceTag `json:"tags,omitempty" doc:"Delete tags matching key/value pairs"` - _ bool `name:"deleteTags" description:"Deleting resource tag(s)"` -} - -// Response returns the struct to unmarshal -func (DeleteTags) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeleteTags) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -//go:generate go run generate/main.go -interface=Listable ListTags - -// ListTags list resource tag(s) -type ListTags struct { - Customer string `json:"customer,omitempty" doc:"list by customer name"` - Key string `json:"key,omitempty" doc:"list by key"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ResourceID *UUID `json:"resourceid,omitempty" doc:"list by resource id"` - ResourceType string `json:"resourcetype,omitempty" doc:"list by resource type"` - Value string `json:"value,omitempty" doc:"list by value"` - _ bool `name:"listTags" description:"List resource tag(s)"` -} - -// ListTagsResponse represents a list of resource tags -type ListTagsResponse struct { - Count int `json:"count"` - Tag []ResourceTag `json:"tag"` -} diff --git a/vendor/github.com/exoscale/egoscale/tags_response.go b/vendor/github.com/exoscale/egoscale/tags_response.go deleted file mode 100644 index 870ef49a8..000000000 --- a/vendor/github.com/exoscale/egoscale/tags_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListTags) Response() interface{} { - return new(ListTagsResponse) -} - -// ListRequest returns itself -func (ls *ListTags) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListTags) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListTags) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListTags) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListTagsResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListTagsResponse was expected, got %T", resp)) - return - } - - for i := range items.Tag { - if !callback(&items.Tag[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/templates.go b/vendor/github.com/exoscale/egoscale/templates.go deleted file mode 100644 index 51c077a7d..000000000 --- a/vendor/github.com/exoscale/egoscale/templates.go +++ /dev/null @@ -1,120 +0,0 @@ -package egoscale - -// Template represents a machine to be deployed. -type Template struct { - Account string `json:"account,omitempty" doc:"the account name to which the template belongs"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account id to which the template belongs"` - Bootable bool `json:"bootable,omitempty" doc:"true if the ISO is bootable, false otherwise"` - Checksum string `json:"checksum,omitempty" doc:"checksum of the template"` - Created string `json:"created,omitempty" doc:"the date this template was created"` - CrossZones bool `json:"crossZones,omitempty" doc:"true if the template is managed across all Zones, false otherwise"` - Details map[string]string `json:"details,omitempty" doc:"additional key/value details tied with template"` - DisplayText string `json:"displaytext,omitempty" doc:"the template display text"` - Format string `json:"format,omitempty" doc:"the format of the template."` - HostID *UUID `json:"hostid,omitempty" doc:"the ID of the secondary storage host for the template"` - HostName string `json:"hostname,omitempty" doc:"the name of the secondary storage host for the template"` - ID *UUID `json:"id,omitempty" doc:"the template ID"` - IsDynamicallyScalable bool `json:"isdynamicallyscalable,omitempty" doc:"true if template contains XS/VMWare tools inorder to support dynamic scaling of VM cpu/memory"` - IsExtractable bool `json:"isextractable,omitempty" doc:"true if the template is extractable, false otherwise"` - IsFeatured bool `json:"isfeatured,omitempty" doc:"true if this template is a featured template, false otherwise"` - IsPublic bool `json:"ispublic,omitempty" doc:"true if this template is a public template, false otherwise"` - IsReady bool `json:"isready,omitempty" doc:"true if the template is ready to be deployed from, false otherwise."` - Name string `json:"name,omitempty" doc:"the template name"` - OsTypeID *UUID `json:"ostypeid,omitempty" doc:"the ID of the OS type for this template."` - OsTypeName string `json:"ostypename,omitempty" doc:"the name of the OS type for this template."` - PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the reset password feature is enabled, false otherwise"` - Removed string `json:"removed,omitempty" doc:"the date this template was removed"` - Size int64 `json:"size,omitempty" doc:"the size of the template"` - SourceTemplateID *UUID `json:"sourcetemplateid,omitempty" doc:"the template ID of the parent template if present"` - SSHKeyEnabled bool `json:"sshkeyenabled,omitempty" doc:"true if template is sshkey enabled, false otherwise"` - Status string `json:"status,omitempty" doc:"the status of the template"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with tempate"` - TemplateDirectory string `json:"templatedirectory,omitempty" doc:"Template directory"` - TemplateTag string `json:"templatetag,omitempty" doc:"the tag of this template"` - TemplateType string `json:"templatetype,omitempty" doc:"the type of the template"` - URL string `json:"url,omitempty" doc:"Original URL of the template where it was downloaded"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the zone for this template"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the zone for this template"` -} - -// ResourceType returns the type of the resource -func (Template) ResourceType() string { - return "Template" -} - -// ListRequest builds the ListTemplates request -func (template Template) ListRequest() (ListCommand, error) { - req := &ListTemplates{ - ID: template.ID, - Name: template.Name, - ZoneID: template.ZoneID, - } - if template.IsFeatured { - req.TemplateFilter = "featured" - } - if template.Removed != "" { - *req.ShowRemoved = true - } - - for i := range template.Tags { - req.Tags = append(req.Tags, template.Tags[i]) - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListTemplates - -// ListTemplates represents a template query filter -type ListTemplates struct { - TemplateFilter string `json:"templatefilter" doc:"Possible values are \"featured\", \"self\", \"selfexecutable\",\"sharedexecutable\",\"executable\", and \"community\". * featured : templates that have been marked as featured and public. * self : templates that have been registered or created by the calling user. * selfexecutable : same as self, but only returns templates that can be used to deploy a new VM. * sharedexecutable : templates ready to be deployed that have been granted to the calling user by another user. * executable : templates that are owned by the calling user, or public templates, that can be used to deploy a VM. * community : templates that have been marked as public but not featured."` - ID *UUID `json:"id,omitempty" doc:"the template ID"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"the template name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowRemoved *bool `json:"showremoved,omitempty" doc:"Show removed templates as well"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"list templates by zoneid"` - _ bool `name:"listTemplates" description:"List all public, private, and privileged templates."` -} - -// ListTemplatesResponse represents a list of templates -type ListTemplatesResponse struct { - Count int `json:"count"` - Template []Template `json:"template"` -} - -// OSCategory represents an OS category -type OSCategory struct { - ID *UUID `json:"id,omitempty" doc:"the ID of the OS category"` - Name string `json:"name,omitempty" doc:"the name of the OS category"` -} - -// ListRequest builds the ListOSCategories request -func (osCat OSCategory) ListRequest() (ListCommand, error) { - req := &ListOSCategories{ - Name: osCat.Name, - ID: osCat.ID, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListOSCategories - -// ListOSCategories lists the OS categories -type ListOSCategories struct { - ID *UUID `json:"id,omitempty" doc:"list Os category by id"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"list os category by name"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - _ bool `name:"listOsCategories" description:"Lists all supported OS categories for this cloud."` -} - -// ListOSCategoriesResponse represents a list of OS categories -type ListOSCategoriesResponse struct { - Count int `json:"count"` - OSCategory []OSCategory `json:"oscategory"` -} diff --git a/vendor/github.com/exoscale/egoscale/templates_response.go b/vendor/github.com/exoscale/egoscale/templates_response.go deleted file mode 100644 index b9d61b546..000000000 --- a/vendor/github.com/exoscale/egoscale/templates_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListTemplates) Response() interface{} { - return new(ListTemplatesResponse) -} - -// ListRequest returns itself -func (ls *ListTemplates) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListTemplates) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListTemplates) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListTemplates) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListTemplatesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListTemplatesResponse was expected, got %T", resp)) - return - } - - for i := range items.Template { - if !callback(&items.Template[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/users.go b/vendor/github.com/exoscale/egoscale/users.go deleted file mode 100644 index 71078a97b..000000000 --- a/vendor/github.com/exoscale/egoscale/users.go +++ /dev/null @@ -1,63 +0,0 @@ -package egoscale - -// User represents a User -type User struct { - APIKey string `json:"apikey,omitempty" doc:"the api key of the user"` - Account string `json:"account,omitempty" doc:"the account name of the user"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID of the user"` - Created string `json:"created,omitempty" doc:"the date and time the user account was created"` - Email string `json:"email,omitempty" doc:"the user email address"` - FirstName string `json:"firstname,omitempty" doc:"the user firstname"` - ID *UUID `json:"id,omitempty" doc:"the user ID"` - IsDefault bool `json:"isdefault,omitempty" doc:"true if user is default, false otherwise"` - LastName string `json:"lastname,omitempty" doc:"the user lastname"` - RoleID *UUID `json:"roleid,omitempty" doc:"the ID of the role"` - RoleName string `json:"rolename,omitempty" doc:"the name of the role"` - RoleType string `json:"roletype,omitempty" doc:"the type of the role"` - SecretKey string `json:"secretkey,omitempty" doc:"the secret key of the user"` - State string `json:"state,omitempty" doc:"the user state"` - Timezone string `json:"timezone,omitempty" doc:"the timezone user was created in"` - UserName string `json:"username,omitempty" doc:"the user name"` -} - -// ListRequest builds the ListUsers request -func (user User) ListRequest() (ListCommand, error) { - req := &ListUsers{ - ID: user.ID, - UserName: user.UserName, - } - - return req, nil -} - -// RegisterUserKeys registers a new set of key of the given user -// -// NB: only the APIKey and SecretKey will be filled -type RegisterUserKeys struct { - ID *UUID `json:"id" doc:"User id"` - _ bool `name:"registerUserKeys" description:"This command allows a user to register for the developer API, returning a secret key and an API key. This request is made through the integration API port, so it is a privileged command and must be made on behalf of a user. It is up to the implementer just how the username and password are entered, and then how that translates to an integration API request. Both secret key and API key should be returned to the user"` -} - -// Response returns the struct to unmarshal -func (RegisterUserKeys) Response() interface{} { - return new(User) -} - -//go:generate go run generate/main.go -interface=Listable ListUsers - -// ListUsers represents the search for Users -type ListUsers struct { - ID *UUID `json:"id,omitempty" doc:"List user by ID."` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - State string `json:"state,omitempty" doc:"List users by state of the user account."` - UserName string `json:"username,omitempty" doc:"List user by the username"` - _ bool `name:"listUsers" description:"Lists user accounts"` -} - -// ListUsersResponse represents a list of users -type ListUsersResponse struct { - Count int `json:"count"` - User []User `json:"user"` -} diff --git a/vendor/github.com/exoscale/egoscale/users_response.go b/vendor/github.com/exoscale/egoscale/users_response.go deleted file mode 100644 index 4bd4bf473..000000000 --- a/vendor/github.com/exoscale/egoscale/users_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListUsers) Response() interface{} { - return new(ListUsersResponse) -} - -// ListRequest returns itself -func (ls *ListUsers) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListUsers) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListUsers) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListUsers) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListUsersResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListUsersResponse was expected, got %T", resp)) - return - } - - for i := range items.User { - if !callback(&items.User[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/uuid.go b/vendor/github.com/exoscale/egoscale/uuid.go deleted file mode 100644 index 839f4d2fe..000000000 --- a/vendor/github.com/exoscale/egoscale/uuid.go +++ /dev/null @@ -1,79 +0,0 @@ -package egoscale - -import ( - "encoding/json" - "fmt" - - uuid "github.com/satori/go.uuid" -) - -// UUID holds a UUID v4 -type UUID struct { - uuid.UUID -} - -// DeepCopy create a true copy of the receiver. -func (u *UUID) DeepCopy() *UUID { - if u == nil { - return nil - } - - out := [uuid.Size]byte{} - copy(out[:], u.Bytes()) - - return &UUID{ - (uuid.UUID)(out), - } -} - -// DeepCopyInto copies the receiver into out. -// -// In must be non nil. -func (u *UUID) DeepCopyInto(out *UUID) { - o := [uuid.Size]byte{} - copy(o[:], u.Bytes()) - - out.UUID = (uuid.UUID)(o) -} - -// Equal returns true if itself is equal to other. -func (u UUID) Equal(other UUID) bool { - return uuid.Equal(u.UUID, other.UUID) -} - -// UnmarshalJSON unmarshals the raw JSON into the UUID. -func (u *UUID) UnmarshalJSON(b []byte) error { - var s string - if err := json.Unmarshal(b, &s); err != nil { - return err - } - - new, err := ParseUUID(s) - if err == nil { - u.UUID = new.UUID - } - return err -} - -// MarshalJSON converts the UUID to a string representation. -func (u UUID) MarshalJSON() ([]byte, error) { - return []byte(fmt.Sprintf("%q", u.String())), nil -} - -// ParseUUID parses a string into a UUID. -func ParseUUID(s string) (*UUID, error) { - u, err := uuid.FromString(s) - if err != nil { - return nil, err - } - return &UUID{u}, nil -} - -// MustParseUUID acts like ParseUUID but panic in case of a failure. -func MustParseUUID(s string) *UUID { - u, e := ParseUUID(s) - if e != nil { - panic(e) - } - return u -} diff --git a/vendor/github.com/exoscale/egoscale/version.go b/vendor/github.com/exoscale/egoscale/version.go deleted file mode 100644 index f8164f086..000000000 --- a/vendor/github.com/exoscale/egoscale/version.go +++ /dev/null @@ -1,4 +0,0 @@ -package egoscale - -// Version of the library -const Version = "0.14.3" diff --git a/vendor/github.com/exoscale/egoscale/virtual_machines.go b/vendor/github.com/exoscale/egoscale/virtual_machines.go deleted file mode 100644 index f48ef58fe..000000000 --- a/vendor/github.com/exoscale/egoscale/virtual_machines.go +++ /dev/null @@ -1,612 +0,0 @@ -package egoscale - -import ( - "bytes" - "compress/gzip" - "context" - "encoding/base64" - "fmt" - "io/ioutil" - "net" - "net/url" -) - -// VirtualMachineState holds the state of the instance -// -// https://github.com/apache/cloudstack/blob/master/api/src/main/java/com/cloud/vm/VirtualMachine.java -type VirtualMachineState string - -const ( - // VirtualMachineStarting VM is being started. At this state, you should find host id filled which means it's being started on that host - VirtualMachineStarting VirtualMachineState = "Starting" - // VirtualMachineRunning VM is running. host id has the host that it is running on - VirtualMachineRunning VirtualMachineState = "Running" - // VirtualMachineStopping VM is being stopped. host id has the host that it is being stopped on - VirtualMachineStopping VirtualMachineState = "Stopping" - // VirtualMachineStopped VM is stopped. host id should be null - VirtualMachineStopped VirtualMachineState = "Stopped" - // VirtualMachineDestroyed VM is marked for destroy - VirtualMachineDestroyed VirtualMachineState = "Destroyed" - // VirtualMachineExpunging "VM is being expunged - VirtualMachineExpunging VirtualMachineState = "Expunging" - // VirtualMachineMigrating VM is being live migrated. host id holds destination host, last host id holds source host - VirtualMachineMigrating VirtualMachineState = "Migrating" - // VirtualMachineMoving VM is being migrated offline (volume is being moved). - VirtualMachineMoving VirtualMachineState = "Moving" - // VirtualMachineError VM is in error - VirtualMachineError VirtualMachineState = "Error" - // VirtualMachineUnknown VM state is unknown - VirtualMachineUnknown VirtualMachineState = "Unknown" - // VirtualMachineShutdowned VM is shutdowned from inside - VirtualMachineShutdowned VirtualMachineState = "Shutdowned" -) - -// VirtualMachine represents a virtual machine -// -// See: http://docs.cloudstack.apache.org/projects/cloudstack-administration/en/stable/virtual_machines.html -type VirtualMachine struct { - Account string `json:"account,omitempty" doc:"the account associated with the virtual machine"` - AccountID *UUID `json:"accountid,omitempty" doc:"the account ID associated with the virtual machine"` - AffinityGroup []AffinityGroup `json:"affinitygroup,omitempty" doc:"list of affinity groups associated with the virtual machine"` - ClusterID *UUID `json:"clusterid,omitempty" doc:"the ID of the vm's cluster"` - ClusterName string `json:"clustername,omitempty" doc:"the name of the vm's cluster"` - CPUNumber int `json:"cpunumber,omitempty" doc:"the number of cpu this virtual machine is running with"` - CPUSpeed int `json:"cpuspeed,omitempty" doc:"the speed of each cpu"` - CPUUsed string `json:"cpuused,omitempty" doc:"the amount of the vm's CPU currently used"` - Created string `json:"created,omitempty" doc:"the date when this virtual machine was created"` - Details map[string]string `json:"details,omitempty" doc:"Vm details in key/value pairs."` - DiskIoRead int64 `json:"diskioread,omitempty" doc:"the read (io) of disk on the vm"` - DiskIoWrite int64 `json:"diskiowrite,omitempty" doc:"the write (io) of disk on the vm"` - DiskKbsRead int64 `json:"diskkbsread,omitempty" doc:"the read (bytes) of disk on the vm"` - DiskKbsWrite int64 `json:"diskkbswrite,omitempty" doc:"the write (bytes) of disk on the vm"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"the ID of the disk offering of the virtual machine"` - DiskOfferingName string `json:"diskofferingname,omitempty" doc:"the name of the disk offering of the virtual machine"` - DisplayName string `json:"displayname,omitempty" doc:"user generated name. The name of the virtual machine is returned if no displayname exists."` - ForVirtualNetwork bool `json:"forvirtualnetwork,omitempty" doc:"the virtual network for the service offering"` - Group string `json:"group,omitempty" doc:"the group name of the virtual machine"` - GroupID *UUID `json:"groupid,omitempty" doc:"the group ID of the virtual machine"` - HAEnable bool `json:"haenable,omitempty" doc:"true if high-availability is enabled, false otherwise"` - HostName string `json:"hostname,omitempty" doc:"the name of the host for the virtual machine"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - InstanceName string `json:"instancename,omitempty" doc:"instance name of the user vm; this parameter is returned to the ROOT admin only"` - IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"` - IsoID *UUID `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"` - IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"` - KeyPair string `json:"keypair,omitempty" doc:"ssh key-pair"` - Memory int `json:"memory,omitempty" doc:"the memory allocated for the virtual machine"` - Name string `json:"name,omitempty" doc:"the name of the virtual machine"` - NetworkKbsRead int64 `json:"networkkbsread,omitempty" doc:"the incoming network traffic on the vm"` - NetworkKbsWrite int64 `json:"networkkbswrite,omitempty" doc:"the outgoing network traffic on the host"` - Nic []Nic `json:"nic,omitempty" doc:"the list of nics associated with vm"` - OSCategoryID *UUID `json:"oscategoryid,omitempty" doc:"Os category ID of the virtual machine"` - OSCategoryName string `json:"oscategoryname,omitempty" doc:"Os category name of the virtual machine"` - OSTypeID *UUID `json:"ostypeid,omitempty" doc:"OS type id of the vm"` - Password string `json:"password,omitempty" doc:"the password (if exists) of the virtual machine"` - PasswordEnabled bool `json:"passwordenabled,omitempty" doc:"true if the password rest feature is enabled, false otherwise"` - PCIDevices []PCIDevice `json:"pcidevices,omitempty" doc:"list of PCI devices"` - PodID *UUID `json:"podid,omitempty" doc:"the ID of the vm's pod"` - PodName string `json:"podname,omitempty" doc:"the name of the vm's pod"` - PublicIP string `json:"publicip,omitempty" doc:"public IP address id associated with vm via Static nat rule"` - PublicIPID *UUID `json:"publicipid,omitempty" doc:"public IP address id associated with vm via Static nat rule"` - RootDeviceID int64 `json:"rootdeviceid,omitempty" doc:"device ID of the root volume"` - RootDeviceType string `json:"rootdevicetype,omitempty" doc:"device type of the root volume"` - SecurityGroup []SecurityGroup `json:"securitygroup,omitempty" doc:"list of security groups associated with the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"the ID of the service offering of the virtual machine"` - ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"the name of the service offering of the virtual machine"` - ServiceState string `json:"servicestate,omitempty" doc:"State of the Service from LB rule"` - State string `json:"state,omitempty" doc:"the state of the virtual machine"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with vm"` - TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"` - TemplateID *UUID `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."` - TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the ID of the availablility zone for the virtual machine"` - ZoneName string `json:"zonename,omitempty" doc:"the name of the availability zone for the virtual machine"` -} - -// ResourceType returns the type of the resource -func (VirtualMachine) ResourceType() string { - return "UserVM" -} - -// Delete destroys the VM -func (vm VirtualMachine) Delete(ctx context.Context, client *Client) error { - _, err := client.RequestWithContext(ctx, &DestroyVirtualMachine{ - ID: vm.ID, - }) - - return err -} - -// ListRequest builds the ListVirtualMachines request -func (vm VirtualMachine) ListRequest() (ListCommand, error) { - // XXX: AffinityGroupID, SecurityGroupID - - req := &ListVirtualMachines{ - GroupID: vm.GroupID, - ID: vm.ID, - Name: vm.Name, - State: vm.State, - TemplateID: vm.TemplateID, - ZoneID: vm.ZoneID, - } - - nic := vm.DefaultNic() - if nic != nil { - req.IPAddress = nic.IPAddress - } - - for i := range vm.Tags { - req.Tags = append(req.Tags, vm.Tags[i]) - } - - return req, nil -} - -// DefaultNic returns the default nic -func (vm VirtualMachine) DefaultNic() *Nic { - for i, nic := range vm.Nic { - if nic.IsDefault { - return &vm.Nic[i] - } - } - - return nil -} - -// IP returns the default nic IP address -func (vm VirtualMachine) IP() *net.IP { - nic := vm.DefaultNic() - if nic != nil { - ip := nic.IPAddress - return &ip - } - - return nil -} - -// NicsByType returns the corresponding interfaces base on the given type -func (vm VirtualMachine) NicsByType(nicType string) []Nic { - nics := make([]Nic, 0) - for _, nic := range vm.Nic { - if nic.Type == nicType { - // XXX The API forgets to specify it - n := nic - n.VirtualMachineID = vm.ID - nics = append(nics, n) - } - } - return nics -} - -// NicByNetworkID returns the corresponding interface based on the given NetworkID -// -// A VM cannot be connected twice to a same network. -func (vm VirtualMachine) NicByNetworkID(networkID UUID) *Nic { - for _, nic := range vm.Nic { - if nic.NetworkID.Equal(networkID) { - n := nic - n.VirtualMachineID = vm.ID - return &n - } - } - return nil -} - -// NicByID returns the corresponding interface base on its ID -func (vm VirtualMachine) NicByID(nicID UUID) *Nic { - for _, nic := range vm.Nic { - if nic.ID.Equal(nicID) { - n := nic - n.VirtualMachineID = vm.ID - return &n - } - } - - return nil -} - -// IPToNetwork represents a mapping between ip and networks -type IPToNetwork struct { - IP net.IP `json:"ip,omitempty"` - Ipv6 net.IP `json:"ipv6,omitempty"` - NetworkID *UUID `json:"networkid,omitempty"` -} - -// PCIDevice represents a PCI card present in the host -type PCIDevice struct { - PCIVendorName string `json:"pcivendorname,omitempty" doc:"Device vendor name of pci card"` - DeviceID string `json:"deviceid,omitempty" doc:"Device model ID of pci card"` - RemainingCapacity int `json:"remainingcapacity,omitempty" doc:"Remaining capacity in terms of no. of more VMs that can be deployped with this vGPU type"` - MaxCapacity int `json:"maxcapacity,omitempty" doc:"Maximum vgpu can be created with this vgpu type on the given pci group"` - PCIVendorID string `json:"pcivendorid,omitempty" doc:"Device vendor ID of pci card"` - PCIDeviceName string `json:"pcidevicename,omitempty" doc:"Device model name of pci card"` -} - -// Password represents an encrypted password -// -// TODO: method to decrypt it, https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=34014652 -type Password struct { - EncryptedPassword string `json:"encryptedpassword"` -} - -// VirtualMachineUserData represents the base64 encoded user-data -type VirtualMachineUserData struct { - UserData string `json:"userdata" doc:"Base 64 encoded VM user data"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"the ID of the virtual machine"` -} - -// Decode decodes as a readable string the content of the user-data (base64 · gzip) -func (userdata VirtualMachineUserData) Decode() (string, error) { - data, err := base64.StdEncoding.DecodeString(userdata.UserData) - if err != nil { - return "", err - } - // 0x1f8b is the magic number for gzip - if len(data) < 2 || data[0] != 0x1f || data[1] != 0x8b { - return string(data), nil - } - gr, err := gzip.NewReader(bytes.NewBuffer(data)) - if err != nil { - return "", err - } - defer gr.Close() // nolint: errcheck - - str, err := ioutil.ReadAll(gr) - if err != nil { - return "", err - } - return string(str), nil -} - -// DeployVirtualMachine (Async) represents the machine creation -// -// Regarding the UserData field, the client is responsible to base64 (and probably gzip) it. Doing it within this library would make the integration with other tools, e.g. Terraform harder. -type DeployVirtualMachine struct { - AffinityGroupIDs []UUID `json:"affinitygroupids,omitempty" doc:"comma separated list of affinity groups id that are going to be applied to the virtual machine. Mutually exclusive with affinitygroupnames parameter"` - AffinityGroupNames []string `json:"affinitygroupnames,omitempty" doc:"comma separated list of affinity groups names that are going to be applied to the virtual machine.Mutually exclusive with affinitygroupids parameter"` - Details map[string]string `json:"details,omitempty" doc:"used to specify the custom parameters."` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"the ID of the disk offering for the virtual machine. If the template is of ISO format, the diskofferingid is for the root disk volume. Otherwise this parameter is used to indicate the offering for the data disk volume. If the templateid parameter passed is from a Template object, the diskofferingid refers to a DATA Disk Volume created. If the templateid parameter passed is from an ISO object, the diskofferingid refers to a ROOT Disk Volume created."` - DisplayName string `json:"displayname,omitempty" doc:"an optional user generated name for the virtual machine"` - Group string `json:"group,omitempty" doc:"an optional group for the virtual machine"` - IP4 *bool `json:"ip4,omitempty" doc:"True to set an IPv4 to the default interface"` - IP6 *bool `json:"ip6,omitempty" doc:"True to set an IPv6 to the default interface"` - IP6Address net.IP `json:"ip6address,omitempty" doc:"the ipv6 address for default vm's network"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"the ip address for default vm's network"` - Keyboard string `json:"keyboard,omitempty" doc:"an optional keyboard device type for the virtual machine. valid value can be one of de,de-ch,es,fi,fr,fr-be,fr-ch,is,it,jp,nl-be,no,pt,uk,us"` - KeyPair string `json:"keypair,omitempty" doc:"name of the ssh key pair used to login to the virtual machine"` - Name string `json:"name,omitempty" doc:"host name for the virtual machine"` - NetworkIDs []UUID `json:"networkids,omitempty" doc:"list of network ids used by virtual machine. Can't be specified with ipToNetworkList parameter"` - RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on deploy. Value is in GB. Only applies to template-based deployments. Analogous to details[0].rootdisksize, which takes precedence over this parameter if both are provided"` - SecurityGroupIDs []UUID `json:"securitygroupids,omitempty" doc:"comma separated list of security groups id that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupnames parameter"` - SecurityGroupNames []string `json:"securitygroupnames,omitempty" doc:"comma separated list of security groups names that going to be applied to the virtual machine. Should be passed only when vm is created from a zone with Basic Network support. Mutually exclusive with securitygroupids parameter"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"` - Size int64 `json:"size,omitempty" doc:"the arbitrary size for the DATADISK volume. Mutually exclusive with diskofferingid"` - StartVM *bool `json:"startvm,omitempty" doc:"true if start vm after creating. Default value is true"` - TemplateID *UUID `json:"templateid" doc:"the ID of the template for the virtual machine"` - UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."` - ZoneID *UUID `json:"zoneid" doc:"availability zone for the virtual machine"` - _ bool `name:"deployVirtualMachine" description:"Creates and automatically starts a virtual machine based on a service offering, disk offering, and template."` -} - -func (req DeployVirtualMachine) onBeforeSend(_ url.Values) error { - // Either AffinityGroupIDs or AffinityGroupNames must be set - if len(req.AffinityGroupIDs) > 0 && len(req.AffinityGroupNames) > 0 { - return fmt.Errorf("either AffinityGroupIDs or AffinityGroupNames must be set") - } - - // Either SecurityGroupIDs or SecurityGroupNames must be set - if len(req.SecurityGroupIDs) > 0 && len(req.SecurityGroupNames) > 0 { - return fmt.Errorf("either SecurityGroupIDs or SecurityGroupNames must be set") - } - - return nil -} - -// Response returns the struct to unmarshal -func (DeployVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DeployVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// StartVirtualMachine (Async) represents the creation of the virtual machine -type StartVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"startVirtualMachine" description:"Starts a virtual machine."` -} - -// Response returns the struct to unmarshal -func (StartVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (StartVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// StopVirtualMachine (Async) represents the stopping of the virtual machine -type StopVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - Forced *bool `json:"forced,omitempty" doc:"Force stop the VM (vm is marked as Stopped even when command fails to be send to the backend). The caller knows the VM is stopped."` - _ bool `name:"stopVirtualMachine" description:"Stops a virtual machine."` -} - -// Response returns the struct to unmarshal -func (StopVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (StopVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RebootVirtualMachine (Async) represents the rebooting of the virtual machine -type RebootVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"rebootVirtualMachine" description:"Reboots a virtual machine."` -} - -// Response returns the struct to unmarshal -func (RebootVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RebootVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RestoreVirtualMachine (Async) represents the restoration of the virtual machine -type RestoreVirtualMachine struct { - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - TemplateID *UUID `json:"templateid,omitempty" doc:"an optional template Id to restore vm from the new template. This can be an ISO id in case of restore vm deployed using ISO"` - RootDiskSize int64 `json:"rootdisksize,omitempty" doc:"Optional field to resize root disk on restore. Value is in GB. Only applies to template-based deployments."` - _ bool `name:"restoreVirtualMachine" description:"Restore a VM to original template/ISO or new template/ISO"` -} - -// Response returns the struct to unmarshal -func (RestoreVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RestoreVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RecoverVirtualMachine represents the restoration of the virtual machine -type RecoverVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"recoverVirtualMachine" description:"Recovers a virtual machine."` -} - -// Response returns the struct to unmarshal -func (RecoverVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// DestroyVirtualMachine (Async) represents the destruction of the virtual machine -type DestroyVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"destroyVirtualMachine" description:"Destroys a virtual machine."` -} - -// Response returns the struct to unmarshal -func (DestroyVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (DestroyVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// UpdateVirtualMachine represents the update of the virtual machine -type UpdateVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"Details in key/value pairs."` - DisplayName string `json:"displayname,omitempty" doc:"user generated name"` - Group string `json:"group,omitempty" doc:"group of the virtual machine"` - Name string `json:"name,omitempty" doc:"new host name of the vm. The VM has to be stopped/started for this update to take affect"` - SecurityGroupIDs []UUID `json:"securitygroupids,omitempty" doc:"list of security group ids to be applied on the virtual machine."` - UserData string `json:"userdata,omitempty" doc:"an optional binary data that can be sent to the virtual machine upon a successful deployment. This binary data must be base64 encoded before adding it to the request. Using HTTP GET (via querystring), you can send up to 2KB of data after base64 encoding. Using HTTP POST(via POST body), you can send up to 32K of data after base64 encoding."` - _ bool `name:"updateVirtualMachine" description:"Updates properties of a virtual machine. The VM has to be stopped and restarted for the new properties to take effect. UpdateVirtualMachine does not first check whether the VM is stopped. Therefore, stop the VM manually before issuing this call."` -} - -// Response returns the struct to unmarshal -func (UpdateVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// ExpungeVirtualMachine represents the annihilation of a VM -type ExpungeVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"expungeVirtualMachine" description:"Expunge a virtual machine. Once expunged, it cannot be recoverd."` -} - -// Response returns the struct to unmarshal -func (ExpungeVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ExpungeVirtualMachine) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ScaleVirtualMachine (Async) scales the virtual machine to a new service offering. -// -// ChangeServiceForVirtualMachine does the same thing but returns the -// new Virtual Machine which is more consistent with the rest of the API. -type ScaleVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the ID of the service offering for the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu,memory and cpunumber. example details[i].name=value"` - _ bool `name:"scaleVirtualMachine" description:"Scales the virtual machine to a new service offering."` -} - -// Response returns the struct to unmarshal -func (ScaleVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ScaleVirtualMachine) AsyncResponse() interface{} { - return new(BooleanResponse) -} - -// ChangeServiceForVirtualMachine changes the service offering for a virtual machine. The virtual machine must be in a "Stopped" state for this command to take effect. -type ChangeServiceForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - ServiceOfferingID *UUID `json:"serviceofferingid" doc:"the service offering ID to apply to the virtual machine"` - Details map[string]string `json:"details,omitempty" doc:"name value pairs of custom parameters for cpu, memory and cpunumber. example details[i].name=value"` - _ bool `name:"changeServiceForVirtualMachine" description:"Changes the service offering for a virtual machine. The virtual machine must be in a \"Stopped\" state for this command to take effect."` -} - -// Response returns the struct to unmarshal -func (ChangeServiceForVirtualMachine) Response() interface{} { - return new(VirtualMachine) -} - -// ResetPasswordForVirtualMachine resets the password for virtual machine. The virtual machine must be in a "Stopped" state... -type ResetPasswordForVirtualMachine struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"resetPasswordForVirtualMachine" description:"Resets the password for virtual machine. The virtual machine must be in a \"Stopped\" state and the template must already support this feature for this command to take effect."` -} - -// Response returns the struct to unmarshal -func (ResetPasswordForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResetPasswordForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// GetVMPassword asks for an encrypted password -type GetVMPassword struct { - ID *UUID `json:"id" doc:"The ID of the virtual machine"` - _ bool `name:"getVMPassword" description:"Returns an encrypted password for the VM"` -} - -// Response returns the struct to unmarshal -func (GetVMPassword) Response() interface{} { - return new(Password) -} - -//go:generate go run generate/main.go -interface=Listable ListVirtualMachines - -// ListVirtualMachines represents a search for a VM -type ListVirtualMachines struct { - AffinityGroupID *UUID `json:"affinitygroupid,omitempty" doc:"list vms by affinity group"` - Details []string `json:"details,omitempty" doc:"comma separated list of host details requested, value can be a list of [all, group, nics, stats, secgrp, tmpl, servoff, diskoff, iso, volume, min, affgrp]. If no parameter is passed in, the details will be defaulted to all"` - ForVirtualNetwork *bool `json:"forvirtualnetwork,omitempty" doc:"list by network type; true if need to list vms using Virtual Network, false otherwise"` - GroupID *UUID `json:"groupid,omitempty" doc:"the group ID"` - ID *UUID `json:"id,omitempty" doc:"the ID of the virtual machine"` - IDs []UUID `json:"ids,omitempty" doc:"the IDs of the virtual machines, mutually exclusive with id"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"an IP address to filter the result"` - IsoID *UUID `json:"isoid,omitempty" doc:"list vms by iso"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"name of the virtual machine"` - NetworkID *UUID `json:"networkid,omitempty" doc:"list by network id"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ServiceOfferindID *UUID `json:"serviceofferingid,omitempty" doc:"list by the service offering"` - State string `json:"state,omitempty" doc:"state of the virtual machine"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - TemplateID *UUID `json:"templateid,omitempty" doc:"list vms by template"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"the availability zone ID"` - _ bool `name:"listVirtualMachines" description:"List the virtual machines owned by the account."` -} - -// ListVirtualMachinesResponse represents a list of virtual machines -type ListVirtualMachinesResponse struct { - Count int `json:"count"` - VirtualMachine []VirtualMachine `json:"virtualmachine"` -} - -// AddNicToVirtualMachine (Async) adds a NIC to a VM -type AddNicToVirtualMachine struct { - NetworkID *UUID `json:"networkid" doc:"Network ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Static IP address lease for the corresponding NIC and network which should be in the range defined in the network"` - _ bool `name:"addNicToVirtualMachine" description:"Adds VM to specified network by creating a NIC"` -} - -// Response returns the struct to unmarshal -func (AddNicToVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (AddNicToVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// RemoveNicFromVirtualMachine (Async) removes a NIC from a VM -type RemoveNicFromVirtualMachine struct { - NicID *UUID `json:"nicid" doc:"NIC ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - _ bool `name:"removeNicFromVirtualMachine" description:"Removes VM from specified network by deleting a NIC"` -} - -// Response returns the struct to unmarshal -func (RemoveNicFromVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (RemoveNicFromVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// UpdateDefaultNicForVirtualMachine (Async) adds a NIC to a VM -type UpdateDefaultNicForVirtualMachine struct { - NicID *UUID `json:"nicid" doc:"NIC ID"` - VirtualMachineID *UUID `json:"virtualmachineid" doc:"Virtual Machine ID"` - _ bool `name:"updateDefaultNicForVirtualMachine" description:"Changes the default NIC on a VM"` -} - -// Response returns the struct to unmarshal -func (UpdateDefaultNicForVirtualMachine) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateDefaultNicForVirtualMachine) AsyncResponse() interface{} { - return new(VirtualMachine) -} - -// GetVirtualMachineUserData returns the user-data of the given VM -type GetVirtualMachineUserData struct { - VirtualMachineID *UUID `json:"virtualmachineid" doc:"The ID of the virtual machine"` - _ bool `name:"getVirtualMachineUserData" description:"Returns user data associated with the VM"` -} - -// Response returns the struct to unmarshal -func (GetVirtualMachineUserData) Response() interface{} { - return new(VirtualMachineUserData) -} - -// UpdateVMNicIP updates the default IP address of a VM Nic -type UpdateVMNicIP struct { - _ bool `name:"updateVmNicIp" description:"Update the default Ip of a VM Nic"` - IPAddress net.IP `json:"ipaddress,omitempty" doc:"Static IP address lease for the corresponding NIC and network which should be in the range defined in the network. If absent, the call removes the lease associated with the nic."` - NicID *UUID `json:"nicid" doc:"the ID of the nic."` -} - -// Response returns the struct to unmarshal -func (UpdateVMNicIP) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (UpdateVMNicIP) AsyncResponse() interface{} { - return new(VirtualMachine) -} diff --git a/vendor/github.com/exoscale/egoscale/virtualmachines_response.go b/vendor/github.com/exoscale/egoscale/virtualmachines_response.go deleted file mode 100644 index 9aafb01a3..000000000 --- a/vendor/github.com/exoscale/egoscale/virtualmachines_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListVirtualMachines) Response() interface{} { - return new(ListVirtualMachinesResponse) -} - -// ListRequest returns itself -func (ls *ListVirtualMachines) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListVirtualMachines) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListVirtualMachines) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListVirtualMachines) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListVirtualMachinesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListVirtualMachinesResponse was expected, got %T", resp)) - return - } - - for i := range items.VirtualMachine { - if !callback(&items.VirtualMachine[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/volumes.go b/vendor/github.com/exoscale/egoscale/volumes.go deleted file mode 100644 index f942890a4..000000000 --- a/vendor/github.com/exoscale/egoscale/volumes.go +++ /dev/null @@ -1,113 +0,0 @@ -package egoscale - -// Volume represents a volume linked to a VM -type Volume struct { - Account string `json:"account,omitempty" doc:"the account associated with the disk volume"` - Attached string `json:"attached,omitempty" doc:"the date the volume was attached to a VM instance"` - ChainInfo string `json:"chaininfo,omitempty" doc:"the chain info of the volume"` - ClusterID *UUID `json:"clusterid,omitempty" doc:"ID of the cluster"` - ClusterName string `json:"clustername,omitempty" doc:"name of the cluster"` - Created string `json:"created,omitempty" doc:"the date the disk volume was created"` - Destroyed bool `json:"destroyed,omitempty" doc:"the boolean state of whether the volume is destroyed or not"` - DeviceID int64 `json:"deviceid,omitempty" doc:"the ID of the device on user vm the volume is attahed to. This tag is not returned when the volume is detached."` - DiskBytesReadRate int64 `json:"diskBytesReadRate,omitempty" doc:"bytes read rate of the disk volume"` - DiskBytesWriteRate int64 `json:"diskBytesWriteRate,omitempty" doc:"bytes write rate of the disk volume"` - DiskIopsReadRate int64 `json:"diskIopsReadRate,omitempty" doc:"io requests read rate of the disk volume"` - DiskIopsWriteRate int64 `json:"diskIopsWriteRate,omitempty" doc:"io requests write rate of the disk volume"` - DiskOfferingDisplayText string `json:"diskofferingdisplaytext,omitempty" doc:"the display text of the disk offering"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"ID of the disk offering"` - DiskOfferingName string `json:"diskofferingname,omitempty" doc:"name of the disk offering"` - DisplayVolume bool `json:"displayvolume,omitempty" doc:"an optional field whether to the display the volume to the end user or not."` - Hypervisor string `json:"hypervisor,omitempty" doc:"Hypervisor the volume belongs to"` - ID *UUID `json:"id,omitempty" doc:"ID of the disk volume"` - IsExtractable *bool `json:"isextractable,omitempty" doc:"true if the volume is extractable, false otherwise"` - IsoDisplayText string `json:"isodisplaytext,omitempty" doc:"an alternate display text of the ISO attached to the virtual machine"` - IsoID *UUID `json:"isoid,omitempty" doc:"the ID of the ISO attached to the virtual machine"` - IsoName string `json:"isoname,omitempty" doc:"the name of the ISO attached to the virtual machine"` - MaxIops int64 `json:"maxiops,omitempty" doc:"max iops of the disk volume"` - MinIops int64 `json:"miniops,omitempty" doc:"min iops of the disk volume"` - Name string `json:"name,omitempty" doc:"name of the disk volume"` - Path string `json:"path,omitempty" doc:"the path of the volume"` - PodID *UUID `json:"podid,omitempty" doc:"ID of the pod"` - PodName string `json:"podname,omitempty" doc:"name of the pod"` - QuiesceVM bool `json:"quiescevm,omitempty" doc:"need quiesce vm or not when taking snapshot"` - ServiceOfferingDisplayText string `json:"serviceofferingdisplaytext,omitempty" doc:"the display text of the service offering for root disk"` - ServiceOfferingID *UUID `json:"serviceofferingid,omitempty" doc:"ID of the service offering for root disk"` - ServiceOfferingName string `json:"serviceofferingname,omitempty" doc:"name of the service offering for root disk"` - Size uint64 `json:"size,omitempty" doc:"size of the disk volume"` - SnapshotID *UUID `json:"snapshotid,omitempty" doc:"ID of the snapshot from which this volume was created"` - State string `json:"state,omitempty" doc:"the state of the disk volume"` - Status string `json:"status,omitempty" doc:"the status of the volume"` - Storage string `json:"storage,omitempty" doc:"name of the primary storage hosting the disk volume"` - StorageID *UUID `json:"storageid,omitempty" doc:"id of the primary storage hosting the disk volume; returned to admin user only"` - StorageType string `json:"storagetype,omitempty" doc:"shared or local storage"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with volume"` - TemplateDisplayText string `json:"templatedisplaytext,omitempty" doc:"an alternate display text of the template for the virtual machine"` - TemplateID *UUID `json:"templateid,omitempty" doc:"the ID of the template for the virtual machine. A -1 is returned if the virtual machine was created from an ISO file."` // no *UUID because of the -1 thingy... - TemplateName string `json:"templatename,omitempty" doc:"the name of the template for the virtual machine"` - Type string `json:"type,omitempty" doc:"type of the disk volume (ROOT or DATADISK)"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"id of the virtual machine"` - VMDisplayName string `json:"vmdisplayname,omitempty" doc:"display name of the virtual machine"` - VMName string `json:"vmname,omitempty" doc:"name of the virtual machine"` - VMState string `json:"vmstate,omitempty" doc:"state of the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"ID of the availability zone"` - ZoneName string `json:"zonename,omitempty" doc:"name of the availability zone"` -} - -// ResourceType returns the type of the resource -func (Volume) ResourceType() string { - return "Volume" -} - -// ListRequest builds the ListVolumes request -func (vol Volume) ListRequest() (ListCommand, error) { - req := &ListVolumes{ - Name: vol.Name, - Type: vol.Type, - VirtualMachineID: vol.VirtualMachineID, - ZoneID: vol.ZoneID, - } - - return req, nil -} - -// ResizeVolume (Async) resizes a volume -type ResizeVolume struct { - ID *UUID `json:"id" doc:"the ID of the disk volume"` - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"new disk offering id"` - Size int64 `json:"size,omitempty" doc:"New volume size in G (must be larger than current size since shrinking the disk is not supported)"` - _ bool `name:"resizeVolume" description:"Resizes a volume"` -} - -// Response returns the struct to unmarshal -func (ResizeVolume) Response() interface{} { - return new(AsyncJobResult) -} - -// AsyncResponse returns the struct to unmarshal the async job -func (ResizeVolume) AsyncResponse() interface{} { - return new(Volume) -} - -//go:generate go run generate/main.go -interface=Listable ListVolumes - -// ListVolumes represents a query listing volumes -type ListVolumes struct { - DiskOfferingID *UUID `json:"diskofferingid,omitempty" doc:"List volumes by disk offering"` - ID *UUID `json:"id,omitempty" doc:"The ID of the disk volume"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"The name of the disk volume"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List resources by tags (key/value pairs)"` - Type string `json:"type,omitempty" doc:"The type of disk volume"` - VirtualMachineID *UUID `json:"virtualmachineid,omitempty" doc:"The ID of the virtual machine"` - ZoneID *UUID `json:"zoneid,omitempty" doc:"The ID of the availability zone"` - _ bool `name:"listVolumes" description:"Lists all volumes."` -} - -// ListVolumesResponse represents a list of volumes -type ListVolumesResponse struct { - Count int `json:"count"` - Volume []Volume `json:"volume"` -} diff --git a/vendor/github.com/exoscale/egoscale/volumes_response.go b/vendor/github.com/exoscale/egoscale/volumes_response.go deleted file mode 100644 index c7486bc1e..000000000 --- a/vendor/github.com/exoscale/egoscale/volumes_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListVolumes) Response() interface{} { - return new(ListVolumesResponse) -} - -// ListRequest returns itself -func (ls *ListVolumes) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListVolumes) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListVolumes) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListVolumes) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListVolumesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListVolumesResponse was expected, got %T", resp)) - return - } - - for i := range items.Volume { - if !callback(&items.Volume[i], nil) { - break - } - } -} diff --git a/vendor/github.com/exoscale/egoscale/zones.go b/vendor/github.com/exoscale/egoscale/zones.go deleted file mode 100644 index 763246033..000000000 --- a/vendor/github.com/exoscale/egoscale/zones.go +++ /dev/null @@ -1,62 +0,0 @@ -package egoscale - -import ( - "net" -) - -// Zone represents a data center -// -// TODO: represent correctly the capacity field. -type Zone struct { - AllocationState string `json:"allocationstate,omitempty" doc:"the allocation state of the cluster"` - Description string `json:"description,omitempty" doc:"Zone description"` - DhcpProvider string `json:"dhcpprovider,omitempty" doc:"the dhcp Provider for the Zone"` - DisplayText string `json:"displaytext,omitempty" doc:"the display text of the zone"` - DNS1 net.IP `json:"dns1,omitempty" doc:"the first DNS for the Zone"` - DNS2 net.IP `json:"dns2,omitempty" doc:"the second DNS for the Zone"` - GuestCIDRAddress *CIDR `json:"guestcidraddress,omitempty" doc:"the guest CIDR address for the Zone"` - ID *UUID `json:"id,omitempty" doc:"Zone id"` - InternalDNS1 net.IP `json:"internaldns1,omitempty" doc:"the first internal DNS for the Zone"` - InternalDNS2 net.IP `json:"internaldns2,omitempty" doc:"the second internal DNS for the Zone"` - IP6DNS1 net.IP `json:"ip6dns1,omitempty" doc:"the first IPv6 DNS for the Zone"` - IP6DNS2 net.IP `json:"ip6dns2,omitempty" doc:"the second IPv6 DNS for the Zone"` - LocalStorageEnabled *bool `json:"localstorageenabled,omitempty" doc:"true if local storage offering enabled, false otherwise"` - Name string `json:"name,omitempty" doc:"Zone name"` - NetworkType string `json:"networktype,omitempty" doc:"the network type of the zone; can be Basic or Advanced"` - ResourceDetails map[string]string `json:"resourcedetails,omitempty" doc:"Meta data associated with the zone (key/value pairs)"` - SecurityGroupsEnabled *bool `json:"securitygroupsenabled,omitempty" doc:"true if security groups support is enabled, false otherwise"` - Tags []ResourceTag `json:"tags,omitempty" doc:"the list of resource tags associated with zone."` - Vlan string `json:"vlan,omitempty" doc:"the vlan range of the zone"` - ZoneToken string `json:"zonetoken,omitempty" doc:"Zone Token"` -} - -// ListRequest builds the ListZones request -func (zone Zone) ListRequest() (ListCommand, error) { - req := &ListZones{ - ID: zone.ID, - Name: zone.Name, - } - - return req, nil -} - -//go:generate go run generate/main.go -interface=Listable ListZones - -// ListZones represents a query for zones -type ListZones struct { - Available *bool `json:"available,omitempty" doc:"true if you want to retrieve all available Zones. False if you only want to return the Zones from which you have at least one VM. Default is false."` - ID *UUID `json:"id,omitempty" doc:"the ID of the zone"` - Keyword string `json:"keyword,omitempty" doc:"List by keyword"` - Name string `json:"name,omitempty" doc:"the name of the zone"` - Page int `json:"page,omitempty"` - PageSize int `json:"pagesize,omitempty"` - ShowCapacities *bool `json:"showcapacities,omitempty" doc:"flag to display the capacity of the zones"` - Tags []ResourceTag `json:"tags,omitempty" doc:"List zones by resource tags (key/value pairs)"` - _ bool `name:"listZones" description:"Lists zones"` -} - -// ListZonesResponse represents a list of zones -type ListZonesResponse struct { - Count int `json:"count"` - Zone []Zone `json:"zone"` -} diff --git a/vendor/github.com/exoscale/egoscale/zones_response.go b/vendor/github.com/exoscale/egoscale/zones_response.go deleted file mode 100644 index 0fe7d06d7..000000000 --- a/vendor/github.com/exoscale/egoscale/zones_response.go +++ /dev/null @@ -1,43 +0,0 @@ -// code generated; DO NOT EDIT. - -package egoscale - -import "fmt" - -// Response returns the struct to unmarshal -func (ListZones) Response() interface{} { - return new(ListZonesResponse) -} - -// ListRequest returns itself -func (ls *ListZones) ListRequest() (ListCommand, error) { - if ls == nil { - return nil, fmt.Errorf("%T cannot be nil", ls) - } - return ls, nil -} - -// SetPage sets the current apge -func (ls *ListZones) SetPage(page int) { - ls.Page = page -} - -// SetPageSize sets the page size -func (ls *ListZones) SetPageSize(pageSize int) { - ls.PageSize = pageSize -} - -// Each triggers the callback for each, valid answer or any non 404 issue -func (ListZones) Each(resp interface{}, callback IterateItemFunc) { - items, ok := resp.(*ListZonesResponse) - if !ok { - callback(nil, fmt.Errorf("wrong type, ListZonesResponse was expected, got %T", resp)) - return - } - - for i := range items.Zone { - if !callback(&items.Zone[i], nil) { - break - } - } -} diff --git a/vendor/github.com/fatih/structs/LICENSE b/vendor/github.com/fatih/structs/LICENSE deleted file mode 100644 index 34504e4b3..000000000 --- a/vendor/github.com/fatih/structs/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Fatih Arslan - -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/fatih/structs/field.go b/vendor/github.com/fatih/structs/field.go deleted file mode 100644 index e69783230..000000000 --- a/vendor/github.com/fatih/structs/field.go +++ /dev/null @@ -1,141 +0,0 @@ -package structs - -import ( - "errors" - "fmt" - "reflect" -) - -var ( - errNotExported = errors.New("field is not exported") - errNotSettable = errors.New("field is not settable") -) - -// Field represents a single struct field that encapsulates high level -// functions around the field. -type Field struct { - value reflect.Value - field reflect.StructField - defaultTag string -} - -// Tag returns the value associated with key in the tag string. If there is no -// such key in the tag, Tag returns the empty string. -func (f *Field) Tag(key string) string { - return f.field.Tag.Get(key) -} - -// Value returns the underlying value of the field. It panics if the field -// is not exported. -func (f *Field) Value() interface{} { - return f.value.Interface() -} - -// IsEmbedded returns true if the given field is an anonymous field (embedded) -func (f *Field) IsEmbedded() bool { - return f.field.Anonymous -} - -// IsExported returns true if the given field is exported. -func (f *Field) IsExported() bool { - return f.field.PkgPath == "" -} - -// IsZero returns true if the given field is not initialized (has a zero value). -// It panics if the field is not exported. -func (f *Field) IsZero() bool { - zero := reflect.Zero(f.value.Type()).Interface() - current := f.Value() - - return reflect.DeepEqual(current, zero) -} - -// Name returns the name of the given field -func (f *Field) Name() string { - return f.field.Name -} - -// Kind returns the fields kind, such as "string", "map", "bool", etc .. -func (f *Field) Kind() reflect.Kind { - return f.value.Kind() -} - -// Set sets the field to given value v. It returns an error if the field is not -// settable (not addressable or not exported) or if the given value's type -// doesn't match the fields type. -func (f *Field) Set(val interface{}) error { - // we can't set unexported fields, so be sure this field is exported - if !f.IsExported() { - return errNotExported - } - - // do we get here? not sure... - if !f.value.CanSet() { - return errNotSettable - } - - given := reflect.ValueOf(val) - - if f.value.Kind() != given.Kind() { - return fmt.Errorf("wrong kind. got: %s want: %s", given.Kind(), f.value.Kind()) - } - - f.value.Set(given) - return nil -} - -// Zero sets the field to its zero value. It returns an error if the field is not -// settable (not addressable or not exported). -func (f *Field) Zero() error { - zero := reflect.Zero(f.value.Type()).Interface() - return f.Set(zero) -} - -// Fields returns a slice of Fields. This is particular handy to get the fields -// of a nested struct . A struct tag with the content of "-" ignores the -// checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field *http.Request `structs:"-"` -// -// It panics if field is not exported or if field's kind is not struct -func (f *Field) Fields() []*Field { - return getFields(f.value, f.defaultTag) -} - -// Field returns the field from a nested struct. It panics if the nested struct -// is not exported or if the field was not found. -func (f *Field) Field(name string) *Field { - field, ok := f.FieldOk(name) - if !ok { - panic("field not found") - } - - return field -} - -// FieldOk returns the field from a nested struct. The boolean returns whether -// the field was found (true) or not (false). -func (f *Field) FieldOk(name string) (*Field, bool) { - value := &f.value - // value must be settable so we need to make sure it holds the address of the - // variable and not a copy, so we can pass the pointer to strctVal instead of a - // copy (which is not assigned to any variable, hence not settable). - // see "https://blog.golang.org/laws-of-reflection#TOC_8." - if f.value.Kind() != reflect.Ptr { - a := f.value.Addr() - value = &a - } - v := strctVal(value.Interface()) - t := v.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: v.FieldByName(name), - }, true -} diff --git a/vendor/github.com/fatih/structs/structs.go b/vendor/github.com/fatih/structs/structs.go deleted file mode 100644 index 3a8770652..000000000 --- a/vendor/github.com/fatih/structs/structs.go +++ /dev/null @@ -1,584 +0,0 @@ -// Package structs contains various utilities functions to work with structs. -package structs - -import ( - "fmt" - - "reflect" -) - -var ( - // DefaultTagName is the default tag name for struct fields which provides - // a more granular to tweak certain structs. Lookup the necessary functions - // for more info. - DefaultTagName = "structs" // struct's field default tag name -) - -// Struct encapsulates a struct type to provide several high level functions -// around the struct. -type Struct struct { - raw interface{} - value reflect.Value - TagName string -} - -// New returns a new *Struct with the struct s. It panics if the s's kind is -// not struct. -func New(s interface{}) *Struct { - return &Struct{ - raw: s, - value: strctVal(s), - TagName: DefaultTagName, - } -} - -// Map converts the given struct to a map[string]interface{}, where the keys -// of the map are the field names and the values of the map the associated -// values of the fields. The default key string is the struct field name but -// can be changed in the struct field's tag value. The "structs" key in the -// struct's field tag value is the key name. Example: -// -// // Field appears in map as key "myName". -// Name string `structs:"myName"` -// -// A tag value with the content of "-" ignores that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A tag value with the content of "string" uses the stringer to get the value. Example: -// -// // The value will be output of Animal's String() func. -// // Map will panic if Animal does not implement String(). -// Field *Animal `structs:"field,string"` -// -// A tag value with the option of "flatten" used in a struct field is to flatten its fields -// in the output map. Example: -// -// // The FieldStruct's fields will be flattened into the output map. -// FieldStruct time.Time `structs:",flatten"` -// -// A tag value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field if -// the field value is empty. Example: -// -// // Field appears in map as key "myName", but the field is -// // skipped if empty. -// Field string `structs:"myName,omitempty"` -// -// // Field appears in map as key "Field" (the default), but -// // the field is skipped if empty. -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Map() map[string]interface{} { - out := make(map[string]interface{}) - s.FillMap(out) - return out -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func (s *Struct) FillMap(out map[string]interface{}) { - if out == nil { - return - } - - fields := s.structFields() - - for _, field := range fields { - name := field.Name - val := s.value.FieldByName(name) - isSubStruct := false - var finalVal interface{} - - tagName, tagOpts := parseTag(field.Tag.Get(s.TagName)) - if tagName != "" { - name = tagName - } - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if !tagOpts.Has("omitnested") { - finalVal = s.nested(val) - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Map, reflect.Struct: - isSubStruct = true - } - } else { - finalVal = val.Interface() - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - out[name] = s.String() - } - continue - } - - if isSubStruct && (tagOpts.Has("flatten")) { - for k := range finalVal.(map[string]interface{}) { - out[k] = finalVal.(map[string]interface{})[k] - } - } else { - out[name] = finalVal - } - } -} - -// Values converts the given s struct's field values to a []interface{}. A -// struct tag with the content of "-" ignores the that particular field. -// Example: -// -// // Field is ignored by this package. -// Field int `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Fields is not processed further by this package. -// Field time.Time `structs:",omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// A tag value with the option of "omitempty" ignores that particular field and -// is not added to the values if the field value is empty. Example: -// -// // Field is skipped if empty -// Field string `structs:",omitempty"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. -func (s *Struct) Values() []interface{} { - fields := s.structFields() - - var t []interface{} - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - // if the value is a zero value and the field is marked as omitempty do - // not include - if tagOpts.Has("omitempty") { - zero := reflect.Zero(val.Type()).Interface() - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - continue - } - } - - if tagOpts.Has("string") { - s, ok := val.Interface().(fmt.Stringer) - if ok { - t = append(t, s.String()) - } - continue - } - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - // look out for embedded structs, and convert them to a - // []interface{} to be added to the final values slice - t = append(t, Values(val.Interface())...) - } else { - t = append(t, val.Interface()) - } - } - - return t -} - -// Fields returns a slice of Fields. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Fields() []*Field { - return getFields(s.value, s.TagName) -} - -// Names returns a slice of field names. A struct tag with the content of "-" -// ignores the checking of that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// It panics if s's kind is not struct. -func (s *Struct) Names() []string { - fields := getFields(s.value, s.TagName) - - names := make([]string, len(fields)) - - for i, field := range fields { - names[i] = field.Name() - } - - return names -} - -func getFields(v reflect.Value, tagName string) []*Field { - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - t := v.Type() - - var fields []*Field - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - - if tag := field.Tag.Get(tagName); tag == "-" { - continue - } - - f := &Field{ - field: field, - value: v.FieldByName(field.Name), - } - - fields = append(fields, f) - - } - - return fields -} - -// Field returns a new Field struct that provides several high level functions -// around a single struct field entity. It panics if the field is not found. -func (s *Struct) Field(name string) *Field { - f, ok := s.FieldOk(name) - if !ok { - panic("field not found") - } - - return f -} - -// FieldOk returns a new Field struct that provides several high level functions -// around a single struct field entity. The boolean returns true if the field -// was found. -func (s *Struct) FieldOk(name string) (*Field, bool) { - t := s.value.Type() - - field, ok := t.FieldByName(name) - if !ok { - return nil, false - } - - return &Field{ - field: field, - value: s.value.FieldByName(name), - defaultTag: s.TagName, - }, true -} - -// IsZero returns true if all fields in a struct is a zero value (not -// initialized) A struct tag with the content of "-" ignores the checking of -// that particular field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) IsZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := IsZero(val.Interface()) - if !ok { - return false - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if !reflect.DeepEqual(current, zero) { - return false - } - } - - return true -} - -// HasZero returns true if a field in a struct is not initialized (zero value). -// A struct tag with the content of "-" ignores the checking of that particular -// field. Example: -// -// // Field is ignored by this package. -// Field bool `structs:"-"` -// -// A value with the option of "omitnested" stops iterating further if the type -// is a struct. Example: -// -// // Field is not processed further by this package. -// Field time.Time `structs:"myName,omitnested"` -// Field *http.Request `structs:",omitnested"` -// -// Note that only exported fields of a struct can be accessed, non exported -// fields will be neglected. It panics if s's kind is not struct. -func (s *Struct) HasZero() bool { - fields := s.structFields() - - for _, field := range fields { - val := s.value.FieldByName(field.Name) - - _, tagOpts := parseTag(field.Tag.Get(s.TagName)) - - if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { - ok := HasZero(val.Interface()) - if ok { - return true - } - - continue - } - - // zero value of the given field, such as "" for string, 0 for int - zero := reflect.Zero(val.Type()).Interface() - - // current value of the given field - current := val.Interface() - - if reflect.DeepEqual(current, zero) { - return true - } - } - - return false -} - -// Name returns the structs's type name within its package. For more info refer -// to Name() function. -func (s *Struct) Name() string { - return s.value.Type().Name() -} - -// structFields returns the exported struct fields for a given s struct. This -// is a convenient helper method to avoid duplicate code in some of the -// functions. -func (s *Struct) structFields() []reflect.StructField { - t := s.value.Type() - - var f []reflect.StructField - - for i := 0; i < t.NumField(); i++ { - field := t.Field(i) - // we can't access the value of unexported fields - if field.PkgPath != "" { - continue - } - - // don't check if it's omitted - if tag := field.Tag.Get(s.TagName); tag == "-" { - continue - } - - f = append(f, field) - } - - return f -} - -func strctVal(s interface{}) reflect.Value { - v := reflect.ValueOf(s) - - // if pointer get the underlying element≤ - for v.Kind() == reflect.Ptr { - v = v.Elem() - } - - if v.Kind() != reflect.Struct { - panic("not struct") - } - - return v -} - -// Map converts the given struct to a map[string]interface{}. For more info -// refer to Struct types Map() method. It panics if s's kind is not struct. -func Map(s interface{}) map[string]interface{} { - return New(s).Map() -} - -// FillMap is the same as Map. Instead of returning the output, it fills the -// given map. -func FillMap(s interface{}, out map[string]interface{}) { - New(s).FillMap(out) -} - -// Values converts the given struct to a []interface{}. For more info refer to -// Struct types Values() method. It panics if s's kind is not struct. -func Values(s interface{}) []interface{} { - return New(s).Values() -} - -// Fields returns a slice of *Field. For more info refer to Struct types -// Fields() method. It panics if s's kind is not struct. -func Fields(s interface{}) []*Field { - return New(s).Fields() -} - -// Names returns a slice of field names. For more info refer to Struct types -// Names() method. It panics if s's kind is not struct. -func Names(s interface{}) []string { - return New(s).Names() -} - -// IsZero returns true if all fields is equal to a zero value. For more info -// refer to Struct types IsZero() method. It panics if s's kind is not struct. -func IsZero(s interface{}) bool { - return New(s).IsZero() -} - -// HasZero returns true if any field is equal to a zero value. For more info -// refer to Struct types HasZero() method. It panics if s's kind is not struct. -func HasZero(s interface{}) bool { - return New(s).HasZero() -} - -// IsStruct returns true if the given variable is a struct or a pointer to -// struct. -func IsStruct(s interface{}) bool { - v := reflect.ValueOf(s) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - // uninitialized zero value of a struct - if v.Kind() == reflect.Invalid { - return false - } - - return v.Kind() == reflect.Struct -} - -// Name returns the structs's type name within its package. It returns an -// empty string for unnamed types. It panics if s's kind is not struct. -func Name(s interface{}) string { - return New(s).Name() -} - -// nested retrieves recursively all types for the given value and returns the -// nested value. -func (s *Struct) nested(val reflect.Value) interface{} { - var finalVal interface{} - - v := reflect.ValueOf(val.Interface()) - if v.Kind() == reflect.Ptr { - v = v.Elem() - } - - switch v.Kind() { - case reflect.Struct: - n := New(val.Interface()) - n.TagName = s.TagName - m := n.Map() - - // do not add the converted value if there are no exported fields, ie: - // time.Time - if len(m) == 0 { - finalVal = val.Interface() - } else { - finalVal = m - } - case reflect.Map: - // get the element type of the map - mapElem := val.Type() - switch val.Type().Kind() { - case reflect.Ptr, reflect.Array, reflect.Map, - reflect.Slice, reflect.Chan: - mapElem = val.Type().Elem() - if mapElem.Kind() == reflect.Ptr { - mapElem = mapElem.Elem() - } - } - - // only iterate over struct types, ie: map[string]StructType, - // map[string][]StructType, - if mapElem.Kind() == reflect.Struct || - (mapElem.Kind() == reflect.Slice && - mapElem.Elem().Kind() == reflect.Struct) { - m := make(map[string]interface{}, val.Len()) - for _, k := range val.MapKeys() { - m[k.String()] = s.nested(val.MapIndex(k)) - } - finalVal = m - break - } - - // TODO(arslan): should this be optional? - finalVal = val.Interface() - case reflect.Slice, reflect.Array: - if val.Type().Kind() == reflect.Interface { - finalVal = val.Interface() - break - } - - // TODO(arslan): should this be optional? - // do not iterate of non struct types, just pass the value. Ie: []int, - // []string, co... We only iterate further if it's a struct. - // i.e []foo or []*foo - if val.Type().Elem().Kind() != reflect.Struct && - !(val.Type().Elem().Kind() == reflect.Ptr && - val.Type().Elem().Elem().Kind() == reflect.Struct) { - finalVal = val.Interface() - break - } - - slices := make([]interface{}, val.Len()) - for x := 0; x < val.Len(); x++ { - slices[x] = s.nested(val.Index(x)) - } - finalVal = slices - default: - finalVal = val.Interface() - } - - return finalVal -} diff --git a/vendor/github.com/fatih/structs/tags.go b/vendor/github.com/fatih/structs/tags.go deleted file mode 100644 index 136a31eba..000000000 --- a/vendor/github.com/fatih/structs/tags.go +++ /dev/null @@ -1,32 +0,0 @@ -package structs - -import "strings" - -// tagOptions contains a slice of tag options -type tagOptions []string - -// Has returns true if the given option is available in tagOptions -func (t tagOptions) Has(opt string) bool { - for _, tagOpt := range t { - if tagOpt == opt { - return true - } - } - - return false -} - -// parseTag splits a struct field's tag into its name and a list of options -// which comes after a name. A tag is in the form of: "name,option1,option2". -// The name can be neglectected. -func parseTag(tag string) (string, tagOptions) { - // tag is one of followings: - // "" - // "name" - // "name,opt" - // "name,opt,opt2" - // ",opt" - - res := strings.Split(tag, ",") - return res[0], res[1:] -} diff --git a/vendor/github.com/flynn/go-shlex/COPYING b/vendor/github.com/flynn/go-shlex/COPYING deleted file mode 100644 index d64569567..000000000 --- a/vendor/github.com/flynn/go-shlex/COPYING +++ /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/flynn/go-shlex/shlex.go b/vendor/github.com/flynn/go-shlex/shlex.go deleted file mode 100644 index 7aeace801..000000000 --- a/vendor/github.com/flynn/go-shlex/shlex.go +++ /dev/null @@ -1,457 +0,0 @@ -/* -Copyright 2012 Google Inc. All Rights Reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package shlex - -/* -Package shlex implements a simple lexer which splits input in to tokens using -shell-style rules for quoting and commenting. -*/ -import ( - "bufio" - "errors" - "fmt" - "io" - "strings" -) - -/* -A TokenType is a top-level token; a word, space, comment, unknown. -*/ -type TokenType int - -/* -A RuneTokenType is the type of a UTF-8 character; a character, quote, space, escape. -*/ -type RuneTokenType int - -type lexerState int - -type Token struct { - tokenType TokenType - value string -} - -/* -Two tokens are equal if both their types and values are equal. A nil token can -never equal another token. -*/ -func (a *Token) Equal(b *Token) bool { - if a == nil || b == nil { - return false - } - if a.tokenType != b.tokenType { - return false - } - return a.value == b.value -} - -const ( - RUNE_CHAR string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-,/@$*()+=><:;&^%~|!?[]{}" - RUNE_SPACE string = " \t\r\n" - RUNE_ESCAPING_QUOTE string = "\"" - RUNE_NONESCAPING_QUOTE string = "'" - RUNE_ESCAPE = "\\" - RUNE_COMMENT = "#" - - RUNETOKEN_UNKNOWN RuneTokenType = 0 - RUNETOKEN_CHAR RuneTokenType = 1 - RUNETOKEN_SPACE RuneTokenType = 2 - RUNETOKEN_ESCAPING_QUOTE RuneTokenType = 3 - RUNETOKEN_NONESCAPING_QUOTE RuneTokenType = 4 - RUNETOKEN_ESCAPE RuneTokenType = 5 - RUNETOKEN_COMMENT RuneTokenType = 6 - RUNETOKEN_EOF RuneTokenType = 7 - - TOKEN_UNKNOWN TokenType = 0 - TOKEN_WORD TokenType = 1 - TOKEN_SPACE TokenType = 2 - TOKEN_COMMENT TokenType = 3 - - STATE_START lexerState = 0 - STATE_INWORD lexerState = 1 - STATE_ESCAPING lexerState = 2 - STATE_ESCAPING_QUOTED lexerState = 3 - STATE_QUOTED_ESCAPING lexerState = 4 - STATE_QUOTED lexerState = 5 - STATE_COMMENT lexerState = 6 - - INITIAL_TOKEN_CAPACITY int = 100 -) - -/* -A type for classifying characters. This allows for different sorts of -classifiers - those accepting extended non-ascii chars, or strict posix -compatibility, for example. -*/ -type TokenClassifier struct { - typeMap map[int32]RuneTokenType -} - -func addRuneClass(typeMap *map[int32]RuneTokenType, runes string, tokenType RuneTokenType) { - for _, rune := range runes { - (*typeMap)[int32(rune)] = tokenType - } -} - -/* -Create a new classifier for basic ASCII characters. -*/ -func NewDefaultClassifier() *TokenClassifier { - typeMap := map[int32]RuneTokenType{} - addRuneClass(&typeMap, RUNE_CHAR, RUNETOKEN_CHAR) - addRuneClass(&typeMap, RUNE_SPACE, RUNETOKEN_SPACE) - addRuneClass(&typeMap, RUNE_ESCAPING_QUOTE, RUNETOKEN_ESCAPING_QUOTE) - addRuneClass(&typeMap, RUNE_NONESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE) - addRuneClass(&typeMap, RUNE_ESCAPE, RUNETOKEN_ESCAPE) - addRuneClass(&typeMap, RUNE_COMMENT, RUNETOKEN_COMMENT) - return &TokenClassifier{ - typeMap: typeMap} -} - -func (classifier *TokenClassifier) ClassifyRune(rune int32) RuneTokenType { - return classifier.typeMap[rune] -} - -/* -A type for turning an input stream in to a sequence of strings. Whitespace and -comments are skipped. -*/ -type Lexer struct { - tokenizer *Tokenizer -} - -/* -Create a new lexer. -*/ -func NewLexer(r io.Reader) (*Lexer, error) { - - tokenizer, err := NewTokenizer(r) - if err != nil { - return nil, err - } - lexer := &Lexer{tokenizer: tokenizer} - return lexer, nil -} - -/* -Return the next word, and an error value. If there are no more words, the error -will be io.EOF. -*/ -func (l *Lexer) NextWord() (string, error) { - var token *Token - var err error - for { - token, err = l.tokenizer.NextToken() - if err != nil { - return "", err - } - switch token.tokenType { - case TOKEN_WORD: - { - return token.value, nil - } - case TOKEN_COMMENT: - { - // skip comments - } - default: - { - panic(fmt.Sprintf("Unknown token type: %v", token.tokenType)) - } - } - } - return "", io.EOF -} - -/* -A type for turning an input stream in to a sequence of typed tokens. -*/ -type Tokenizer struct { - input *bufio.Reader - classifier *TokenClassifier -} - -/* -Create a new tokenizer. -*/ -func NewTokenizer(r io.Reader) (*Tokenizer, error) { - input := bufio.NewReader(r) - classifier := NewDefaultClassifier() - tokenizer := &Tokenizer{ - input: input, - classifier: classifier} - return tokenizer, nil -} - -/* -Scan the stream for the next token. - -This uses an internal state machine. It will panic if it encounters a character -which it does not know how to handle. -*/ -func (t *Tokenizer) scanStream() (*Token, error) { - state := STATE_START - var tokenType TokenType - value := make([]int32, 0, INITIAL_TOKEN_CAPACITY) - var ( - nextRune int32 - nextRuneType RuneTokenType - err error - ) -SCAN: - for { - nextRune, _, err = t.input.ReadRune() - nextRuneType = t.classifier.ClassifyRune(nextRune) - if err != nil { - if err == io.EOF { - nextRuneType = RUNETOKEN_EOF - err = nil - } else { - return nil, err - } - } - switch state { - case STATE_START: // no runes read yet - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - return nil, io.EOF - } - case RUNETOKEN_CHAR: - { - tokenType = TOKEN_WORD - value = append(value, nextRune) - state = STATE_INWORD - } - case RUNETOKEN_SPACE: - { - } - case RUNETOKEN_ESCAPING_QUOTE: - { - tokenType = TOKEN_WORD - state = STATE_QUOTED_ESCAPING - } - case RUNETOKEN_NONESCAPING_QUOTE: - { - tokenType = TOKEN_WORD - state = STATE_QUOTED - } - case RUNETOKEN_ESCAPE: - { - tokenType = TOKEN_WORD - state = STATE_ESCAPING - } - case RUNETOKEN_COMMENT: - { - tokenType = TOKEN_COMMENT - state = STATE_COMMENT - } - default: - { - return nil, errors.New(fmt.Sprintf("Unknown rune: %v", nextRune)) - } - } - } - case STATE_INWORD: // in a regular word - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_COMMENT: - { - value = append(value, nextRune) - } - case RUNETOKEN_SPACE: - { - t.input.UnreadRune() - break SCAN - } - case RUNETOKEN_ESCAPING_QUOTE: - { - state = STATE_QUOTED_ESCAPING - } - case RUNETOKEN_NONESCAPING_QUOTE: - { - state = STATE_QUOTED - } - case RUNETOKEN_ESCAPE: - { - state = STATE_ESCAPING - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - case STATE_ESCAPING: // the next rune after an escape character - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - err = errors.New("EOF found after escape character") - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: - { - state = STATE_INWORD - value = append(value, nextRune) - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - case STATE_ESCAPING_QUOTED: // the next rune after an escape character, in double quotes - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - err = errors.New("EOF found after escape character") - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: - { - state = STATE_QUOTED_ESCAPING - value = append(value, nextRune) - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - case STATE_QUOTED_ESCAPING: // in escaping double quotes - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - err = errors.New("EOF found when expecting closing quote.") - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_NONESCAPING_QUOTE, RUNETOKEN_COMMENT: - { - value = append(value, nextRune) - } - case RUNETOKEN_ESCAPING_QUOTE: - { - state = STATE_INWORD - } - case RUNETOKEN_ESCAPE: - { - state = STATE_ESCAPING_QUOTED - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - case STATE_QUOTED: // in non-escaping single quotes - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - err = errors.New("EOF found when expecting closing quote.") - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_SPACE, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT: - { - value = append(value, nextRune) - } - case RUNETOKEN_NONESCAPING_QUOTE: - { - state = STATE_INWORD - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - case STATE_COMMENT: - { - switch nextRuneType { - case RUNETOKEN_EOF: - { - break SCAN - } - case RUNETOKEN_CHAR, RUNETOKEN_UNKNOWN, RUNETOKEN_ESCAPING_QUOTE, RUNETOKEN_ESCAPE, RUNETOKEN_COMMENT, RUNETOKEN_NONESCAPING_QUOTE: - { - value = append(value, nextRune) - } - case RUNETOKEN_SPACE: - { - if nextRune == '\n' { - state = STATE_START - break SCAN - } else { - value = append(value, nextRune) - } - } - default: - { - return nil, errors.New(fmt.Sprintf("Uknown rune: %v", nextRune)) - } - } - } - default: - { - panic(fmt.Sprintf("Unexpected state: %v", state)) - } - } - } - token := &Token{ - tokenType: tokenType, - value: string(value)} - return token, err -} - -/* -Return the next token in the stream, and an error value. If there are no more -tokens available, the error value will be io.EOF. -*/ -func (t *Tokenizer) NextToken() (*Token, error) { - return t.scanStream() -} - -/* -Split a string in to a slice of strings, based upon shell-style rules for -quoting, escaping, and spaces. -*/ -func Split(s string) ([]string, error) { - l, err := NewLexer(strings.NewReader(s)) - if err != nil { - return nil, err - } - subStrings := []string{} - for { - word, err := l.NextWord() - if err != nil { - if err == io.EOF { - return subStrings, nil - } - return subStrings, err - } - subStrings = append(subStrings, word) - } - return subStrings, nil -} diff --git a/vendor/github.com/gambol99/go-marathon/LICENSE b/vendor/github.com/gambol99/go-marathon/LICENSE deleted file mode 100644 index 5e0fd33cb..000000000 --- a/vendor/github.com/gambol99/go-marathon/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/gambol99/go-marathon/application.go b/vendor/github.com/gambol99/go-marathon/application.go deleted file mode 100644 index 958781f49..000000000 --- a/vendor/github.com/gambol99/go-marathon/application.go +++ /dev/null @@ -1,985 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "errors" - "fmt" - "net/url" - "time" -) - -var ( - // ErrNoApplicationContainer is thrown when a container has been specified yet - ErrNoApplicationContainer = errors.New("you have not specified a docker container yet") -) - -// Applications is a collection of applications -type Applications struct { - Apps []Application `json:"apps"` -} - -// IPAddressPerTask is used by IP-per-task functionality https://mesosphere.github.io/marathon/docs/ip-per-task.html -type IPAddressPerTask struct { - Groups *[]string `json:"groups,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - Discovery *Discovery `json:"discovery,omitempty"` - NetworkName string `json:"networkName,omitempty"` -} - -// Discovery provides info about ports expose by IP-per-task functionality -type Discovery struct { - Ports *[]Port `json:"ports,omitempty"` -} - -// Port provides info about ports used by IP-per-task -type Port struct { - Number int `json:"number,omitempty"` - Name string `json:"name,omitempty"` - Protocol string `json:"protocol,omitempty"` -} - -// Application is the definition for an application in marathon -type Application struct { - ID string `json:"id,omitempty"` - Cmd *string `json:"cmd,omitempty"` - Args *[]string `json:"args,omitempty"` - Constraints *[][]string `json:"constraints,omitempty"` - Container *Container `json:"container,omitempty"` - CPUs float64 `json:"cpus,omitempty"` - GPUs *float64 `json:"gpus,omitempty"` - Disk *float64 `json:"disk,omitempty"` - Networks *[]PodNetwork `json:"networks,omitempty"` - - // Contains non-secret environment variables. Secrets environment variables are part of the Secrets map. - Env *map[string]string `json:"-"` - Executor *string `json:"executor,omitempty"` - HealthChecks *[]HealthCheck `json:"healthChecks,omitempty"` - ReadinessChecks *[]ReadinessCheck `json:"readinessChecks,omitempty"` - Instances *int `json:"instances,omitempty"` - Mem *float64 `json:"mem,omitempty"` - Tasks []*Task `json:"tasks,omitempty"` - Ports []int `json:"ports"` - PortDefinitions *[]PortDefinition `json:"portDefinitions,omitempty"` - RequirePorts *bool `json:"requirePorts,omitempty"` - BackoffSeconds *float64 `json:"backoffSeconds,omitempty"` - BackoffFactor *float64 `json:"backoffFactor,omitempty"` - MaxLaunchDelaySeconds *float64 `json:"maxLaunchDelaySeconds,omitempty"` - TaskKillGracePeriodSeconds *float64 `json:"taskKillGracePeriodSeconds,omitempty"` - Deployments []map[string]string `json:"deployments,omitempty"` - // Available when embedding readiness information through query parameter. - ReadinessCheckResults *[]ReadinessCheckResult `json:"readinessCheckResults,omitempty"` - Dependencies []string `json:"dependencies"` - TasksRunning int `json:"tasksRunning,omitempty"` - TasksStaged int `json:"tasksStaged,omitempty"` - TasksHealthy int `json:"tasksHealthy,omitempty"` - TasksUnhealthy int `json:"tasksUnhealthy,omitempty"` - TaskStats map[string]TaskStats `json:"taskStats,omitempty"` - User string `json:"user,omitempty"` - UpgradeStrategy *UpgradeStrategy `json:"upgradeStrategy,omitempty"` - UnreachableStrategy *UnreachableStrategy `json:"unreachableStrategy,omitempty"` - KillSelection string `json:"killSelection,omitempty"` - Uris *[]string `json:"uris,omitempty"` - Version string `json:"version,omitempty"` - VersionInfo *VersionInfo `json:"versionInfo,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` - AcceptedResourceRoles []string `json:"acceptedResourceRoles,omitempty"` - LastTaskFailure *LastTaskFailure `json:"lastTaskFailure,omitempty"` - Fetch *[]Fetch `json:"fetch,omitempty"` - IPAddressPerTask *IPAddressPerTask `json:"ipAddress,omitempty"` - Residency *Residency `json:"residency,omitempty"` - Secrets *map[string]Secret `json:"-"` -} - -// ApplicationVersions is a collection of application versions for a specific app in marathon -type ApplicationVersions struct { - Versions []string `json:"versions"` -} - -// ApplicationVersion is the application version response from marathon -type ApplicationVersion struct { - Version string `json:"version"` -} - -// VersionInfo is the application versioning details from marathon -type VersionInfo struct { - LastScalingAt string `json:"lastScalingAt,omitempty"` - LastConfigChangeAt string `json:"lastConfigChangeAt,omitempty"` -} - -// Fetch will download URI before task starts -type Fetch struct { - URI string `json:"uri"` - Executable bool `json:"executable"` - Extract bool `json:"extract"` - Cache bool `json:"cache"` -} - -// GetAppOpts contains a payload for Application method -// embed: Embeds nested resources that match the supplied path. -// You can specify this parameter multiple times with different values -type GetAppOpts struct { - Embed []string `url:"embed,omitempty"` -} - -// DeleteAppOpts contains a payload for DeleteApplication method -// force: overrides a currently running deployment. -type DeleteAppOpts struct { - Force bool `url:"force,omitempty"` -} - -// TaskStats is a container for Stats -type TaskStats struct { - Stats Stats `json:"stats"` -} - -// Stats is a collection of aggregate statistics about an application's tasks -type Stats struct { - Counts map[string]int `json:"counts"` - LifeTime map[string]float64 `json:"lifeTime"` -} - -// Secret is the environment variable and secret store path associated with a secret. -// The value for EnvVar is populated from the env field, and Source is populated from -// the secrets field of the application json. -type Secret struct { - EnvVar string - Source string -} - -// SetIPAddressPerTask defines that the application will have a IP address defines by a external agent. -// This configuration is not allowed to be used with Port or PortDefinitions. Thus, the implementation -// clears both. -func (r *Application) SetIPAddressPerTask(ipAddressPerTask IPAddressPerTask) *Application { - r.Ports = make([]int, 0) - r.EmptyPortDefinitions() - r.IPAddressPerTask = &ipAddressPerTask - - return r -} - -// NewDockerApplication creates a default docker application -func NewDockerApplication() *Application { - application := new(Application) - application.Container = NewDockerContainer() - return application -} - -// Name sets the name / ID of the application i.e. the identifier for this application -func (r *Application) Name(id string) *Application { - r.ID = validateID(id) - return r -} - -// Command sets the cmd of the application -func (r *Application) Command(cmd string) *Application { - r.Cmd = &cmd - return r -} - -// CPU set the amount of CPU shares per instance which is assigned to the application -// cpu: the CPU shared (check Docker docs) per instance -func (r *Application) CPU(cpu float64) *Application { - r.CPUs = cpu - return r -} - -// SetGPUs set the amount of GPU per instance which is assigned to the application -// gpu: the GPU (check MESOS docs) per instance -func (r *Application) SetGPUs(gpu float64) *Application { - r.GPUs = &gpu - return r -} - -// EmptyGPUs explicitly empties GPUs -- use this if you need to empty -// gpus of an application that already has gpus set (setting port definitions to nil will -// keep the current value) -func (r *Application) EmptyGPUs() *Application { - g := 0.0 - r.GPUs = &g - return r -} - -// Storage sets the amount of disk space the application is assigned, which for docker -// application I don't believe is relevant -// disk: the disk space in MB -func (r *Application) Storage(disk float64) *Application { - r.Disk = &disk - return r -} - -// AllTaskRunning checks to see if all the application tasks are running, i.e. the instances is equal -// to the number of running tasks -func (r *Application) AllTaskRunning() bool { - if r.Instances == nil || *r.Instances == 0 { - return true - } - if r.Tasks == nil { - return false - } - if r.TasksRunning == *r.Instances { - return true - } - return false -} - -// DependsOn adds one or more dependencies for this application. Note, if you want to wait for -// an application dependency to actually be UP, i.e. not just deployed, you need a health check -// on the dependant app. -// names: the application id(s) this application depends on -func (r *Application) DependsOn(names ...string) *Application { - if r.Dependencies == nil { - r.Dependencies = make([]string, 0) - } - r.Dependencies = append(r.Dependencies, names...) - - return r -} - -// Memory sets he amount of memory the application can consume per instance -// memory: the amount of MB to assign -func (r *Application) Memory(memory float64) *Application { - r.Mem = &memory - - return r -} - -// AddPortDefinition adds a port definition. Port definitions are used to define ports that -// should be considered part of a resource. They are necessary when you are using HOST -// networking and no port mappings are specified. -func (r *Application) AddPortDefinition(portDefinition PortDefinition) *Application { - if r.PortDefinitions == nil { - r.EmptyPortDefinitions() - } - - portDefinitions := *r.PortDefinitions - portDefinitions = append(portDefinitions, portDefinition) - r.PortDefinitions = &portDefinitions - return r -} - -// EmptyPortDefinitions explicitly empties port definitions -- use this if you need to empty -// port definitions of an application that already has port definitions set (setting port definitions to nil will -// keep the current value) -func (r *Application) EmptyPortDefinitions() *Application { - r.PortDefinitions = &[]PortDefinition{} - - return r -} - -// Count sets the number of instances of the application to run -// count: the number of instances to run -func (r *Application) Count(count int) *Application { - r.Instances = &count - - return r -} - -// SetTaskKillGracePeriod sets the number of seconds between escalating from SIGTERM to SIGKILL -// when signalling tasks to terminate. Using this grace period, tasks should perform orderly shut down -// immediately upon receiving SIGTERM. -// seconds: the number of seconds -func (r *Application) SetTaskKillGracePeriod(seconds float64) *Application { - r.TaskKillGracePeriodSeconds = &seconds - - return r -} - -// AddArgs adds one or more arguments to the applications -// arguments: the argument(s) you are adding -func (r *Application) AddArgs(arguments ...string) *Application { - if r.Args == nil { - r.EmptyArgs() - } - - args := *r.Args - args = append(args, arguments...) - r.Args = &args - - return r -} - -// EmptyArgs explicitly empties arguments -- use this if you need to empty -// arguments of an application that already has arguments set (setting args to nil will -// keep the current value) -func (r *Application) EmptyArgs() *Application { - r.Args = &[]string{} - - return r -} - -// AddConstraint adds a new constraint -// constraints: the constraint definition, one constraint per array element -func (r *Application) AddConstraint(constraints ...string) *Application { - if r.Constraints == nil { - r.EmptyConstraints() - } - - c := *r.Constraints - c = append(c, constraints) - r.Constraints = &c - - return r -} - -// EmptyConstraints explicitly empties constraints -- use this if you need to empty -// constraints of an application that already has constraints set (setting constraints to nil will -// keep the current value) -func (r *Application) EmptyConstraints() *Application { - r.Constraints = &[][]string{} - - return r -} - -// AddLabel adds a label to the application -// name: the name of the label -// value: value for this label -func (r *Application) AddLabel(name, value string) *Application { - if r.Labels == nil { - r.EmptyLabels() - } - (*r.Labels)[name] = value - - return r -} - -// EmptyLabels explicitly empties the labels -- use this if you need to empty -// the labels of an application that already has labels set (setting labels to nil will -// keep the current value) -func (r *Application) EmptyLabels() *Application { - r.Labels = &map[string]string{} - - return r -} - -// AddEnv adds an environment variable to the application -// name: the name of the variable -// value: go figure, the value associated to the above -func (r *Application) AddEnv(name, value string) *Application { - if r.Env == nil { - r.EmptyEnvs() - } - (*r.Env)[name] = value - - return r -} - -// EmptyEnvs explicitly empties the envs -- use this if you need to empty -// the environments of an application that already has environments set (setting env to nil will -// keep the current value) -func (r *Application) EmptyEnvs() *Application { - r.Env = &map[string]string{} - - return r -} - -// AddSecret adds a secret declaration -// envVar: the name of the environment variable -// name: the name of the secret -// source: the source ID of the secret -func (r *Application) AddSecret(envVar, name, source string) *Application { - if r.Secrets == nil { - r.EmptySecrets() - } - (*r.Secrets)[name] = Secret{EnvVar: envVar, Source: source} - - return r -} - -// EmptySecrets explicitly empties the secrets -- use this if you need to empty -// the secrets of an application that already has secrets set (setting secrets to nil will -// keep the current value) -func (r *Application) EmptySecrets() *Application { - r.Secrets = &map[string]Secret{} - - return r -} - -// SetExecutor sets the executor -func (r *Application) SetExecutor(executor string) *Application { - r.Executor = &executor - - return r -} - -// AddHealthCheck adds a health check -// healthCheck the health check that should be added -func (r *Application) AddHealthCheck(healthCheck HealthCheck) *Application { - if r.HealthChecks == nil { - r.EmptyHealthChecks() - } - - healthChecks := *r.HealthChecks - healthChecks = append(healthChecks, healthCheck) - r.HealthChecks = &healthChecks - - return r -} - -// EmptyHealthChecks explicitly empties health checks -- use this if you need to empty -// health checks of an application that already has health checks set (setting health checks to nil will -// keep the current value) -func (r *Application) EmptyHealthChecks() *Application { - r.HealthChecks = &[]HealthCheck{} - - return r -} - -// HasHealthChecks is a helper method, used to check if an application has health checks -func (r *Application) HasHealthChecks() bool { - return r.HealthChecks != nil && len(*r.HealthChecks) > 0 -} - -// AddReadinessCheck adds a readiness check. -func (r *Application) AddReadinessCheck(readinessCheck ReadinessCheck) *Application { - if r.ReadinessChecks == nil { - r.EmptyReadinessChecks() - } - - readinessChecks := *r.ReadinessChecks - readinessChecks = append(readinessChecks, readinessCheck) - r.ReadinessChecks = &readinessChecks - - return r -} - -// EmptyReadinessChecks empties the readiness checks. -func (r *Application) EmptyReadinessChecks() *Application { - r.ReadinessChecks = &[]ReadinessCheck{} - - return r -} - -// DeploymentIDs retrieves the application deployments IDs -func (r *Application) DeploymentIDs() []*DeploymentID { - var deployments []*DeploymentID - - if r.Deployments == nil { - return deployments - } - - // step: extract the deployment id from the result - for _, deploy := range r.Deployments { - if id, found := deploy["id"]; found { - deployment := &DeploymentID{ - Version: r.Version, - DeploymentID: id, - } - deployments = append(deployments, deployment) - } - } - - return deployments -} - -// CheckHTTP adds a HTTP check to an application -// port: the port the check should be checking -// interval: the interval in seconds the check should be performed -func (r *Application) CheckHTTP(path string, port, interval int) (*Application, error) { - if r.Container == nil || r.Container.Docker == nil { - return nil, ErrNoApplicationContainer - } - // step: get the port index - portIndex, err := r.Container.Docker.ServicePortIndex(port) - if err != nil { - portIndex, err = r.Container.ServicePortIndex(port) - if err != nil { - return nil, err - } - } - health := NewDefaultHealthCheck() - health.IntervalSeconds = interval - *health.Path = path - *health.PortIndex = portIndex - // step: add to the checks - r.AddHealthCheck(*health) - - return r, nil -} - -// CheckTCP adds a TCP check to an application; note the port mapping must already exist, or an -// error will thrown -// port: the port the check should, err, check -// interval: the interval in seconds the check should be performed -func (r *Application) CheckTCP(port, interval int) (*Application, error) { - if r.Container == nil || r.Container.Docker == nil { - return nil, ErrNoApplicationContainer - } - // step: get the port index - portIndex, err := r.Container.Docker.ServicePortIndex(port) - if err != nil { - portIndex, err = r.Container.ServicePortIndex(port) - if err != nil { - return nil, err - } - } - health := NewDefaultHealthCheck() - health.Protocol = "TCP" - health.IntervalSeconds = interval - *health.PortIndex = portIndex - // step: add to the checks - r.AddHealthCheck(*health) - - return r, nil -} - -// AddUris adds one or more uris to the applications -// arguments: the uri(s) you are adding -func (r *Application) AddUris(newUris ...string) *Application { - if r.Uris == nil { - r.EmptyUris() - } - - uris := *r.Uris - uris = append(uris, newUris...) - r.Uris = &uris - - return r -} - -// EmptyUris explicitly empties uris -- use this if you need to empty -// uris of an application that already has uris set (setting uris to nil will -// keep the current value) -func (r *Application) EmptyUris() *Application { - r.Uris = &[]string{} - - return r -} - -// AddFetchURIs adds one or more fetch URIs to the application. -// fetchURIs: the fetch URI(s) to add. -func (r *Application) AddFetchURIs(fetchURIs ...Fetch) *Application { - if r.Fetch == nil { - r.EmptyFetchURIs() - } - - fetch := *r.Fetch - fetch = append(fetch, fetchURIs...) - r.Fetch = &fetch - - return r -} - -// EmptyFetchURIs explicitly empties fetch URIs -- use this if you need to empty -// fetch URIs of an application that already has fetch URIs set. -// Setting fetch URIs to nil will keep the current value. -func (r *Application) EmptyFetchURIs() *Application { - r.Fetch = &[]Fetch{} - - return r -} - -// SetUpgradeStrategy sets the upgrade strategy. -func (r *Application) SetUpgradeStrategy(us UpgradeStrategy) *Application { - r.UpgradeStrategy = &us - return r -} - -// EmptyUpgradeStrategy explicitly empties the upgrade strategy -- use this if -// you need to empty the upgrade strategy of an application that already has -// the upgrade strategy set (setting it to nil will keep the current value). -func (r *Application) EmptyUpgradeStrategy() *Application { - r.UpgradeStrategy = &UpgradeStrategy{} - return r -} - -// SetUnreachableStrategy sets the unreachable strategy. -func (r *Application) SetUnreachableStrategy(us UnreachableStrategy) *Application { - r.UnreachableStrategy = &us - return r -} - -// EmptyUnreachableStrategy explicitly empties the unreachable strategy -- use this if -// you need to empty the unreachable strategy of an application that already has -// the unreachable strategy set (setting it to nil will keep the current value). -func (r *Application) EmptyUnreachableStrategy() *Application { - r.UnreachableStrategy = &UnreachableStrategy{} - return r -} - -// SetResidency sets behavior for resident applications, an application is resident when -// it has local persistent volumes set -func (r *Application) SetResidency(whenLost TaskLostBehaviorType) *Application { - r.Residency = &Residency{ - TaskLostBehavior: whenLost, - } - return r -} - -// EmptyResidency explicitly empties the residency -- use this if -// you need to empty the residency of an application that already has -// the residency set (setting it to nil will keep the current value). -func (r *Application) EmptyResidency() *Application { - r.Residency = &Residency{} - return r -} - -// String returns the json representation of this application -func (r *Application) String() string { - s, err := json.MarshalIndent(r, "", " ") - if err != nil { - return fmt.Sprintf(`{"error": "error decoding type into json: %s"}`, err) - } - - return string(s) -} - -// Applications retrieves an array of all the applications which are running in marathon -func (r *marathonClient) Applications(v url.Values) (*Applications, error) { - query := v.Encode() - if query != "" { - query = "?" + query - } - - applications := new(Applications) - err := r.apiGet(marathonAPIApps+query, nil, applications) - if err != nil { - return nil, err - } - - return applications, nil -} - -// ListApplications retrieves an array of the application names currently running in marathon -func (r *marathonClient) ListApplications(v url.Values) ([]string, error) { - applications, err := r.Applications(v) - if err != nil { - return nil, err - } - var list []string - for _, application := range applications.Apps { - list = append(list, application.ID) - } - - return list, nil -} - -// HasApplicationVersion checks to see if the application version exists in Marathon -// name: the id used to identify the application -// version: the version (normally a timestamp) your looking for -func (r *marathonClient) HasApplicationVersion(name, version string) (bool, error) { - id := trimRootPath(name) - versions, err := r.ApplicationVersions(id) - if err != nil { - return false, err - } - - return contains(versions.Versions, version), nil -} - -// ApplicationVersions is a list of versions which has been deployed with marathon for a specific application -// name: the id used to identify the application -func (r *marathonClient) ApplicationVersions(name string) (*ApplicationVersions, error) { - path := fmt.Sprintf("%s/versions", buildPath(name)) - versions := new(ApplicationVersions) - if err := r.apiGet(path, nil, versions); err != nil { - return nil, err - } - return versions, nil -} - -// SetApplicationVersion changes the version of the application -// name: the id used to identify the application -// version: the version (normally a timestamp) you wish to change to -func (r *marathonClient) SetApplicationVersion(name string, version *ApplicationVersion) (*DeploymentID, error) { - path := buildPath(name) - deploymentID := new(DeploymentID) - if err := r.apiPut(path, version, deploymentID); err != nil { - return nil, err - } - - return deploymentID, nil -} - -// Application retrieves the application configuration from marathon -// name: the id used to identify the application -func (r *marathonClient) Application(name string) (*Application, error) { - var wrapper struct { - Application *Application `json:"app"` - } - - if err := r.apiGet(buildPath(name), nil, &wrapper); err != nil { - return nil, err - } - - return wrapper.Application, nil -} - -// ApplicationBy retrieves the application configuration from marathon -// name: the id used to identify the application -// opts: GetAppOpts request payload -func (r *marathonClient) ApplicationBy(name string, opts *GetAppOpts) (*Application, error) { - path, err := addOptions(buildPath(name), opts) - if err != nil { - return nil, err - } - var wrapper struct { - Application *Application `json:"app"` - } - - if err := r.apiGet(path, nil, &wrapper); err != nil { - return nil, err - } - - return wrapper.Application, nil -} - -// ApplicationByVersion retrieves the application configuration from marathon -// name: the id used to identify the application -// version: the version of the configuration you would like to receive -func (r *marathonClient) ApplicationByVersion(name, version string) (*Application, error) { - app := new(Application) - - path := fmt.Sprintf("%s/versions/%s", buildPath(name), version) - if err := r.apiGet(path, nil, app); err != nil { - return nil, err - } - - return app, nil -} - -// ApplicationOK validates that the application, or more appropriately it's tasks have passed all the health checks. -// If no health checks exist, we simply return true -// name: the id used to identify the application -func (r *marathonClient) ApplicationOK(name string) (bool, error) { - // step: get the application - application, err := r.Application(name) - if err != nil { - return false, err - } - - // step: check if all the tasks are running? - if !application.AllTaskRunning() { - return false, nil - } - - // step: if the application has not health checks, just return true - if application.HealthChecks == nil || len(*application.HealthChecks) == 0 { - return true, nil - } - - // step: iterate the application checks and look for false - for _, task := range application.Tasks { - // Health check results may not be available immediately. Assume - // non-healthiness if they are missing for any task. - if task.HealthCheckResults == nil { - return false, nil - } - - for _, check := range task.HealthCheckResults { - //When a task is flapping in Marathon, this is sometimes nil - if check == nil || !check.Alive { - return false, nil - } - } - } - - return true, nil -} - -// ApplicationDeployments retrieves an array of Deployment IDs for an application -// name: the id used to identify the application -func (r *marathonClient) ApplicationDeployments(name string) ([]*DeploymentID, error) { - application, err := r.Application(name) - if err != nil { - return nil, err - } - - return application.DeploymentIDs(), nil -} - -// CreateApplication creates a new application in Marathon -// application: the structure holding the application configuration -func (r *marathonClient) CreateApplication(application *Application) (*Application, error) { - result := new(Application) - if err := r.apiPost(marathonAPIApps, application, result); err != nil { - return nil, err - } - - return result, nil -} - -// WaitOnApplication waits for an application to be deployed -// name: the id of the application -// timeout: a duration of time to wait for an application to deploy -func (r *marathonClient) WaitOnApplication(name string, timeout time.Duration) error { - return r.wait(name, timeout, r.appExistAndRunning) -} - -func (r *marathonClient) appExistAndRunning(name string) bool { - app, err := r.Application(name) - if apiErr, ok := err.(*APIError); ok && apiErr.ErrCode == ErrCodeNotFound { - return false - } - if err == nil && app.AllTaskRunning() { - return true - } - return false -} - -// DeleteApplication deletes an application from marathon -// name: the id used to identify the application -// force: used to force the delete operation in case of blocked deployment -func (r *marathonClient) DeleteApplication(name string, force bool) (*DeploymentID, error) { - path := buildPathWithForceParam(name, force) - // step: check of the application already exists - deployID := new(DeploymentID) - if err := r.apiDelete(path, nil, deployID); err != nil { - return nil, err - } - - return deployID, nil -} - -// RestartApplication performs a rolling restart of marathon application -// name: the id used to identify the application -func (r *marathonClient) RestartApplication(name string, force bool) (*DeploymentID, error) { - deployment := new(DeploymentID) - var options struct{} - path := buildPathWithForceParam(fmt.Sprintf("%s/restart", name), force) - if err := r.apiPost(path, &options, deployment); err != nil { - return nil, err - } - - return deployment, nil -} - -// ScaleApplicationInstances changes the number of instance an application is running -// name: the id used to identify the application -// instances: the number of instances you wish to change to -// force: used to force the scale operation in case of blocked deployment -func (r *marathonClient) ScaleApplicationInstances(name string, instances int, force bool) (*DeploymentID, error) { - changes := new(Application) - changes.ID = validateID(name) - changes.Instances = &instances - path := buildPathWithForceParam(name, force) - deployID := new(DeploymentID) - if err := r.apiPut(path, changes, deployID); err != nil { - return nil, err - } - - return deployID, nil -} - -// UpdateApplication updates an application in Marathon -// application: the structure holding the application configuration -func (r *marathonClient) UpdateApplication(application *Application, force bool) (*DeploymentID, error) { - result := new(DeploymentID) - path := buildPathWithForceParam(application.ID, force) - if err := r.apiPut(path, application, result); err != nil { - return nil, err - } - return result, nil -} - -func buildPathWithForceParam(rootPath string, force bool) string { - path := buildPath(rootPath) - if force { - path += "?force=true" - } - return path -} - -func buildPath(path string) string { - return fmt.Sprintf("%s/%s", marathonAPIApps, trimRootPath(path)) -} - -// EmptyLabels explicitly empties labels -- use this if you need to empty -// labels of an application that already has IP per task with labels defined -func (i *IPAddressPerTask) EmptyLabels() *IPAddressPerTask { - i.Labels = &map[string]string{} - return i -} - -// AddLabel adds a label to an IPAddressPerTask -// name: The label name -// value: The label value -func (i *IPAddressPerTask) AddLabel(name, value string) *IPAddressPerTask { - if i.Labels == nil { - i.EmptyLabels() - } - (*i.Labels)[name] = value - return i -} - -// EmptyGroups explicitly empties groups -- use this if you need to empty -// groups of an application that already has IP per task with groups defined -func (i *IPAddressPerTask) EmptyGroups() *IPAddressPerTask { - i.Groups = &[]string{} - return i -} - -// AddGroup adds a group to an IPAddressPerTask -// group: The group name -func (i *IPAddressPerTask) AddGroup(group string) *IPAddressPerTask { - if i.Groups == nil { - i.EmptyGroups() - } - - groups := *i.Groups - groups = append(groups, group) - i.Groups = &groups - - return i -} - -// SetDiscovery define the discovery to an IPAddressPerTask -// discovery: The discovery struct -func (i *IPAddressPerTask) SetDiscovery(discovery Discovery) *IPAddressPerTask { - i.Discovery = &discovery - return i -} - -// EmptyPorts explicitly empties discovey port -- use this if you need to empty -// discovey port of an application that already has IP per task with discovey ports -// defined -func (d *Discovery) EmptyPorts() *Discovery { - d.Ports = &[]Port{} - return d -} - -// AddPort adds a port to the discovery info of a IP per task applicable -// port: The discovery port -func (d *Discovery) AddPort(port Port) *Discovery { - if d.Ports == nil { - d.EmptyPorts() - } - ports := *d.Ports - ports = append(ports, port) - d.Ports = &ports - return d -} - -// EmptyNetworks explicitly empties networks -func (r *Application) EmptyNetworks() *Application { - r.Networks = &[]PodNetwork{} - return r -} - -// SetNetwork sets the networking mode -func (r *Application) SetNetwork(name string, mode PodNetworkMode) *Application { - if r.Networks == nil { - r.EmptyNetworks() - } - - network := PodNetwork{Name: name, Mode: mode} - networks := *r.Networks - networks = append(networks, network) - r.Networks = &networks - return r -} diff --git a/vendor/github.com/gambol99/go-marathon/application_marshalling.go b/vendor/github.com/gambol99/go-marathon/application_marshalling.go deleted file mode 100644 index 8bedd9e96..000000000 --- a/vendor/github.com/gambol99/go-marathon/application_marshalling.go +++ /dev/null @@ -1,106 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" -) - -// Alias aliases the Application struct so that it will be marshaled/unmarshaled automatically -type Alias Application - -// TmpEnvSecret holds the secret values deserialized from the environment variables field -type TmpEnvSecret struct { - Secret string `json:"secret,omitempty"` -} - -// TmpSecret holds the deserialized secrets field in a Marathon application configuration -type TmpSecret struct { - Source string `json:"source,omitempty"` -} - -// UnmarshalJSON unmarshals the given Application JSON as expected except for environment variables and secrets. -// Environment varialbes are stored in the Env field. Secrets, including the environment variable part, -// are stored in the Secrets field. -func (app *Application) UnmarshalJSON(b []byte) error { - aux := &struct { - *Alias - Env map[string]interface{} `json:"env"` - Secrets map[string]TmpSecret `json:"secrets"` - }{ - Alias: (*Alias)(app), - } - if err := json.Unmarshal(b, aux); err != nil { - return fmt.Errorf("malformed application definition %v", err) - } - env := &map[string]string{} - secrets := &map[string]Secret{} - - for envName, genericEnvValue := range aux.Env { - switch envValOrSecret := genericEnvValue.(type) { - case string: - (*env)[envName] = envValOrSecret - case map[string]interface{}: - for secret, secretStore := range envValOrSecret { - if secStore, ok := secretStore.(string); ok && secret == "secret" { - (*secrets)[secStore] = Secret{EnvVar: envName} - break - } - return fmt.Errorf("unexpected secret field %v of value type %T", secret, envValOrSecret[secret]) - } - default: - return fmt.Errorf("unexpected environment variable type %T", envValOrSecret) - } - } - app.Env = env - for k, v := range aux.Secrets { - tmp := (*secrets)[k] - tmp.Source = v.Source - (*secrets)[k] = tmp - } - app.Secrets = secrets - return nil -} - -// MarshalJSON marshals the given Application as expected except for environment variables and secrets, -// which are marshaled from specialized structs. The environment variable piece of the secrets and other -// normal environment variables are combined and marshaled to the env field. The secrets and the related -// source are marshaled into the secrets field. -func (app *Application) MarshalJSON() ([]byte, error) { - env := make(map[string]interface{}) - secrets := make(map[string]TmpSecret) - - if app.Env != nil { - for k, v := range *app.Env { - env[string(k)] = string(v) - } - } - if app.Secrets != nil { - for k, v := range *app.Secrets { - env[v.EnvVar] = TmpEnvSecret{Secret: k} - secrets[k] = TmpSecret{v.Source} - } - } - aux := &struct { - *Alias - Env map[string]interface{} `json:"env,omitempty"` - Secrets map[string]TmpSecret `json:"secrets,omitempty"` - }{Alias: (*Alias)(app), Env: env, Secrets: secrets} - - return json.Marshal(aux) -} diff --git a/vendor/github.com/gambol99/go-marathon/client.go b/vendor/github.com/gambol99/go-marathon/client.go deleted file mode 100644 index 00736a4b2..000000000 --- a/vendor/github.com/gambol99/go-marathon/client.go +++ /dev/null @@ -1,494 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "log" - "net" - "net/http" - "net/url" - "regexp" - "strings" - "sync" - "time" -) - -// Marathon is the interface to the marathon API -type Marathon interface { - // -- APPLICATIONS --- - - // get a listing of the application ids - ListApplications(url.Values) ([]string, error) - // a list of application versions - ApplicationVersions(name string) (*ApplicationVersions, error) - // check a application version exists - HasApplicationVersion(name, version string) (bool, error) - // change an application to a different version - SetApplicationVersion(name string, version *ApplicationVersion) (*DeploymentID, error) - // check if an application is ok - ApplicationOK(name string) (bool, error) - // create an application in marathon - CreateApplication(application *Application) (*Application, error) - // delete an application - DeleteApplication(name string, force bool) (*DeploymentID, error) - // update an application in marathon - UpdateApplication(application *Application, force bool) (*DeploymentID, error) - // a list of deployments on a application - ApplicationDeployments(name string) ([]*DeploymentID, error) - // scale a application - ScaleApplicationInstances(name string, instances int, force bool) (*DeploymentID, error) - // restart an application - RestartApplication(name string, force bool) (*DeploymentID, error) - // get a list of applications from marathon - Applications(url.Values) (*Applications, error) - // get an application by name - Application(name string) (*Application, error) - // get an application by options - ApplicationBy(name string, opts *GetAppOpts) (*Application, error) - // get an application by name and version - ApplicationByVersion(name, version string) (*Application, error) - // wait of application - WaitOnApplication(name string, timeout time.Duration) error - - // -- PODS --- - // whether this version of Marathon supports pods - SupportsPods() (bool, error) - - // get pod status - PodStatus(name string) (*PodStatus, error) - // get all pod statuses - PodStatuses() ([]*PodStatus, error) - - // get pod - Pod(name string) (*Pod, error) - // get all pods - Pods() ([]Pod, error) - // create pod - CreatePod(pod *Pod) (*Pod, error) - // update pod - UpdatePod(pod *Pod, force bool) (*Pod, error) - // delete pod - DeletePod(name string, force bool) (*DeploymentID, error) - // wait on pod to be deployed - WaitOnPod(name string, timeout time.Duration) error - // check if a pod is running - PodIsRunning(name string) bool - - // get versions of a pod - PodVersions(name string) ([]string, error) - // get pod by version - PodByVersion(name, version string) (*Pod, error) - - // delete instances of a pod - DeletePodInstances(name string, instances []string) ([]*PodInstance, error) - // delete pod instance - DeletePodInstance(name, instance string) (*PodInstance, error) - - // -- TASKS --- - - // get a list of tasks for a specific application - Tasks(application string) (*Tasks, error) - // get a list of all tasks - AllTasks(opts *AllTasksOpts) (*Tasks, error) - // get the endpoints for a service on a application - TaskEndpoints(name string, port int, healthCheck bool) ([]string, error) - // kill all the tasks for any application - KillApplicationTasks(applicationID string, opts *KillApplicationTasksOpts) (*Tasks, error) - // kill a single task - KillTask(taskID string, opts *KillTaskOpts) (*Task, error) - // kill the given array of tasks - KillTasks(taskIDs []string, opts *KillTaskOpts) error - - // --- GROUPS --- - - // list all the groups in the system - Groups() (*Groups, error) - // retrieve a specific group from marathon - Group(name string) (*Group, error) - // list all groups in marathon by options - GroupsBy(opts *GetGroupOpts) (*Groups, error) - // retrieve a specific group from marathon by options - GroupBy(name string, opts *GetGroupOpts) (*Group, error) - // create a group deployment - CreateGroup(group *Group) error - // delete a group - DeleteGroup(name string, force bool) (*DeploymentID, error) - // update a groups - UpdateGroup(id string, group *Group, force bool) (*DeploymentID, error) - // check if a group exists - HasGroup(name string) (bool, error) - // wait for an group to be deployed - WaitOnGroup(name string, timeout time.Duration) error - - // --- DEPLOYMENTS --- - - // get a list of the deployments - Deployments() ([]*Deployment, error) - // delete a deployment - DeleteDeployment(id string, force bool) (*DeploymentID, error) - // check to see if a deployment exists - HasDeployment(id string) (bool, error) - // wait of a deployment to finish - WaitOnDeployment(id string, timeout time.Duration) error - - // --- SUBSCRIPTIONS --- - - // a list of current subscriptions - Subscriptions() (*Subscriptions, error) - // add a events listener - AddEventsListener(filter int) (EventsChannel, error) - // remove a events listener - RemoveEventsListener(channel EventsChannel) - // Subscribe a callback URL - Subscribe(string) error - // Unsubscribe a callback URL - Unsubscribe(string) error - - // --- QUEUE --- - // get marathon launch queue - Queue() (*Queue, error) - // resets task launch delay of the specific application - DeleteQueueDelay(appID string) error - - // --- MISC --- - - // get the marathon url - GetMarathonURL() string - // ping the marathon - Ping() (bool, error) - // grab the marathon server info - Info() (*Info, error) - // retrieve the leader info - Leader() (string, error) - // cause the current leader to abdicate - AbdicateLeader() (string, error) -} - -var ( - // ErrMarathonDown is thrown when all the marathon endpoints are down - ErrMarathonDown = errors.New("all the Marathon hosts are presently down") - // ErrTimeoutError is thrown when the operation has timed out - ErrTimeoutError = errors.New("the operation has timed out") - - // Default HTTP client used for SSE subscription requests - // It is invalid to set client.Timeout because it includes time to read response so - // set dial, tls handshake and response header timeouts instead - defaultHTTPSSEClient = &http.Client{ - Transport: &http.Transport{ - Dial: (&net.Dialer{ - Timeout: 5 * time.Second, - }).Dial, - ResponseHeaderTimeout: 10 * time.Second, - TLSHandshakeTimeout: 5 * time.Second, - }, - } - - // Default HTTP client used for non SSE requests - defaultHTTPClient = &http.Client{ - Timeout: 10 * time.Second, - } -) - -// EventsChannelContext holds contextual data for an EventsChannel. -type EventsChannelContext struct { - filter int - done chan struct{} - completion *sync.WaitGroup -} - -type marathonClient struct { - sync.RWMutex - // the configuration for the client - config Config - // the flag used to prevent multiple SSE subscriptions - subscribedToSSE bool - // the ip address of the client - ipAddress string - // the http server - eventsHTTP *http.Server - // the marathon hosts - hosts *cluster - // a map of service you wish to listen to - listeners map[EventsChannel]EventsChannelContext - // a custom log function for debug messages - debugLog func(format string, v ...interface{}) - // the marathon HTTP client to ensure consistency in requests - client *httpClient -} - -type httpClient struct { - // the configuration for the marathon HTTP client - config Config -} - -// newRequestError signals that creating a new http.Request failed -type newRequestError struct { - error -} - -// NewClient creates a new marathon client -// config: the configuration to use -func NewClient(config Config) (Marathon, error) { - // step: if the SSE HTTP client is missing, prefer a configured regular - // client, and otherwise use the default SSE HTTP client. - if config.HTTPSSEClient == nil { - config.HTTPSSEClient = defaultHTTPSSEClient - if config.HTTPClient != nil { - config.HTTPSSEClient = config.HTTPClient - } - } - - // step: if a regular HTTP client is missing, use the default one. - if config.HTTPClient == nil { - config.HTTPClient = defaultHTTPClient - } - - // step: if no polling wait time is set, default to 500 milliseconds. - if config.PollingWaitTime == 0 { - config.PollingWaitTime = defaultPollingWaitTime - } - - // step: setup shared client - client := &httpClient{config: config} - - // step: create a new cluster - hosts, err := newCluster(client, config.URL, config.DCOSToken != "") - if err != nil { - return nil, err - } - - debugLog := func(string, ...interface{}) {} - if config.LogOutput != nil { - logger := log.New(config.LogOutput, "", 0) - debugLog = func(format string, v ...interface{}) { - logger.Printf(format, v...) - } - } - - return &marathonClient{ - config: config, - listeners: make(map[EventsChannel]EventsChannelContext), - hosts: hosts, - debugLog: debugLog, - client: client, - }, nil -} - -// GetMarathonURL retrieves the marathon url -func (r *marathonClient) GetMarathonURL() string { - return r.config.URL -} - -// Ping pings the current marathon endpoint (note, this is not a ICMP ping, but a rest api call) -func (r *marathonClient) Ping() (bool, error) { - if err := r.apiGet(marathonAPIPing, nil, nil); err != nil { - return false, err - } - return true, nil -} - -func (r *marathonClient) apiHead(path string, result interface{}) error { - return r.apiCall("HEAD", path, nil, result) -} - -func (r *marathonClient) apiGet(path string, post, result interface{}) error { - return r.apiCall("GET", path, post, result) -} - -func (r *marathonClient) apiPut(path string, post, result interface{}) error { - return r.apiCall("PUT", path, post, result) -} - -func (r *marathonClient) apiPost(path string, post, result interface{}) error { - return r.apiCall("POST", path, post, result) -} - -func (r *marathonClient) apiDelete(path string, post, result interface{}) error { - return r.apiCall("DELETE", path, post, result) -} - -func (r *marathonClient) apiCall(method, path string, body, result interface{}) error { - const deploymentHeader = "Marathon-Deployment-Id" - - for { - // step: marshall the request to json - var requestBody []byte - var err error - if body != nil { - if requestBody, err = json.Marshal(body); err != nil { - return err - } - } - - // step: create the API request - request, member, err := r.buildAPIRequest(method, path, bytes.NewReader(requestBody)) - if err != nil { - return err - } - - // step: perform the API request - response, err := r.client.Do(request) - if err != nil { - r.hosts.markDown(member) - // step: attempt the request on another member - r.debugLog("apiCall(): request failed on host: %s, error: %s, trying another", member, err) - continue - } - defer response.Body.Close() - - // step: read the response body - respBody, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - if len(requestBody) > 0 { - r.debugLog("apiCall(): %v %v %s returned %v %s", request.Method, request.URL.String(), requestBody, response.Status, oneLogLine(respBody)) - } else { - r.debugLog("apiCall(): %v %v returned %v %s", request.Method, request.URL.String(), response.Status, oneLogLine(respBody)) - } - - // step: check for a successful response - if response.StatusCode >= 200 && response.StatusCode <= 299 { - if result != nil { - // If we have a deployment ID header and no response body, give them that - // This specifically handles the use case of a DELETE on an app/pod - // We need a way to retrieve the deployment ID - deploymentID := response.Header.Get(deploymentHeader) - if len(respBody) == 0 && deploymentID != "" { - d := DeploymentID{ - DeploymentID: deploymentID, - } - if deployID, ok := result.(*DeploymentID); ok { - *deployID = d - } - } else { - if err := json.Unmarshal(respBody, result); err != nil { - return fmt.Errorf("failed to unmarshal response from Marathon: %s", err) - } - } - } - return nil - } - - // step: if the member node returns a >= 500 && <= 599 we should try another node? - if response.StatusCode >= 500 && response.StatusCode <= 599 { - // step: mark the host as down - r.hosts.markDown(member) - r.debugLog("apiCall(): request failed, host: %s, status: %d, trying another", member, response.StatusCode) - continue - } - - return NewAPIError(response.StatusCode, respBody) - } -} - -// wait waits until the provided function returns true (or times out) -func (r *marathonClient) wait(name string, timeout time.Duration, fn func(string) bool) error { - timer := time.NewTimer(timeout) - defer timer.Stop() - - ticker := time.NewTicker(r.config.PollingWaitTime) - defer ticker.Stop() - for { - if fn(name) { - return nil - } - - select { - case <-timer.C: - return ErrTimeoutError - case <-ticker.C: - continue - } - } -} - -// buildAPIRequest creates a default API request. -// It fails when there is no available member in the cluster anymore or when the request can not be built. -func (r *marathonClient) buildAPIRequest(method, path string, reader io.Reader) (request *http.Request, member string, err error) { - // Grab a member from the cluster - member, err = r.hosts.getMember() - if err != nil { - return nil, "", ErrMarathonDown - } - - // Build the HTTP request to Marathon - request, err = r.client.buildMarathonJSONRequest(method, member, path, reader) - if err != nil { - return nil, member, newRequestError{err} - } - return request, member, nil -} - -// buildMarathonJSONRequest is like buildMarathonRequest but sets the -// Content-Type and Accept headers to application/json. -func (rc *httpClient) buildMarathonJSONRequest(method, member, path string, reader io.Reader) (request *http.Request, err error) { - req, err := rc.buildMarathonRequest(method, member, path, reader) - if err == nil { - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - } - - return req, err -} - -// buildMarathonRequest creates a new HTTP request and configures it according to the *httpClient configuration. -// The path must not contain a leading "/", otherwise buildMarathonRequest will panic. -func (rc *httpClient) buildMarathonRequest(method, member, path string, reader io.Reader) (request *http.Request, err error) { - if strings.HasPrefix(path, "/") { - panic(fmt.Sprintf("Path '%s' must not start with a leading slash", path)) - } - - // Create the endpoint URL - url := fmt.Sprintf("%s/%s", member, path) - - // Instantiate an HTTP request - request, err = http.NewRequest(method, url, reader) - if err != nil { - return nil, err - } - - // Add any basic auth and the content headers - if rc.config.HTTPBasicAuthUser != "" && rc.config.HTTPBasicPassword != "" { - request.SetBasicAuth(rc.config.HTTPBasicAuthUser, rc.config.HTTPBasicPassword) - } - - if rc.config.DCOSToken != "" { - request.Header.Add("Authorization", "token="+rc.config.DCOSToken) - } - - return request, nil -} - -func (rc *httpClient) Do(request *http.Request) (response *http.Response, err error) { - return rc.config.HTTPClient.Do(request) -} - -var oneLogLineRegex = regexp.MustCompile(`(?m)^\s*`) - -// oneLogLine removes indentation at the beginning of each line and -// escapes new line characters. -func oneLogLine(in []byte) []byte { - return bytes.Replace(oneLogLineRegex.ReplaceAll(in, nil), []byte("\n"), []byte("\\n "), -1) -} diff --git a/vendor/github.com/gambol99/go-marathon/cluster.go b/vendor/github.com/gambol99/go-marathon/cluster.go deleted file mode 100644 index 3ca99b2c4..000000000 --- a/vendor/github.com/gambol99/go-marathon/cluster.go +++ /dev/null @@ -1,191 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" - "net/url" - "strings" - "sync" - "time" -) - -const ( - memberStatusUp = 0 - memberStatusDown = 1 -) - -// the status of a member node -type memberStatus int - -// cluster is a collection of marathon nodes -type cluster struct { - sync.RWMutex - // a collection of nodes - members []*member - // the marathon HTTP client to ensure consistency in requests - client *httpClient - // healthCheckInterval is the interval by which we probe down nodes for - // availability again. - healthCheckInterval time.Duration -} - -// member represents an individual endpoint -type member struct { - // the name / ip address of the host - endpoint string - // the status of the host - status memberStatus -} - -// newCluster returns a new marathon cluster -func newCluster(client *httpClient, marathonURL string, isDCOS bool) (*cluster, error) { - // step: extract and basic validate the endpoints - var members []*member - var defaultProto string - - for _, endpoint := range strings.Split(marathonURL, ",") { - // step: check for nothing - if endpoint == "" { - return nil, newInvalidEndpointError("endpoint is blank") - } - // step: prepend scheme if missing on (non-initial) endpoint. - if !strings.HasPrefix(endpoint, "http://") && !strings.HasPrefix(endpoint, "https://") { - if defaultProto == "" { - return nil, newInvalidEndpointError("missing scheme on (first) endpoint") - } - - endpoint = fmt.Sprintf("%s://%s", defaultProto, endpoint) - } - // step: parse the url - u, err := url.Parse(endpoint) - if err != nil { - return nil, newInvalidEndpointError("invalid endpoint '%s': %s", endpoint, err) - } - if defaultProto == "" { - defaultProto = u.Scheme - } - - // step: check for empty hosts - if u.Host == "" { - return nil, newInvalidEndpointError("endpoint: %s must have a host", endpoint) - } - - // step: if DCOS is set and no path is given, set the default DCOS path. - // done in order to maintain compatibility with automatic addition of the - // default DCOS path. - if isDCOS && strings.TrimLeft(u.Path, "/") == "" { - u.Path = defaultDCOSPath - } - - // step: create a new node for this endpoint - members = append(members, &member{endpoint: u.String()}) - } - - return &cluster{ - client: client, - members: members, - healthCheckInterval: 5 * time.Second, - }, nil -} - -// retrieve the current member, i.e. the current endpoint in use -func (c *cluster) getMember() (string, error) { - c.RLock() - defer c.RUnlock() - for _, n := range c.members { - if n.status == memberStatusUp { - return n.endpoint, nil - } - } - - return "", ErrMarathonDown -} - -// markDown marks down the current endpoint -func (c *cluster) markDown(endpoint string) { - c.Lock() - defer c.Unlock() - for _, n := range c.members { - // step: check if this is the node and it's marked as up - The double checking on the - // nodes status ensures the multiple calls don't create multiple checks - if n.status == memberStatusUp && n.endpoint == endpoint { - n.status = memberStatusDown - go c.healthCheckNode(n) - break - } - } -} - -// healthCheckNode performs a health check on the node and when active updates the status -func (c *cluster) healthCheckNode(node *member) { - // step: wait for the node to become active ... we are assuming a /ping is enough here - ticker := time.NewTicker(c.healthCheckInterval) - defer ticker.Stop() - for range ticker.C { - req, err := c.client.buildMarathonRequest("GET", node.endpoint, "ping", nil) - if err == nil { - res, err := c.client.Do(req) - if err == nil && res.StatusCode == 200 { - // step: mark the node as active again - c.Lock() - node.status = memberStatusUp - c.Unlock() - break - } - } - } -} - -// activeMembers returns a list of active members -func (c *cluster) activeMembers() []string { - return c.membersList(memberStatusUp) -} - -// nonActiveMembers returns a list of non-active members in the cluster -func (c *cluster) nonActiveMembers() []string { - return c.membersList(memberStatusDown) -} - -// memberList returns a list of members of a specified status -func (c *cluster) membersList(status memberStatus) []string { - c.RLock() - defer c.RUnlock() - var list []string - for _, m := range c.members { - if m.status == status { - list = append(list, m.endpoint) - } - } - - return list -} - -// size returns the size of the cluster -func (c *cluster) size() int { - return len(c.members) -} - -// String returns a string representation -func (m member) String() string { - status := "UP" - if m.status == memberStatusDown { - status = "DOWN" - } - - return fmt.Sprintf("member: %s:%s", m.endpoint, status) -} diff --git a/vendor/github.com/gambol99/go-marathon/config.go b/vendor/github.com/gambol99/go-marathon/config.go deleted file mode 100644 index 2e110cc81..000000000 --- a/vendor/github.com/gambol99/go-marathon/config.go +++ /dev/null @@ -1,71 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "io" - "io/ioutil" - "net/http" - "time" -) - -const defaultPollingWaitTime = 500 * time.Millisecond - -const defaultDCOSPath = "marathon" - -// EventsTransport describes which transport should be used to deliver Marathon events -type EventsTransport int - -// Config holds the settings and options for the client -type Config struct { - // URL is the url for marathon - URL string - // EventsTransport is the events transport: EventsTransportCallback or EventsTransportSSE - EventsTransport EventsTransport - // EventsPort is the event handler port - EventsPort int - // the interface we should be listening on for events - EventsInterface string - // HTTPBasicAuthUser is the http basic auth - HTTPBasicAuthUser string - // HTTPBasicPassword is the http basic password - HTTPBasicPassword string - // CallbackURL custom callback url - CallbackURL string - // DCOSToken for DCOS environment, This will override the Authorization header - DCOSToken string - // LogOutput the output for debug log messages - LogOutput io.Writer - // HTTPClient is the HTTP client - HTTPClient *http.Client - // HTTPSSEClient is the HTTP client used for SSE subscriptions, can't have client.Timeout set - HTTPSSEClient *http.Client - // wait time (in milliseconds) between repetitive requests to the API during polling - PollingWaitTime time.Duration -} - -// NewDefaultConfig create a default client config -func NewDefaultConfig() Config { - return Config{ - URL: "http://127.0.0.1:8080", - EventsTransport: EventsTransportCallback, - EventsPort: 10001, - EventsInterface: "eth0", - LogOutput: ioutil.Discard, - PollingWaitTime: defaultPollingWaitTime, - } -} diff --git a/vendor/github.com/gambol99/go-marathon/const.go b/vendor/github.com/gambol99/go-marathon/const.go deleted file mode 100644 index ba8d9b865..000000000 --- a/vendor/github.com/gambol99/go-marathon/const.go +++ /dev/null @@ -1,43 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -const ( - defaultEventsURL = "/event" - - /* --- api related constants --- */ - marathonAPIVersion = "v2" - marathonAPIEventStream = marathonAPIVersion + "/events" - marathonAPISubscription = marathonAPIVersion + "/eventSubscriptions" - marathonAPIApps = marathonAPIVersion + "/apps" - marathonAPIPods = marathonAPIVersion + "/pods" - marathonAPITasks = marathonAPIVersion + "/tasks" - marathonAPIDeployments = marathonAPIVersion + "/deployments" - marathonAPIGroups = marathonAPIVersion + "/groups" - marathonAPIQueue = marathonAPIVersion + "/queue" - marathonAPIInfo = marathonAPIVersion + "/info" - marathonAPILeader = marathonAPIVersion + "/leader" - marathonAPIPing = "ping" -) - -const ( - // EventsTransportCallback activates callback events transport - EventsTransportCallback EventsTransport = 1 << iota - - // EventsTransportSSE activates stream events transport - EventsTransportSSE -) diff --git a/vendor/github.com/gambol99/go-marathon/deployment.go b/vendor/github.com/gambol99/go-marathon/deployment.go deleted file mode 100644 index fc8480de9..000000000 --- a/vendor/github.com/gambol99/go-marathon/deployment.go +++ /dev/null @@ -1,174 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" - "time" -) - -// Deployment is a marathon deployment definition -type Deployment struct { - ID string `json:"id"` - Version string `json:"version"` - CurrentStep int `json:"currentStep"` - TotalSteps int `json:"totalSteps"` - AffectedApps []string `json:"affectedApps"` - AffectedPods []string `json:"affectedPods"` - Steps [][]*DeploymentStep `json:"-"` - XXStepsRaw json.RawMessage `json:"steps"` // Holds raw steps JSON to unmarshal later - CurrentActions []*DeploymentStep `json:"currentActions"` -} - -// DeploymentID is the identifier for a application deployment -type DeploymentID struct { - DeploymentID string `json:"deploymentId"` - Version string `json:"version"` -} - -// DeploymentStep is a step in the application deployment plan -type DeploymentStep struct { - Action string `json:"action"` - App string `json:"app"` - ReadinessCheckResults *[]ReadinessCheckResult `json:"readinessCheckResults,omitempty"` -} - -// StepActions is a series of deployment steps -type StepActions struct { - Actions []struct { - Action string `json:"action"` // 1.1.2 and after - Type string `json:"type"` // 1.1.1 and before - App string `json:"app"` - } -} - -// DeploymentPlan is a collection of steps for application deployment -type DeploymentPlan struct { - ID string `json:"id"` - Version string `json:"version"` - Original *Group `json:"original"` - Target *Group `json:"target"` - Steps []*StepActions `json:"steps"` -} - -// Deployments retrieves a list of current deployments -func (r *marathonClient) Deployments() ([]*Deployment, error) { - var deployments []*Deployment - err := r.apiGet(marathonAPIDeployments, nil, &deployments) - if err != nil { - return nil, err - } - // Allows loading of deployment steps from the Marathon v1.X API - // Implements a fix for issue https://github.com/gambol99/go-marathon/issues/153 - for _, deployment := range deployments { - // Unmarshal pre-v1.X step - if err := json.Unmarshal(deployment.XXStepsRaw, &deployment.Steps); err != nil { - deployment.Steps = make([][]*DeploymentStep, 0) - var steps []*StepActions - // Unmarshal v1.X Marathon step - if err := json.Unmarshal(deployment.XXStepsRaw, &steps); err != nil { - return nil, err - } - for stepIndex, step := range steps { - deployment.Steps = append(deployment.Steps, make([]*DeploymentStep, len(step.Actions))) - for actionIndex, action := range step.Actions { - var stepAction string - if action.Type != "" { - stepAction = action.Type - } else { - stepAction = action.Action - } - deployment.Steps[stepIndex][actionIndex] = &DeploymentStep{ - Action: stepAction, - App: action.App, - } - } - } - } - } - return deployments, nil -} - -// DeleteDeployment delete a current deployment from marathon -// id: the deployment id you wish to delete -// force: whether or not to force the deletion -func (r *marathonClient) DeleteDeployment(id string, force bool) (*DeploymentID, error) { - path := fmt.Sprintf("%s/%s", marathonAPIDeployments, id) - - // if force=true, no body is returned - if force { - path += "?force=true" - return nil, r.apiDelete(path, nil, nil) - } - - deployment := new(DeploymentID) - err := r.apiDelete(path, nil, deployment) - - if err != nil { - return nil, err - } - - return deployment, nil -} - -// HasDeployment checks to see if a deployment exists -// id: the deployment id you are looking for -func (r *marathonClient) HasDeployment(id string) (bool, error) { - deployments, err := r.Deployments() - if err != nil { - return false, err - } - for _, deployment := range deployments { - if deployment.ID == id { - return true, nil - } - } - return false, nil -} - -// WaitOnDeployment waits on a deployment to finish -// version: the version of the application -// timeout: the timeout to wait for the deployment to take, otherwise return an error -func (r *marathonClient) WaitOnDeployment(id string, timeout time.Duration) error { - if found, err := r.HasDeployment(id); err != nil { - return err - } else if !found { - return nil - } - - nowTime := time.Now() - stopTime := nowTime.Add(timeout) - if timeout <= 0 { - stopTime = nowTime.Add(time.Duration(900) * time.Second) - } - - // step: a somewhat naive implementation, but it will work - for { - if time.Now().After(stopTime) { - return ErrTimeoutError - } - found, err := r.HasDeployment(id) - if err != nil { - return err - } - if !found { - return nil - } - time.Sleep(r.config.PollingWaitTime) - } -} diff --git a/vendor/github.com/gambol99/go-marathon/docker.go b/vendor/github.com/gambol99/go-marathon/docker.go deleted file mode 100644 index 20bc1b761..000000000 --- a/vendor/github.com/gambol99/go-marathon/docker.go +++ /dev/null @@ -1,459 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "errors" - "fmt" -) - -// Container is the definition for a container type in marathon -type Container struct { - Type string `json:"type,omitempty"` - Docker *Docker `json:"docker,omitempty"` - Volumes *[]Volume `json:"volumes,omitempty"` - PortMappings *[]PortMapping `json:"portMappings,omitempty"` -} - -// PortMapping is the portmapping structure between container and mesos -type PortMapping struct { - ContainerPort int `json:"containerPort,omitempty"` - HostPort int `json:"hostPort"` - Labels *map[string]string `json:"labels,omitempty"` - Name string `json:"name,omitempty"` - ServicePort int `json:"servicePort,omitempty"` - Protocol string `json:"protocol,omitempty"` - NetworkNames *[]string `json:"networkNames,omitempty"` -} - -// Parameters is the parameters to pass to the docker client when creating the container -type Parameters struct { - Key string `json:"key,omitempty"` - Value string `json:"value,omitempty"` -} - -// Volume is the docker volume details associated to the container -type Volume struct { - ContainerPath string `json:"containerPath,omitempty"` - HostPath string `json:"hostPath,omitempty"` - External *ExternalVolume `json:"external,omitempty"` - Mode string `json:"mode,omitempty"` - Persistent *PersistentVolume `json:"persistent,omitempty"` -} - -// PersistentVolumeType is the a persistent docker volume to be mounted -type PersistentVolumeType string - -const ( - // PersistentVolumeTypeRoot is the root path of the persistent volume - PersistentVolumeTypeRoot PersistentVolumeType = "root" - // PersistentVolumeTypePath is the mount path of the persistent volume - PersistentVolumeTypePath PersistentVolumeType = "path" - // PersistentVolumeTypeMount is the mount type of the persistent volume - PersistentVolumeTypeMount PersistentVolumeType = "mount" -) - -// PersistentVolume declares a Volume to be Persistent, and sets -// the size (in MiB) and optional type, max size (MiB) and constraints for the Volume. -type PersistentVolume struct { - Type PersistentVolumeType `json:"type,omitempty"` - Size int `json:"size"` - MaxSize int `json:"maxSize,omitempty"` - Constraints *[][]string `json:"constraints,omitempty"` -} - -// SetType sets the type of mesos disk resource to use -// type: PersistentVolumeType enum -func (p *PersistentVolume) SetType(tp PersistentVolumeType) *PersistentVolume { - p.Type = tp - return p -} - -// SetSize sets size of the persistent volume -// size: size in MiB -func (p *PersistentVolume) SetSize(size int) *PersistentVolume { - p.Size = size - return p -} - -// SetMaxSize sets maximum size of an exclusive mount-disk resource to consider; -// does not apply to root or path disk resource types -// maxSize: size in MiB -func (p *PersistentVolume) SetMaxSize(maxSize int) *PersistentVolume { - p.MaxSize = maxSize - return p -} - -// AddConstraint adds a new constraint -// constraints: the constraint definition, one constraint per array element -func (p *PersistentVolume) AddConstraint(constraints ...string) *PersistentVolume { - if p.Constraints == nil { - p.EmptyConstraints() - } - - c := *p.Constraints - c = append(c, constraints) - p.Constraints = &c - return p -} - -// EmptyConstraints explicitly empties constraints -- use this if you need to empty -// constraints of an application that already has constraints set (setting constraints to nil will -// keep the current value) -func (p *PersistentVolume) EmptyConstraints() *PersistentVolume { - p.Constraints = &[][]string{} - return p -} - -// ExternalVolume is an external volume definition -type ExternalVolume struct { - Name string `json:"name,omitempty"` - Provider string `json:"provider,omitempty"` - Options *map[string]string `json:"options,omitempty"` -} - -// Docker is the docker definition from a marathon application -type Docker struct { - ForcePullImage *bool `json:"forcePullImage,omitempty"` - Image string `json:"image,omitempty"` - Network string `json:"network,omitempty"` - Parameters *[]Parameters `json:"parameters,omitempty"` - PortMappings *[]PortMapping `json:"portMappings,omitempty"` - Privileged *bool `json:"privileged,omitempty"` -} - -// Volume attachs a volume to the container -// host_path: the path on the docker host to map -// container_path: the path inside the container to map the host volume -// mode: the mode to map the container -func (container *Container) Volume(hostPath, containerPath, mode string) *Container { - if container.Volumes == nil { - container.EmptyVolumes() - } - - volumes := *container.Volumes - volumes = append(volumes, Volume{ - ContainerPath: containerPath, - HostPath: hostPath, - Mode: mode, - }) - - container.Volumes = &volumes - - return container -} - -// EmptyVolumes explicitly empties the volumes -- use this if you need to empty -// volumes of an application that already has volumes set (setting volumes to nil will -// keep the current value) -func (container *Container) EmptyVolumes() *Container { - container.Volumes = &[]Volume{} - return container -} - -// SetPersistentVolume defines persistent properties for volume -func (v *Volume) SetPersistentVolume() *PersistentVolume { - ev := &PersistentVolume{} - v.Persistent = ev - return ev -} - -// EmptyPersistentVolume empties the persistent volume definition -func (v *Volume) EmptyPersistentVolume() *Volume { - v.Persistent = &PersistentVolume{} - return v -} - -// SetExternalVolume define external elements for a volume -// name: the name of the volume -// provider: the provider of the volume (e.g. dvdi) -func (v *Volume) SetExternalVolume(name, provider string) *ExternalVolume { - ev := &ExternalVolume{ - Name: name, - Provider: provider, - } - v.External = ev - return ev -} - -// EmptyExternalVolume emptys the external volume definition -func (v *Volume) EmptyExternalVolume() *Volume { - v.External = &ExternalVolume{} - return v -} - -// AddOption adds an option to an ExternalVolume -// name: the name of the option -// value: value for the option -func (ev *ExternalVolume) AddOption(name, value string) *ExternalVolume { - if ev.Options == nil { - ev.EmptyOptions() - } - (*ev.Options)[name] = value - - return ev -} - -// EmptyOptions explicitly empties the options -func (ev *ExternalVolume) EmptyOptions() *ExternalVolume { - ev.Options = &map[string]string{} - - return ev -} - -// NewDockerContainer creates a default docker container for you -func NewDockerContainer() *Container { - container := &Container{} - container.Type = "DOCKER" - container.Docker = &Docker{} - - return container -} - -// SetForcePullImage sets whether the docker image should always be force pulled before -// starting an instance -// forcePull: true / false -func (docker *Docker) SetForcePullImage(forcePull bool) *Docker { - docker.ForcePullImage = &forcePull - - return docker -} - -// SetPrivileged sets whether the docker image should be started -// with privilege turned on -// priv: true / false -func (docker *Docker) SetPrivileged(priv bool) *Docker { - docker.Privileged = &priv - - return docker -} - -// Container sets the image of the container -// image: the image name you are using -func (docker *Docker) Container(image string) *Docker { - docker.Image = image - return docker -} - -// Bridged sets the networking mode to bridged -func (docker *Docker) Bridged() *Docker { - docker.Network = "BRIDGE" - return docker -} - -// Host sets the networking mode to host -func (docker *Docker) Host() *Docker { - docker.Network = "HOST" - return docker -} - -// Expose sets the container to expose the following TCP ports -// ports: the TCP ports the container is exposing -func (container *Container) Expose(ports ...int) *Container { - for _, port := range ports { - container.ExposePort(PortMapping{ - ContainerPort: port, - HostPort: 0, - ServicePort: 0, - Protocol: "tcp"}) - } - return container -} - -// Expose sets the container to expose the following TCP ports -// ports: the TCP ports the container is exposing -func (docker *Docker) Expose(ports ...int) *Docker { - for _, port := range ports { - docker.ExposePort(PortMapping{ - ContainerPort: port, - HostPort: 0, - ServicePort: 0, - Protocol: "tcp"}) - } - return docker -} - -// ExposeUDP sets the container to expose the following UDP ports -// ports: the UDP ports the container is exposing -func (container *Container) ExposeUDP(ports ...int) *Container { - for _, port := range ports { - container.ExposePort(PortMapping{ - ContainerPort: port, - HostPort: 0, - ServicePort: 0, - Protocol: "udp"}) - } - return container -} - -// ExposeUDP sets the container to expose the following UDP ports -// ports: the UDP ports the container is exposing -func (docker *Docker) ExposeUDP(ports ...int) *Docker { - for _, port := range ports { - docker.ExposePort(PortMapping{ - ContainerPort: port, - HostPort: 0, - ServicePort: 0, - Protocol: "udp"}) - } - return docker -} - -// ExposePort exposes an port in the container -func (container *Container) ExposePort(portMapping PortMapping) *Container { - if container.PortMappings == nil { - container.EmptyPortMappings() - } - - portMappings := *container.PortMappings - portMappings = append(portMappings, portMapping) - container.PortMappings = &portMappings - - return container -} - -// ExposePort exposes an port in the container -func (docker *Docker) ExposePort(portMapping PortMapping) *Docker { - if docker.PortMappings == nil { - docker.EmptyPortMappings() - } - - portMappings := *docker.PortMappings - portMappings = append(portMappings, portMapping) - docker.PortMappings = &portMappings - - return docker -} - -// EmptyPortMappings explicitly empties the port mappings -- use this if you need to empty -// port mappings of an application that already has port mappings set (setting port mappings to nil will -// keep the current value) -func (container *Container) EmptyPortMappings() *Container { - container.PortMappings = &[]PortMapping{} - return container -} - -// EmptyPortMappings explicitly empties the port mappings -- use this if you need to empty -// port mappings of an application that already has port mappings set (setting port mappings to nil will -// keep the current value) -func (docker *Docker) EmptyPortMappings() *Docker { - docker.PortMappings = &[]PortMapping{} - return docker -} - -// AddLabel adds a label to a PortMapping -// name: the name of the label -// value: value for this label -func (p *PortMapping) AddLabel(name, value string) *PortMapping { - if p.Labels == nil { - p.EmptyLabels() - } - (*p.Labels)[name] = value - - return p -} - -// EmptyLabels explicitly empties the labels -- use this if you need to empty -// the labels of a port mapping that already has labels set (setting labels to -// nil will keep the current value) -func (p *PortMapping) EmptyLabels() *PortMapping { - p.Labels = &map[string]string{} - - return p -} - -// AddParameter adds a parameter to the docker execution line when creating the container -// key: the name of the option to add -// value: the value of the option -func (docker *Docker) AddParameter(key string, value string) *Docker { - if docker.Parameters == nil { - docker.EmptyParameters() - } - - parameters := *docker.Parameters - parameters = append(parameters, Parameters{ - Key: key, - Value: value}) - - docker.Parameters = ¶meters - - return docker -} - -// EmptyParameters explicitly empties the parameters -- use this if you need to empty -// parameters of an application that already has parameters set (setting parameters to nil will -// keep the current value) -func (docker *Docker) EmptyParameters() *Docker { - docker.Parameters = &[]Parameters{} - return docker -} - -// ServicePortIndex finds the service port index of the exposed port -// port: the port you are looking for -func (container *Container) ServicePortIndex(port int) (int, error) { - if container.PortMappings == nil || len(*container.PortMappings) == 0 { - return 0, errors.New("The container does not contain any port mappings to search") - } - - // step: iterate and find the port - for index, containerPort := range *container.PortMappings { - if containerPort.ContainerPort == port { - return index, nil - } - } - - // step: we didn't find the port in the mappings - return 0, fmt.Errorf("The container port %d was not found in the container port mappings", port) -} - -// ServicePortIndex finds the service port index of the exposed port -// port: the port you are looking for -func (docker *Docker) ServicePortIndex(port int) (int, error) { - if docker.PortMappings == nil || len(*docker.PortMappings) == 0 { - return 0, errors.New("The docker does not contain any port mappings to search") - } - - // step: iterate and find the port - for index, containerPort := range *docker.PortMappings { - if containerPort.ContainerPort == port { - return index, nil - } - } - - // step: we didn't find the port in the mappings - return 0, fmt.Errorf("The docker port %d was not found in the container port mappings", port) -} - -// AddNetwork adds a network name to a PortMapping -// name: the name of the network -func (p *PortMapping) AddNetwork(name string) *PortMapping { - if p.NetworkNames == nil { - p.EmptyNetworkNames() - } - networks := *p.NetworkNames - networks = append(networks, name) - p.NetworkNames = &networks - return p -} - -// EmptyNetworkNames explicitly empties the network names -- use this if you need to empty -// the network names of a port mapping that already has network names set -func (p *PortMapping) EmptyNetworkNames() *PortMapping { - p.NetworkNames = &[]string{} - - return p -} diff --git a/vendor/github.com/gambol99/go-marathon/error.go b/vendor/github.com/gambol99/go-marathon/error.go deleted file mode 100644 index d52e60de1..000000000 --- a/vendor/github.com/gambol99/go-marathon/error.go +++ /dev/null @@ -1,229 +0,0 @@ -/* -Copyright 2015 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" - "net/http" - "strings" -) - -const ( - // ErrCodeBadRequest specifies a 400 Bad Request error. - ErrCodeBadRequest = iota - // ErrCodeUnauthorized specifies a 401 Unauthorized error. - ErrCodeUnauthorized - // ErrCodeForbidden specifies a 403 Forbidden error. - ErrCodeForbidden - // ErrCodeNotFound specifies a 404 Not Found error. - ErrCodeNotFound - // ErrCodeDuplicateID specifies a PUT 409 Conflict error. - ErrCodeDuplicateID - // ErrCodeAppLocked specifies a POST 409 Conflict error. - ErrCodeAppLocked - // ErrCodeInvalidBean specifies a 422 UnprocessableEntity error. - ErrCodeInvalidBean - // ErrCodeServer specifies a 500+ Server error. - ErrCodeServer - // ErrCodeUnknown specifies an unknown error. - ErrCodeUnknown - // ErrCodeMethodNotAllowed specifies a 405 Method Not Allowed. - ErrCodeMethodNotAllowed -) - -// InvalidEndpointError indicates a endpoint error in the marathon urls -type InvalidEndpointError struct { - message string -} - -// Error returns the string message -func (e *InvalidEndpointError) Error() string { - return e.message -} - -// newInvalidEndpointError creates a new error -func newInvalidEndpointError(message string, args ...interface{}) error { - return &InvalidEndpointError{message: fmt.Sprintf(message, args)} -} - -// APIError represents a generic API error. -type APIError struct { - // ErrCode specifies the nature of the error. - ErrCode int - message string -} - -func (e *APIError) Error() string { - return fmt.Sprintf("Marathon API error: %s", e.message) -} - -// NewAPIError creates a new APIError instance from the given response code and content. -func NewAPIError(code int, content []byte) error { - var errDef errorDefinition - switch { - case code == http.StatusBadRequest: - errDef = &badRequestDef{} - case code == http.StatusUnauthorized: - errDef = &simpleErrDef{code: ErrCodeUnauthorized} - case code == http.StatusForbidden: - errDef = &simpleErrDef{code: ErrCodeForbidden} - case code == http.StatusNotFound: - errDef = &simpleErrDef{code: ErrCodeNotFound} - case code == http.StatusMethodNotAllowed: - errDef = &simpleErrDef{code: ErrCodeMethodNotAllowed} - case code == http.StatusConflict: - errDef = &conflictDef{} - case code == 422: - errDef = &unprocessableEntityDef{} - case code >= http.StatusInternalServerError: - errDef = &simpleErrDef{code: ErrCodeServer} - default: - errDef = &simpleErrDef{code: ErrCodeUnknown} - } - - return parseContent(errDef, content) -} - -type errorDefinition interface { - message() string - errCode() int -} - -func parseContent(errDef errorDefinition, content []byte) error { - // If the content cannot be JSON-unmarshalled, we assume that it's not JSON - // and encode it into the APIError instance as-is. - errMessage := string(content) - if err := json.Unmarshal(content, errDef); err == nil { - errMessage = errDef.message() - } - - return &APIError{message: errMessage, ErrCode: errDef.errCode()} -} - -type simpleErrDef struct { - Message string `json:"message"` - code int -} - -func (def *simpleErrDef) message() string { - return def.Message -} - -func (def *simpleErrDef) errCode() int { - return def.code -} - -type detailDescription struct { - Path string `json:"path"` - Errors []string `json:"errors"` -} - -func (d detailDescription) String() string { - return fmt.Sprintf("path: '%s' errors: %s", d.Path, strings.Join(d.Errors, ", ")) -} - -type badRequestDef struct { - Message string `json:"message"` - Details []detailDescription `json:"details"` -} - -func (def *badRequestDef) message() string { - var details []string - for _, detail := range def.Details { - details = append(details, detail.String()) - } - - return fmt.Sprintf("%s (%s)", def.Message, strings.Join(details, "; ")) -} - -func (def *badRequestDef) errCode() int { - return ErrCodeBadRequest -} - -type conflictDef struct { - Message string `json:"message"` - Deployments []struct { - ID string `json:"id"` - } `json:"deployments"` -} - -func (def *conflictDef) message() string { - if len(def.Deployments) == 0 { - // 409 Conflict response to "POST /v2/apps". - return def.Message - } - - // 409 Conflict response to "PUT /v2/apps/{appId}". - var ids []string - for _, deployment := range def.Deployments { - ids = append(ids, deployment.ID) - } - return fmt.Sprintf("%s (locking deployment IDs: %s)", def.Message, strings.Join(ids, ", ")) -} - -func (def *conflictDef) errCode() int { - if len(def.Deployments) == 0 { - return ErrCodeDuplicateID - } - - return ErrCodeAppLocked -} - -type unprocessableEntityDetails []struct { - // Used in Marathon >= 1.0.0-RC1. - detailDescription - // Used in Marathon < 1.0.0-RC1. - Attribute string `json:"attribute"` - Error string `json:"error"` -} - -type unprocessableEntityDef struct { - Message string `json:"message"` - // Name used in Marathon >= 0.15.0. - Details unprocessableEntityDetails `json:"details"` - // Name used in Marathon < 0.15.0. - Errors unprocessableEntityDetails `json:"errors"` -} - -func (def *unprocessableEntityDef) message() string { - joinDetails := func(details unprocessableEntityDetails) []string { - var res []string - for _, detail := range details { - res = append(res, fmt.Sprintf("attribute '%s': %s", detail.Attribute, detail.Error)) - } - return res - } - - var details []string - switch { - case len(def.Errors) > 0: - details = joinDetails(def.Errors) - case len(def.Details) > 0 && len(def.Details[0].Attribute) > 0: - details = joinDetails(def.Details) - default: - for _, detail := range def.Details { - details = append(details, detail.detailDescription.String()) - } - } - - return fmt.Sprintf("%s (%s)", def.Message, strings.Join(details, "; ")) -} - -func (def *unprocessableEntityDef) errCode() int { - return ErrCodeInvalidBean -} diff --git a/vendor/github.com/gambol99/go-marathon/events.go b/vendor/github.com/gambol99/go-marathon/events.go deleted file mode 100644 index 5814cad29..000000000 --- a/vendor/github.com/gambol99/go-marathon/events.go +++ /dev/null @@ -1,366 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import "fmt" - -// EventType is a wrapper for a marathon event -type EventType struct { - EventType string `json:"eventType"` -} - -const ( - // EventIDAPIRequest is the event listener ID for the corresponding event. - EventIDAPIRequest = 1 << iota - // EventIDStatusUpdate is the event listener ID for the corresponding event. - EventIDStatusUpdate - // EventIDFrameworkMessage is the event listener ID for the corresponding event. - EventIDFrameworkMessage - // EventIDSubscription is the event listener ID for the corresponding event. - EventIDSubscription - // EventIDUnsubscribed is the event listener ID for the corresponding event. - EventIDUnsubscribed - // EventIDStreamAttached is the event listener ID for the corresponding event. - EventIDStreamAttached - // EventIDStreamDetached is the event listener ID for the corresponding event. - EventIDStreamDetached - // EventIDAddHealthCheck is the event listener ID for the corresponding event. - EventIDAddHealthCheck - // EventIDRemoveHealthCheck is the event listener ID for the corresponding event. - EventIDRemoveHealthCheck - // EventIDFailedHealthCheck is the event listener ID for the corresponding event. - EventIDFailedHealthCheck - // EventIDChangedHealthCheck is the event listener ID for the corresponding event. - EventIDChangedHealthCheck - // EventIDGroupChangeSuccess is the event listener ID for the corresponding event. - EventIDGroupChangeSuccess - // EventIDGroupChangeFailed is the event listener ID for the corresponding event. - EventIDGroupChangeFailed - // EventIDDeploymentSuccess is the event listener ID for the corresponding event. - EventIDDeploymentSuccess - // EventIDDeploymentFailed is the event listener ID for the corresponding event. - EventIDDeploymentFailed - // EventIDDeploymentInfo is the event listener ID for the corresponding event. - EventIDDeploymentInfo - // EventIDDeploymentStepSuccess is the event listener ID for the corresponding event. - EventIDDeploymentStepSuccess - // EventIDDeploymentStepFailed is the event listener ID for the corresponding event. - EventIDDeploymentStepFailed - // EventIDAppTerminated is the event listener ID for the corresponding event. - EventIDAppTerminated - //EventIDApplications comprises all listener IDs for application events. - EventIDApplications = EventIDStatusUpdate | EventIDChangedHealthCheck | EventIDFailedHealthCheck | EventIDAppTerminated - //EventIDSubscriptions comprises all listener IDs for subscription events. - EventIDSubscriptions = EventIDSubscription | EventIDUnsubscribed | EventIDStreamAttached | EventIDStreamDetached -) - -var ( - eventTypesMap map[string]int -) - -func init() { - eventTypesMap = map[string]int{ - "api_post_event": EventIDAPIRequest, - "status_update_event": EventIDStatusUpdate, - "framework_message_event": EventIDFrameworkMessage, - "subscribe_event": EventIDSubscription, - "unsubscribe_event": EventIDUnsubscribed, - "event_stream_attached": EventIDStreamAttached, - "event_stream_detached": EventIDStreamDetached, - "add_health_check_event": EventIDAddHealthCheck, - "remove_health_check_event": EventIDRemoveHealthCheck, - "failed_health_check_event": EventIDFailedHealthCheck, - "health_status_changed_event": EventIDChangedHealthCheck, - "group_change_success": EventIDGroupChangeSuccess, - "group_change_failed": EventIDGroupChangeFailed, - "deployment_success": EventIDDeploymentSuccess, - "deployment_failed": EventIDDeploymentFailed, - "deployment_info": EventIDDeploymentInfo, - "deployment_step_success": EventIDDeploymentStepSuccess, - "deployment_step_failure": EventIDDeploymentStepFailed, - "app_terminated_event": EventIDAppTerminated, - } -} - -// -// Events taken from: https://mesosphere.github.io/marathon/docs/event-bus.html -// - -// Event is the definition for a event in marathon -type Event struct { - ID int - Name string - Event interface{} -} - -func (event *Event) String() string { - return fmt.Sprintf("type: %s, event: %s", event.Name, event.Event) -} - -// EventsChannel is a channel to receive events upon -type EventsChannel chan *Event - -/* --- API Request --- */ - -// EventAPIRequest describes an 'api_post_event' event. -type EventAPIRequest struct { - EventType string `json:"eventType"` - ClientIP string `json:"clientIp"` - Timestamp string `json:"timestamp"` - URI string `json:"uri"` - AppDefinition *Application `json:"appDefinition"` -} - -/* --- Status Update --- */ - -// EventStatusUpdate describes a 'status_update_event' event. -type EventStatusUpdate struct { - EventType string `json:"eventType"` - Timestamp string `json:"timestamp,omitempty"` - SlaveID string `json:"slaveId,omitempty"` - TaskID string `json:"taskId"` - TaskStatus string `json:"taskStatus"` - Message string `json:"message,omitempty"` - AppID string `json:"appId"` - Host string `json:"host"` - Ports []int `json:"ports,omitempty"` - IPAddresses []*IPAddress `json:"ipAddresses"` - Version string `json:"version,omitempty"` -} - -// EventAppTerminated describes an 'app_terminated_event' event. -type EventAppTerminated struct { - EventType string `json:"eventType"` - Timestamp string `json:"timestamp,omitempty"` - AppID string `json:"appId"` -} - -/* --- Framework Message --- */ - -// EventFrameworkMessage describes a 'framework_message_event' event. -type EventFrameworkMessage struct { - EventType string `json:"eventType"` - ExecutorID string `json:"executorId"` - Message string `json:"message"` - SlaveID string `json:"slaveId"` - Timestamp string `json:"timestamp"` -} - -/* --- Event Subscription --- */ - -// EventSubscription describes a 'subscribe_event' event. -type EventSubscription struct { - CallbackURL string `json:"callbackUrl"` - ClientIP string `json:"clientIp"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` -} - -// EventUnsubscription describes an 'unsubscribe_event' event. -type EventUnsubscription struct { - CallbackURL string `json:"callbackUrl"` - ClientIP string `json:"clientIp"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` -} - -// EventStreamAttached describes an 'event_stream_attached' event. -type EventStreamAttached struct { - RemoteAddress string `json:"remoteAddress"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` -} - -// EventStreamDetached describes an 'event_stream_detached' event. -type EventStreamDetached struct { - RemoteAddress string `json:"remoteAddress"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` -} - -/* --- Health Checks --- */ - -// EventAddHealthCheck describes an 'add_health_check_event' event. -type EventAddHealthCheck struct { - AppID string `json:"appId"` - EventType string `json:"eventType"` - HealthCheck struct { - GracePeriodSeconds float64 `json:"gracePeriodSeconds"` - IntervalSeconds float64 `json:"intervalSeconds"` - MaxConsecutiveFailures float64 `json:"maxConsecutiveFailures"` - Path string `json:"path"` - PortIndex float64 `json:"portIndex"` - Protocol string `json:"protocol"` - TimeoutSeconds float64 `json:"timeoutSeconds"` - } `json:"healthCheck"` - Timestamp string `json:"timestamp"` -} - -// EventRemoveHealthCheck describes a 'remove_health_check_event' event. -type EventRemoveHealthCheck struct { - AppID string `json:"appId"` - EventType string `json:"eventType"` - HealthCheck struct { - GracePeriodSeconds float64 `json:"gracePeriodSeconds"` - IntervalSeconds float64 `json:"intervalSeconds"` - MaxConsecutiveFailures float64 `json:"maxConsecutiveFailures"` - Path string `json:"path"` - PortIndex float64 `json:"portIndex"` - Protocol string `json:"protocol"` - TimeoutSeconds float64 `json:"timeoutSeconds"` - } `json:"healthCheck"` - Timestamp string `json:"timestamp"` -} - -// EventFailedHealthCheck describes a 'failed_health_check_event' event. -type EventFailedHealthCheck struct { - AppID string `json:"appId"` - EventType string `json:"eventType"` - HealthCheck struct { - GracePeriodSeconds float64 `json:"gracePeriodSeconds"` - IntervalSeconds float64 `json:"intervalSeconds"` - MaxConsecutiveFailures float64 `json:"maxConsecutiveFailures"` - Path string `json:"path"` - PortIndex float64 `json:"portIndex"` - Protocol string `json:"protocol"` - TimeoutSeconds float64 `json:"timeoutSeconds"` - } `json:"healthCheck"` - Timestamp string `json:"timestamp"` -} - -// EventHealthCheckChanged describes a 'health_status_changed_event' event. -type EventHealthCheckChanged struct { - EventType string `json:"eventType"` - Timestamp string `json:"timestamp,omitempty"` - AppID string `json:"appId"` - TaskID string `json:"taskId"` - Version string `json:"version,omitempty"` - Alive bool `json:"alive"` -} - -/* --- Deployments --- */ - -// EventGroupChangeSuccess describes a 'group_change_success' event. -type EventGroupChangeSuccess struct { - EventType string `json:"eventType"` - GroupID string `json:"groupId"` - Timestamp string `json:"timestamp"` - Version string `json:"version"` -} - -// EventGroupChangeFailed describes a 'group_change_failed' event. -type EventGroupChangeFailed struct { - EventType string `json:"eventType"` - GroupID string `json:"groupId"` - Timestamp string `json:"timestamp"` - Version string `json:"version"` - Reason string `json:"reason"` -} - -// EventDeploymentSuccess describes a 'deployment_success' event. -type EventDeploymentSuccess struct { - ID string `json:"id"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` - Plan *DeploymentPlan `json:"plan"` -} - -// EventDeploymentFailed describes a 'deployment_failed' event. -type EventDeploymentFailed struct { - ID string `json:"id"` - EventType string `json:"eventType"` - Timestamp string `json:"timestamp"` -} - -// EventDeploymentInfo describes a 'deployment_info' event. -type EventDeploymentInfo struct { - EventType string `json:"eventType"` - CurrentStep *StepActions `json:"currentStep"` - Timestamp string `json:"timestamp"` - Plan *DeploymentPlan `json:"plan"` -} - -// EventDeploymentStepSuccess describes a 'deployment_step_success' event. -type EventDeploymentStepSuccess struct { - EventType string `json:"eventType"` - CurrentStep *StepActions `json:"currentStep"` - Timestamp string `json:"timestamp"` - Plan *DeploymentPlan `json:"plan"` -} - -// EventDeploymentStepFailure describes a 'deployment_step_failure' event. -type EventDeploymentStepFailure struct { - EventType string `json:"eventType"` - CurrentStep *StepActions `json:"currentStep"` - Timestamp string `json:"timestamp"` - Plan *DeploymentPlan `json:"plan"` -} - -// GetEvent returns allocated empty event object which corresponds to provided event type -// eventType: the type of Marathon event -func GetEvent(eventType string) (*Event, error) { - // step: check it's supported - id, found := eventTypesMap[eventType] - if found { - event := new(Event) - event.ID = id - event.Name = eventType - switch eventType { - case "api_post_event": - event.Event = new(EventAPIRequest) - case "status_update_event": - event.Event = new(EventStatusUpdate) - case "framework_message_event": - event.Event = new(EventFrameworkMessage) - case "subscribe_event": - event.Event = new(EventSubscription) - case "unsubscribe_event": - event.Event = new(EventUnsubscription) - case "event_stream_attached": - event.Event = new(EventStreamAttached) - case "event_stream_detached": - event.Event = new(EventStreamDetached) - case "add_health_check_event": - event.Event = new(EventAddHealthCheck) - case "remove_health_check_event": - event.Event = new(EventRemoveHealthCheck) - case "failed_health_check_event": - event.Event = new(EventFailedHealthCheck) - case "health_status_changed_event": - event.Event = new(EventHealthCheckChanged) - case "group_change_success": - event.Event = new(EventGroupChangeSuccess) - case "group_change_failed": - event.Event = new(EventGroupChangeFailed) - case "deployment_success": - event.Event = new(EventDeploymentSuccess) - case "deployment_failed": - event.Event = new(EventDeploymentFailed) - case "deployment_info": - event.Event = new(EventDeploymentInfo) - case "deployment_step_success": - event.Event = new(EventDeploymentStepSuccess) - case "deployment_step_failure": - event.Event = new(EventDeploymentStepFailure) - case "app_terminated_event": - event.Event = new(EventAppTerminated) - } - return event, nil - } - - return nil, fmt.Errorf("the event type: %s was not found or supported", eventType) -} diff --git a/vendor/github.com/gambol99/go-marathon/group.go b/vendor/github.com/gambol99/go-marathon/group.go deleted file mode 100644 index 63ce310bb..000000000 --- a/vendor/github.com/gambol99/go-marathon/group.go +++ /dev/null @@ -1,237 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" - "time" -) - -// Group is a marathon application group -type Group struct { - ID string `json:"id"` - Apps []*Application `json:"apps"` - Dependencies []string `json:"dependencies"` - Groups []*Group `json:"groups"` -} - -// Groups is a collection of marathon application groups -type Groups struct { - ID string `json:"id"` - Apps []*Application `json:"apps"` - Dependencies []string `json:"dependencies"` - Groups []*Group `json:"groups"` -} - -// GetGroupOpts contains a payload for Group and Groups method -// embed: Embeds nested resources that match the supplied path. -// You can specify this parameter multiple times with different values -type GetGroupOpts struct { - Embed []string `url:"embed,omitempty"` -} - -// DeleteGroupOpts contains a payload for DeleteGroup method -// force: overrides a currently running deployment. -type DeleteGroupOpts struct { - Force bool `url:"force,omitempty"` -} - -// UpdateGroupOpts contains a payload for UpdateGroup method -// force: overrides a currently running deployment. -type UpdateGroupOpts struct { - Force bool `url:"force,omitempty"` -} - -// NewApplicationGroup create a new application group -// name: the name of the group -func NewApplicationGroup(name string) *Group { - return &Group{ - ID: name, - Apps: make([]*Application, 0), - Dependencies: make([]string, 0), - Groups: make([]*Group, 0), - } -} - -// Name sets the name of the group -// name: the name of the group -func (r *Group) Name(name string) *Group { - r.ID = validateID(name) - return r -} - -// App add a application to the group in question -// application: a pointer to the Application -func (r *Group) App(application *Application) *Group { - if r.Apps == nil { - r.Apps = make([]*Application, 0) - } - r.Apps = append(r.Apps, application) - return r -} - -// Groups retrieves a list of all the groups from marathon -func (r *marathonClient) Groups() (*Groups, error) { - groups := new(Groups) - if err := r.apiGet(marathonAPIGroups, "", groups); err != nil { - return nil, err - } - return groups, nil -} - -// Group retrieves the configuration of a specific group from marathon -// name: the identifier for the group -func (r *marathonClient) Group(name string) (*Group, error) { - group := new(Group) - if err := r.apiGet(fmt.Sprintf("%s/%s", marathonAPIGroups, trimRootPath(name)), nil, group); err != nil { - return nil, err - } - return group, nil -} - -// GroupsBy retrieves a list of all the groups from marathon by embed options -// opts: GetGroupOpts request payload -func (r *marathonClient) GroupsBy(opts *GetGroupOpts) (*Groups, error) { - path, err := addOptions(marathonAPIGroups, opts) - if err != nil { - return nil, err - } - groups := new(Groups) - if err := r.apiGet(path, "", groups); err != nil { - return nil, err - } - return groups, nil -} - -// GroupBy retrieves the configuration of a specific group from marathon -// name: the identifier for the group -// opts: GetGroupOpts request payload -func (r *marathonClient) GroupBy(name string, opts *GetGroupOpts) (*Group, error) { - path, err := addOptions(fmt.Sprintf("%s/%s", marathonAPIGroups, trimRootPath(name)), opts) - if err != nil { - return nil, err - } - group := new(Group) - if err := r.apiGet(path, nil, group); err != nil { - return nil, err - } - return group, nil -} - -// HasGroup checks if the group exists in marathon -// name: the identifier for the group -func (r *marathonClient) HasGroup(name string) (bool, error) { - path := fmt.Sprintf("%s/%s", marathonAPIGroups, trimRootPath(name)) - err := r.apiGet(path, "", nil) - if err != nil { - if apiErr, ok := err.(*APIError); ok && apiErr.ErrCode == ErrCodeNotFound { - return false, nil - } - return false, err - } - return true, nil -} - -// CreateGroup creates a new group in marathon -// group: a pointer the Group structure defining the group -func (r *marathonClient) CreateGroup(group *Group) error { - return r.apiPost(marathonAPIGroups, group, nil) -} - -// WaitOnGroup waits for all the applications in a group to be deployed -// group: the identifier for the group -// timeout: a duration of time to wait before considering it failed (all tasks in all apps running defined as deployed) -func (r *marathonClient) WaitOnGroup(name string, timeout time.Duration) error { - err := deadline(timeout, func(stop_channel chan bool) error { - var flick atomicSwitch - go func() { - <-stop_channel - close(stop_channel) - flick.SwitchOn() - }() - for !flick.IsSwitched() { - if group, err := r.Group(name); err != nil { - continue - } else { - allRunning := true - // for each of the application, check if the tasks and running - for _, appID := range group.Apps { - // Arrrgghhh!! .. so we can't use application instances from the Application struct like with app wait on as it - // appears the instance count is not set straight away!! .. it defaults to zero and changes probably at the - // dependencies gets deployed. Which is probably how it internally handles dependencies .. - // step: grab the application - application, err := r.Application(appID.ID) - if err != nil { - allRunning = false - break - } - - if application.Tasks == nil { - allRunning = false - } else if len(application.Tasks) != *appID.Instances { - allRunning = false - } else if application.TasksRunning != *appID.Instances { - allRunning = false - } else if len(application.DeploymentIDs()) > 0 { - allRunning = false - } - } - // has anyone toggle the flag? - if allRunning { - return nil - } - } - time.Sleep(r.config.PollingWaitTime) - } - return nil - }) - - return err -} - -// DeleteGroup deletes a group from marathon -// name: the identifier for the group -// force: used to force the delete operation in case of blocked deployment -func (r *marathonClient) DeleteGroup(name string, force bool) (*DeploymentID, error) { - version := new(DeploymentID) - path := fmt.Sprintf("%s/%s", marathonAPIGroups, trimRootPath(name)) - if force { - path += "?force=true" - } - if err := r.apiDelete(path, nil, version); err != nil { - return nil, err - } - - return version, nil -} - -// UpdateGroup updates the parameters of a groups -// name: the identifier for the group -// group: the group structure with the new params -// force: used to force the update operation in case of blocked deployment -func (r *marathonClient) UpdateGroup(name string, group *Group, force bool) (*DeploymentID, error) { - deploymentID := new(DeploymentID) - path := fmt.Sprintf("%s/%s", marathonAPIGroups, trimRootPath(name)) - if force { - path += "?force=true" - } - if err := r.apiPut(path, group, deploymentID); err != nil { - return nil, err - } - - return deploymentID, nil -} diff --git a/vendor/github.com/gambol99/go-marathon/health.go b/vendor/github.com/gambol99/go-marathon/health.go deleted file mode 100644 index 4ebeb3170..000000000 --- a/vendor/github.com/gambol99/go-marathon/health.go +++ /dev/null @@ -1,129 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// HealthCheck is the definition for an application health check -type HealthCheck struct { - Command *Command `json:"command,omitempty"` - PortIndex *int `json:"portIndex,omitempty"` - Port *int `json:"port,omitempty"` - Path *string `json:"path,omitempty"` - MaxConsecutiveFailures *int `json:"maxConsecutiveFailures,omitempty"` - Protocol string `json:"protocol,omitempty"` - GracePeriodSeconds int `json:"gracePeriodSeconds,omitempty"` - IntervalSeconds int `json:"intervalSeconds,omitempty"` - TimeoutSeconds int `json:"timeoutSeconds,omitempty"` - IgnoreHTTP1xx *bool `json:"ignoreHttp1xx,omitempty"` -} - -// HTTPHealthCheck describes an HTTP based health check -type HTTPHealthCheck struct { - Endpoint string `json:"endpoint,omitempty"` - Path string `json:"path,omitempty"` - Scheme string `json:"scheme,omitempty"` -} - -// TCPHealthCheck describes a TCP based health check -type TCPHealthCheck struct { - Endpoint string `json:"endpoint,omitempty"` -} - -// CommandHealthCheck describes a shell-based health check -type CommandHealthCheck struct { - Command PodCommand `json:"command,omitempty"` -} - -// PodHealthCheck describes how to determine a pod's health -type PodHealthCheck struct { - HTTP *HTTPHealthCheck `json:"http,omitempty"` - TCP *TCPHealthCheck `json:"tcp,omitempty"` - Exec *CommandHealthCheck `json:"exec,omitempty"` - GracePeriodSeconds *int `json:"gracePeriodSeconds,omitempty"` - IntervalSeconds *int `json:"intervalSeconds,omitempty"` - MaxConsecutiveFailures *int `json:"maxConsecutiveFailures,omitempty"` - TimeoutSeconds *int `json:"timeoutSeconds,omitempty"` - DelaySeconds *int `json:"delaySeconds,omitempty"` -} - -// SetCommand sets the given command on the health check. -func (h *HealthCheck) SetCommand(c Command) *HealthCheck { - h.Command = &c - return h -} - -// SetPortIndex sets the given port index on the health check. -func (h *HealthCheck) SetPortIndex(i int) *HealthCheck { - h.PortIndex = &i - return h -} - -// SetPort sets the given port on the health check. -func (h *HealthCheck) SetPort(i int) *HealthCheck { - h.Port = &i - return h -} - -// SetPath sets the given path on the health check. -func (h *HealthCheck) SetPath(p string) *HealthCheck { - h.Path = &p - return h -} - -// SetMaxConsecutiveFailures sets the maximum consecutive failures on the health check. -func (h *HealthCheck) SetMaxConsecutiveFailures(i int) *HealthCheck { - h.MaxConsecutiveFailures = &i - return h -} - -// SetIgnoreHTTP1xx sets ignore http 1xx on the health check. -func (h *HealthCheck) SetIgnoreHTTP1xx(ignore bool) *HealthCheck { - h.IgnoreHTTP1xx = &ignore - return h -} - -// NewDefaultHealthCheck creates a default application health check -func NewDefaultHealthCheck() *HealthCheck { - portIndex := 0 - path := "" - maxConsecutiveFailures := 3 - - return &HealthCheck{ - Protocol: "HTTP", - Path: &path, - PortIndex: &portIndex, - MaxConsecutiveFailures: &maxConsecutiveFailures, - GracePeriodSeconds: 30, - IntervalSeconds: 10, - TimeoutSeconds: 5, - } -} - -// HealthCheckResult is the health check result -type HealthCheckResult struct { - Alive bool `json:"alive"` - ConsecutiveFailures int `json:"consecutiveFailures"` - FirstSuccess string `json:"firstSuccess"` - LastFailure string `json:"lastFailure"` - LastFailureCause string `json:"lastFailureCause"` - LastSuccess string `json:"lastSuccess"` - TaskID string `json:"taskId"` -} - -// Command is the command health check type -type Command struct { - Value string `json:"value"` -} diff --git a/vendor/github.com/gambol99/go-marathon/info.go b/vendor/github.com/gambol99/go-marathon/info.go deleted file mode 100644 index 45f5d6807..000000000 --- a/vendor/github.com/gambol99/go-marathon/info.go +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// Info is the detailed stats returned from marathon info -type Info struct { - EventSubscriber struct { - HTTPEndpoints []string `json:"http_endpoints"` - Type string `json:"type"` - } `json:"event_subscriber"` - FrameworkID string `json:"frameworkId"` - HTTPConfig struct { - AssetsPath interface{} `json:"assets_path"` - HTTPPort float64 `json:"http_port"` - HTTPSPort float64 `json:"https_port"` - } `json:"http_config"` - Leader string `json:"leader"` - MarathonConfig struct { - Checkpoint bool `json:"checkpoint"` - Executor string `json:"executor"` - FailoverTimeout float64 `json:"failover_timeout"` - FrameworkName string `json:"framework_name"` - Ha bool `json:"ha"` - Hostname string `json:"hostname"` - LeaderProxyConnectionTimeoutMs float64 `json:"leader_proxy_connection_timeout_ms"` - LeaderProxyReadTimeoutMs float64 `json:"leader_proxy_read_timeout_ms"` - LocalPortMax float64 `json:"local_port_max"` - LocalPortMin float64 `json:"local_port_min"` - Master string `json:"master"` - MesosLeaderUIURL string `json:"mesos_leader_ui_url"` - WebUIURL string `json:"webui_url"` - MesosRole string `json:"mesos_role"` - MesosUser string `json:"mesos_user"` - ReconciliationInitialDelay float64 `json:"reconciliation_initial_delay"` - ReconciliationInterval float64 `json:"reconciliation_interval"` - TaskLaunchTimeout float64 `json:"task_launch_timeout"` - TaskReservationTimeout float64 `json:"task_reservation_timeout"` - } `json:"marathon_config"` - Name string `json:"name"` - Version string `json:"version"` - ZookeeperConfig struct { - Zk string `json:"zk"` - ZkFutureTimeout struct { - Duration float64 `json:"duration"` - } `json:"zk_future_timeout"` - ZkHosts string `json:"zk_hosts"` - ZkPath string `json:"zk_path"` - ZkState string `json:"zk_state"` - ZkTimeout float64 `json:"zk_timeout"` - } `json:"zookeeper_config"` -} - -// Info retrieves the info stats from marathon -func (r *marathonClient) Info() (*Info, error) { - info := new(Info) - if err := r.apiGet(marathonAPIInfo, nil, info); err != nil { - return nil, err - } - - return info, nil -} - -// Leader retrieves the current marathon leader node -func (r *marathonClient) Leader() (string, error) { - var leader struct { - Leader string `json:"leader"` - } - if err := r.apiGet(marathonAPILeader, nil, &leader); err != nil { - return "", err - } - - return leader.Leader, nil -} - -// AbdicateLeader abdicates the marathon leadership -func (r *marathonClient) AbdicateLeader() (string, error) { - var message struct { - Message string `json:"message"` - } - - if err := r.apiDelete(marathonAPILeader, nil, &message); err != nil { - return "", err - } - - return message.Message, nil -} diff --git a/vendor/github.com/gambol99/go-marathon/last_task_failure.go b/vendor/github.com/gambol99/go-marathon/last_task_failure.go deleted file mode 100644 index 357deee52..000000000 --- a/vendor/github.com/gambol99/go-marathon/last_task_failure.go +++ /dev/null @@ -1,29 +0,0 @@ -/* -Copyright 2015 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// LastTaskFailure provides details on the last error experienced by an application -type LastTaskFailure struct { - AppID string `json:"appId,omitempty"` - Host string `json:"host,omitempty"` - Message string `json:"message,omitempty"` - SlaveID string `json:"slaveId,omitempty"` - State string `json:"state,omitempty"` - TaskID string `json:"taskId,omitempty"` - Timestamp string `json:"timestamp,omitempty"` - Version string `json:"version,omitempty"` -} diff --git a/vendor/github.com/gambol99/go-marathon/network.go b/vendor/github.com/gambol99/go-marathon/network.go deleted file mode 100644 index 6804996f4..000000000 --- a/vendor/github.com/gambol99/go-marathon/network.go +++ /dev/null @@ -1,124 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PodNetworkMode is the mode of a network descriptor -type PodNetworkMode string - -const ( - ContainerNetworkMode PodNetworkMode = "container" - BridgeNetworkMode PodNetworkMode = "container/bridge" - HostNetworkMode PodNetworkMode = "host" -) - -// PodNetwork contains network descriptors for a pod -type PodNetwork struct { - Name string `json:"name,omitempty"` - Mode PodNetworkMode `json:"mode,omitempty"` - Labels map[string]string `json:"labels,omitempty"` -} - -// PodEndpoint describes an endpoint for a pod's container -type PodEndpoint struct { - Name string `json:"name,omitempty"` - ContainerPort int `json:"containerPort,omitempty"` - HostPort int `json:"hostPort,omitempty"` - Protocol []string `json:"protocol,omitempty"` - Labels map[string]string `json:"labels,omitempty"` -} - -// NewPodNetwork creates an empty PodNetwork -func NewPodNetwork(name string) *PodNetwork { - return &PodNetwork{ - Name: name, - Labels: map[string]string{}, - } -} - -// NewPodEndpoint creates an empty PodEndpoint -func NewPodEndpoint() *PodEndpoint { - return &PodEndpoint{ - Protocol: []string{}, - Labels: map[string]string{}, - } -} - -// NewBridgePodNetwork creates a PodNetwork for a container in bridge mode -func NewBridgePodNetwork() *PodNetwork { - pn := NewPodNetwork("") - return pn.SetMode(BridgeNetworkMode) -} - -// NewContainerPodNetwork creates a PodNetwork for a container -func NewContainerPodNetwork(name string) *PodNetwork { - pn := NewPodNetwork(name) - return pn.SetMode(ContainerNetworkMode) -} - -// NewHostPodNetwork creates a PodNetwork for a container in host mode -func NewHostPodNetwork() *PodNetwork { - pn := NewPodNetwork("") - return pn.SetMode(HostNetworkMode) -} - -// SetName sets the name of a PodNetwork -func (n *PodNetwork) SetName(name string) *PodNetwork { - n.Name = name - return n -} - -// SetMode sets the mode of a PodNetwork -func (n *PodNetwork) SetMode(mode PodNetworkMode) *PodNetwork { - n.Mode = mode - return n -} - -// Label sets a label of a PodNetwork -func (n *PodNetwork) Label(key, value string) *PodNetwork { - n.Labels[key] = value - return n -} - -// SetName sets the name for a PodEndpoint -func (e *PodEndpoint) SetName(name string) *PodEndpoint { - e.Name = name - return e -} - -// SetContainerPort sets the container port for a PodEndpoint -func (e *PodEndpoint) SetContainerPort(port int) *PodEndpoint { - e.ContainerPort = port - return e -} - -// SetHostPort sets the host port for a PodEndpoint -func (e *PodEndpoint) SetHostPort(port int) *PodEndpoint { - e.HostPort = port - return e -} - -// AddProtocol appends a protocol for a PodEndpoint -func (e *PodEndpoint) AddProtocol(protocol string) *PodEndpoint { - e.Protocol = append(e.Protocol, protocol) - return e -} - -// Label sets a label for a PodEndpoint -func (e *PodEndpoint) Label(key, value string) *PodEndpoint { - e.Labels[key] = value - return e -} diff --git a/vendor/github.com/gambol99/go-marathon/pod.go b/vendor/github.com/gambol99/go-marathon/pod.go deleted file mode 100644 index adeb70a54..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod.go +++ /dev/null @@ -1,277 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" -) - -// Pod is the definition for an pod in marathon -type Pod struct { - ID string `json:"id,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Version string `json:"version,omitempty"` - User string `json:"user,omitempty"` - // Non-secret environment variables. Actual secrets are stored in Secrets - // Magic happens at marshaling/unmarshaling to get them into the correct schema - Env map[string]string `json:"-"` - Secrets map[string]Secret `json:"-"` - Containers []*PodContainer `json:"containers,omitempty"` - Volumes []*PodVolume `json:"volumes,omitempty"` - Networks []*PodNetwork `json:"networks,omitempty"` - Scaling *PodScalingPolicy `json:"scaling,omitempty"` - Scheduling *PodSchedulingPolicy `json:"scheduling,omitempty"` - ExecutorResources *ExecutorResources `json:"executorResources,omitempty"` -} - -// PodScalingPolicy is the scaling policy of the pod -type PodScalingPolicy struct { - Kind string `json:"kind"` - Instances int `json:"instances"` - MaxInstances int `json:"maxInstances,omitempty"` -} - -// NewPod create an empty pod -func NewPod() *Pod { - return &Pod{ - Labels: map[string]string{}, - Env: map[string]string{}, - Containers: []*PodContainer{}, - Secrets: map[string]Secret{}, - Volumes: []*PodVolume{}, - Networks: []*PodNetwork{}, - } -} - -// Name sets the name / ID of the pod i.e. the identifier for this pod -func (p *Pod) Name(id string) *Pod { - p.ID = validateID(id) - return p -} - -// SetUser sets the user to run the pod as -func (p *Pod) SetUser(user string) *Pod { - p.User = user - return p -} - -// EmptyLabels empties the labels in a pod -func (p *Pod) EmptyLabels() *Pod { - p.Labels = make(map[string]string) - return p -} - -// AddLabel adds a label to a pod -func (p *Pod) AddLabel(key, value string) *Pod { - p.Labels[key] = value - return p -} - -// SetLabels sets the labels for a pod -func (p *Pod) SetLabels(labels map[string]string) *Pod { - p.Labels = labels - return p -} - -// EmptyEnvs empties the environment variables for a pod -func (p *Pod) EmptyEnvs() *Pod { - p.Env = make(map[string]string) - return p -} - -// AddEnv adds an environment variable to a pod -func (p *Pod) AddEnv(name, value string) *Pod { - if p.Env == nil { - p = p.EmptyEnvs() - } - p.Env[name] = value - return p -} - -// ExtendEnv extends the environment with the new environment variables -func (p *Pod) ExtendEnv(env map[string]string) *Pod { - if p.Env == nil { - p = p.EmptyEnvs() - } - - for k, v := range env { - p.AddEnv(k, v) - } - return p -} - -// AddContainer adds a container to a pod -func (p *Pod) AddContainer(container *PodContainer) *Pod { - p.Containers = append(p.Containers, container) - return p -} - -// EmptySecrets empties the secret sources in a pod -func (p *Pod) EmptySecrets() *Pod { - p.Secrets = make(map[string]Secret) - return p -} - -// GetSecretSource gets the source of the named secret -func (p *Pod) GetSecretSource(name string) (string, error) { - if val, ok := p.Secrets[name]; ok { - return val.Source, nil - } - return "", fmt.Errorf("secret does not exist") -} - -// AddSecret adds the secret to the pod -func (p *Pod) AddSecret(envVar, secretName, sourceName string) *Pod { - if p.Secrets == nil { - p = p.EmptySecrets() - } - p.Secrets[secretName] = Secret{EnvVar: envVar, Source: sourceName} - return p -} - -// AddVolume adds a volume to a pod -func (p *Pod) AddVolume(vol *PodVolume) *Pod { - p.Volumes = append(p.Volumes, vol) - return p -} - -// AddNetwork adds a PodNetwork to a pod -func (p *Pod) AddNetwork(net *PodNetwork) *Pod { - p.Networks = append(p.Networks, net) - return p -} - -// Count sets the count of the pod -func (p *Pod) Count(count int) *Pod { - p.Scaling = &PodScalingPolicy{ - Kind: "fixed", - Instances: count, - } - return p -} - -// SetPodSchedulingPolicy sets the PodSchedulingPolicy of a pod -func (p *Pod) SetPodSchedulingPolicy(policy *PodSchedulingPolicy) *Pod { - p.Scheduling = policy - return p -} - -// SetExecutorResources sets the resources for the pod executor -func (p *Pod) SetExecutorResources(resources *ExecutorResources) *Pod { - p.ExecutorResources = resources - return p -} - -// SupportsPods determines if this version of marathon supports pods -// If HEAD returns 200 it does -func (r *marathonClient) SupportsPods() (bool, error) { - if err := r.apiHead(marathonAPIPods, nil); err != nil { - // If we get a 404 we can return a strict false, otherwise it could be - // a valid error - if apiErr, ok := err.(*APIError); ok && apiErr.ErrCode == ErrCodeNotFound { - return false, nil - } - return false, err - } - - return true, nil -} - -// Pod gets a pod object from marathon by name -func (r *marathonClient) Pod(name string) (*Pod, error) { - uri := buildPodURI(name) - result := new(Pod) - if err := r.apiGet(uri, nil, result); err != nil { - return nil, err - } - - return result, nil -} - -// Pods gets all pods from marathon -func (r *marathonClient) Pods() ([]Pod, error) { - var result []Pod - if err := r.apiGet(marathonAPIPods, nil, &result); err != nil { - return nil, err - } - - return result, nil -} - -// CreatePod creates a new pod in Marathon -func (r *marathonClient) CreatePod(pod *Pod) (*Pod, error) { - result := new(Pod) - if err := r.apiPost(marathonAPIPods, &pod, result); err != nil { - return nil, err - } - - return result, nil -} - -// DeletePod deletes a pod from marathon -func (r *marathonClient) DeletePod(name string, force bool) (*DeploymentID, error) { - uri := fmt.Sprintf("%s?force=%v", buildPodURI(name), force) - - deployID := new(DeploymentID) - if err := r.apiDelete(uri, nil, deployID); err != nil { - return nil, err - } - - return deployID, nil -} - -// UpdatePod creates a new pod in Marathon -func (r *marathonClient) UpdatePod(pod *Pod, force bool) (*Pod, error) { - uri := fmt.Sprintf("%s?force=%v", buildPodURI(pod.ID), force) - result := new(Pod) - - if err := r.apiPut(uri, pod, result); err != nil { - return nil, err - } - - return result, nil -} - -// PodVersions gets all the deployed versions of a pod -func (r *marathonClient) PodVersions(name string) ([]string, error) { - uri := buildPodVersionURI(name) - var result []string - if err := r.apiGet(uri, nil, &result); err != nil { - return nil, err - } - - return result, nil -} - -// PodByVersion gets a pod by a version identifier -func (r *marathonClient) PodByVersion(name, version string) (*Pod, error) { - uri := fmt.Sprintf("%s/%s", buildPodVersionURI(name), version) - result := new(Pod) - if err := r.apiGet(uri, nil, result); err != nil { - return nil, err - } - - return result, nil -} - -func buildPodVersionURI(name string) string { - return fmt.Sprintf("%s/%s::versions", marathonAPIPods, trimRootPath(name)) -} - -func buildPodURI(path string) string { - return fmt.Sprintf("%s/%s", marathonAPIPods, trimRootPath(path)) -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_container.go b/vendor/github.com/gambol99/go-marathon/pod_container.go deleted file mode 100644 index c5ef908ff..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_container.go +++ /dev/null @@ -1,193 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PodContainer describes a container in a pod -type PodContainer struct { - Name string `json:"name,omitempty"` - Exec *PodExec `json:"exec,omitempty"` - Resources *Resources `json:"resources,omitempty"` - Endpoints []*PodEndpoint `json:"endpoints,omitempty"` - Image *PodContainerImage `json:"image,omitempty"` - Env map[string]string `json:"-"` - Secrets map[string]Secret `json:"-"` - User string `json:"user,omitempty"` - HealthCheck *PodHealthCheck `json:"healthCheck,omitempty"` - VolumeMounts []*PodVolumeMount `json:"volumeMounts,omitempty"` - Artifacts []*PodArtifact `json:"artifacts,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - Lifecycle PodLifecycle `json:"lifecycle,omitempty"` -} - -// PodLifecycle describes the lifecycle of a pod -type PodLifecycle struct { - KillGracePeriodSeconds *float64 `json:"killGracePeriodSeconds,omitempty"` -} - -// PodCommand is the command to run as the entrypoint of the container -type PodCommand struct { - Shell string `json:"shell,omitempty"` -} - -// PodExec contains the PodCommand -type PodExec struct { - Command PodCommand `json:"command,omitempty"` -} - -// PodArtifact describes how to obtain a generic artifact for a pod -type PodArtifact struct { - URI string `json:"uri,omitempty"` - Extract bool `json:"extract,omitempty"` - Executable bool `json:"executable,omitempty"` - Cache bool `json:"cache,omitempty"` - DestPath string `json:"destPath,omitempty"` -} - -// NewPodContainer creates an empty PodContainer -func NewPodContainer() *PodContainer { - return &PodContainer{ - Endpoints: []*PodEndpoint{}, - Env: map[string]string{}, - VolumeMounts: []*PodVolumeMount{}, - Artifacts: []*PodArtifact{}, - Labels: map[string]string{}, - Resources: NewResources(), - } -} - -// SetName sets the name of a pod container -func (p *PodContainer) SetName(name string) *PodContainer { - p.Name = name - return p -} - -// SetCommand sets the shell command of a pod container -func (p *PodContainer) SetCommand(name string) *PodContainer { - p.Exec = &PodExec{ - Command: PodCommand{ - Shell: name, - }, - } - return p -} - -// CPUs sets the CPUs of a pod container -func (p *PodContainer) CPUs(cpu float64) *PodContainer { - p.Resources.Cpus = cpu - return p -} - -// Memory sets the memory of a pod container -func (p *PodContainer) Memory(memory float64) *PodContainer { - p.Resources.Mem = memory - return p -} - -// Storage sets the storage capacity of a pod container -func (p *PodContainer) Storage(disk float64) *PodContainer { - p.Resources.Disk = disk - return p -} - -// GPUs sets the GPU requirements of a pod container -func (p *PodContainer) GPUs(gpu int32) *PodContainer { - p.Resources.Gpus = gpu - return p -} - -// AddEndpoint appends an endpoint for a pod container -func (p *PodContainer) AddEndpoint(endpoint *PodEndpoint) *PodContainer { - p.Endpoints = append(p.Endpoints, endpoint) - return p -} - -// SetImage sets the image of a pod container -func (p *PodContainer) SetImage(image *PodContainerImage) *PodContainer { - p.Image = image - return p -} - -// EmptyEnvironment initialized env to empty -func (p *PodContainer) EmptyEnvs() *PodContainer { - p.Env = make(map[string]string) - return p -} - -// AddEnvironment adds an environment variable for a pod container -func (p *PodContainer) AddEnv(name, value string) *PodContainer { - if p.Env == nil { - p = p.EmptyEnvs() - } - p.Env[name] = value - return p -} - -// ExtendEnvironment extends the environment for a pod container -func (p *PodContainer) ExtendEnv(env map[string]string) *PodContainer { - if p.Env == nil { - p = p.EmptyEnvs() - } - for k, v := range env { - p.AddEnv(k, v) - } - return p -} - -// AddSecret adds a secret to the environment for a pod container -func (p *PodContainer) AddSecret(name, secretName string) *PodContainer { - if p.Env == nil { - p = p.EmptyEnvs() - } - p.Env[name] = secretName - return p -} - -// SetUser sets the user to run the pod as -func (p *PodContainer) SetUser(user string) *PodContainer { - p.User = user - return p -} - -// SetHealthCheck sets the health check of a pod container -func (p *PodContainer) SetHealthCheck(healthcheck *PodHealthCheck) *PodContainer { - p.HealthCheck = healthcheck - return p -} - -// AddVolumeMount appends a volume mount to a pod container -func (p *PodContainer) AddVolumeMount(mount *PodVolumeMount) *PodContainer { - p.VolumeMounts = append(p.VolumeMounts, mount) - return p -} - -// AddArtifact appends an artifact to a pod container -func (p *PodContainer) AddArtifact(artifact *PodArtifact) *PodContainer { - p.Artifacts = append(p.Artifacts, artifact) - return p -} - -// AddLabel adds a label to a pod container -func (p *PodContainer) AddLabel(key, value string) *PodContainer { - p.Labels[key] = value - return p -} - -// SetLifecycle sets the lifecycle of a pod container -func (p *PodContainer) SetLifecycle(lifecycle PodLifecycle) *PodContainer { - p.Lifecycle = lifecycle - return p -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_container_image.go b/vendor/github.com/gambol99/go-marathon/pod_container_image.go deleted file mode 100644 index 9cc7d41d3..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_container_image.go +++ /dev/null @@ -1,57 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// ImageType represents the image format type -type ImageType string - -const ( - // ImageTypeDocker is the docker format - ImageTypeDocker ImageType = "DOCKER" - - // ImageTypeAppC is the appc format - ImageTypeAppC ImageType = "APPC" -) - -// PodContainerImage describes how to retrieve the container image -type PodContainerImage struct { - Kind ImageType `json:"kind,omitempty"` - ID string `json:"id,omitempty"` - ForcePull bool `json:"forcePull,omitempty"` -} - -// NewPodContainerImage creates an empty PodContainerImage -func NewPodContainerImage() *PodContainerImage { - return &PodContainerImage{} -} - -// SetKind sets the Kind of the image -func (i *PodContainerImage) SetKind(typ ImageType) *PodContainerImage { - i.Kind = typ - return i -} - -// SetID sets the ID of the image -func (i *PodContainerImage) SetID(id string) *PodContainerImage { - i.ID = id - return i -} - -// NewDockerPodContainerImage creates a docker PodContainerImage -func NewDockerPodContainerImage() *PodContainerImage { - return NewPodContainerImage().SetKind(ImageTypeDocker) -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_container_marshalling.go b/vendor/github.com/gambol99/go-marathon/pod_container_marshalling.go deleted file mode 100644 index 917aeac1c..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_container_marshalling.go +++ /dev/null @@ -1,94 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" -) - -// PodContainerAlias aliases the PodContainer struct so that it will be marshaled/unmarshaled automatically -type PodContainerAlias PodContainer - -// UnmarshalJSON unmarshals the given PodContainer JSON as expected except for environment variables and secrets. -// Environment variables are stored in the Env field. Secrets, including the environment variable part, -// are stored in the Secrets field. -func (p *PodContainer) UnmarshalJSON(b []byte) error { - aux := &struct { - *PodContainerAlias - Env map[string]interface{} `json:"environment"` - }{ - PodContainerAlias: (*PodContainerAlias)(p), - } - if err := json.Unmarshal(b, aux); err != nil { - return fmt.Errorf("malformed pod container definition %v", err) - } - env := map[string]string{} - secrets := map[string]Secret{} - - for envName, genericEnvValue := range aux.Env { - switch envValOrSecret := genericEnvValue.(type) { - case string: - env[envName] = envValOrSecret - case map[string]interface{}: - for secret, secretStore := range envValOrSecret { - if secStore, ok := secretStore.(string); ok && secret == "secret" { - secrets[secStore] = Secret{EnvVar: envName} - break - } - return fmt.Errorf("unexpected secret field %v of value type %T", secret, envValOrSecret[secret]) - } - default: - return fmt.Errorf("unexpected environment variable type %T", envValOrSecret) - } - } - p.Env = env - for k, v := range aux.Secrets { - tmp := secrets[k] - tmp.Source = v.Source - secrets[k] = tmp - } - p.Secrets = secrets - return nil -} - -// MarshalJSON marshals the given PodContainer as expected except for environment variables and secrets, -// which are marshaled from specialized structs. The environment variable piece of the secrets and other -// normal environment variables are combined and marshaled to the env field. The secrets and the related -// source are marshaled into the secrets field. -func (p *PodContainer) MarshalJSON() ([]byte, error) { - env := make(map[string]interface{}) - secrets := make(map[string]TmpSecret) - - if p.Env != nil { - for k, v := range p.Env { - env[string(k)] = string(v) - } - } - if p.Secrets != nil { - for k, v := range p.Secrets { - env[v.EnvVar] = TmpEnvSecret{Secret: k} - secrets[k] = TmpSecret{v.Source} - } - } - aux := &struct { - *PodContainerAlias - Env map[string]interface{} `json:"environment,omitempty"` - }{PodContainerAlias: (*PodContainerAlias)(p), Env: env} - - return json.Marshal(aux) -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_instance.go b/vendor/github.com/gambol99/go-marathon/pod_instance.go deleted file mode 100644 index 5df0afa16..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_instance.go +++ /dev/null @@ -1,105 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" - "time" -) - -// PodInstance is the representation of an instance as returned by deleting an instance -type PodInstance struct { - InstanceID PodInstanceID `json:"instanceId"` - AgentInfo PodAgentInfo `json:"agentInfo"` - TasksMap map[string]PodTask `json:"tasksMap"` - RunSpecVersion time.Time `json:"runSpecVersion"` - State PodInstanceStateHistory `json:"state"` - UnreachableStrategy EnabledUnreachableStrategy `json:"unreachableStrategy"` -} - -// PodInstanceStateHistory is the pod instance's state -type PodInstanceStateHistory struct { - Condition PodTaskCondition `json:"condition"` - Since time.Time `json:"since"` - ActiveSince time.Time `json:"activeSince"` -} - -// PodInstanceID contains the instance ID -type PodInstanceID struct { - ID string `json:"idString"` -} - -// PodAgentInfo contains info about the agent the instance is running on -type PodAgentInfo struct { - Host string `json:"host"` - AgentID string `json:"agentId"` - Attributes []string `json:"attributes"` -} - -// PodTask contains the info about the specific task within the instance -type PodTask struct { - TaskID string `json:"taskId"` - RunSpecVersion time.Time `json:"runSpecVersion"` - Status PodTaskStatus `json:"status"` -} - -// PodTaskStatus is the current status of the task -type PodTaskStatus struct { - StagedAt time.Time `json:"stagedAt"` - StartedAt time.Time `json:"startedAt"` - MesosStatus string `json:"mesosStatus"` - Condition PodTaskCondition `json:"condition"` - NetworkInfo PodNetworkInfo `json:"networkInfo"` -} - -// PodTaskCondition contains a string representation of the condition -type PodTaskCondition struct { - Str string `json:"str"` -} - -// PodNetworkInfo contains the network info for a task -type PodNetworkInfo struct { - HostName string `json:"hostName"` - HostPorts []int `json:"hostPorts"` - IPAddresses []IPAddress `json:"ipAddresses"` -} - -// DeletePodInstances deletes all instances of the named pod -func (r *marathonClient) DeletePodInstances(name string, instances []string) ([]*PodInstance, error) { - uri := buildPodInstancesURI(name) - var result []*PodInstance - if err := r.apiDelete(uri, instances, &result); err != nil { - return nil, err - } - - return result, nil -} - -// DeletePodInstance deletes a specific instance of a pod -func (r *marathonClient) DeletePodInstance(name, instance string) (*PodInstance, error) { - uri := fmt.Sprintf("%s/%s", buildPodInstancesURI(name), instance) - result := new(PodInstance) - if err := r.apiDelete(uri, nil, result); err != nil { - return nil, err - } - - return result, nil -} - -func buildPodInstancesURI(path string) string { - return fmt.Sprintf("%s/%s::instances", marathonAPIPods, trimRootPath(path)) -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_instance_status.go b/vendor/github.com/gambol99/go-marathon/pod_instance_status.go deleted file mode 100644 index cc8915599..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_instance_status.go +++ /dev/null @@ -1,89 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PodInstanceState is the state of a specific pod instance -type PodInstanceState string - -const ( - // PodInstanceStatePending is when an instance is pending scheduling - PodInstanceStatePending PodInstanceState = "PENDING" - - // PodInstanceStateStaging is when an instance is staged to be scheduled - PodInstanceStateStaging PodInstanceState = "STAGING" - - // PodInstanceStateStable is when an instance is stably running - PodInstanceStateStable PodInstanceState = "STABLE" - - // PodInstanceStateDegraded is when an instance is degraded status - PodInstanceStateDegraded PodInstanceState = "DEGRADED" - - // PodInstanceStateTerminal is when an instance is terminal - PodInstanceStateTerminal PodInstanceState = "TERMINAL" -) - -// PodInstanceStatus is the status of a pod instance -type PodInstanceStatus struct { - AgentHostname string `json:"agentHostname,omitempty"` - Conditions []*StatusCondition `json:"conditions,omitempty"` - Containers []*ContainerStatus `json:"containers,omitempty"` - ID string `json:"id,omitempty"` - LastChanged string `json:"lastChanged,omitempty"` - LastUpdated string `json:"lastUpdated,omitempty"` - Message string `json:"message,omitempty"` - Networks []*PodNetworkStatus `json:"networks,omitempty"` - Resources *Resources `json:"resources,omitempty"` - SpecReference string `json:"specReference,omitempty"` - Status PodInstanceState `json:"status,omitempty"` - StatusSince string `json:"statusSince,omitempty"` -} - -// PodNetworkStatus is the networks attached to a pod instance -type PodNetworkStatus struct { - Addresses []string `json:"addresses,omitempty"` - Name string `json:"name,omitempty"` -} - -// StatusCondition describes info about a status change -type StatusCondition struct { - Name string `json:"name,omitempty"` - Value string `json:"value,omitempty"` - Reason string `json:"reason,omitempty"` - LastChanged string `json:"lastChanged,omitempty"` - LastUpdated string `json:"lastUpdated,omitempty"` -} - -// ContainerStatus contains all status information for a container instance -type ContainerStatus struct { - Conditions []*StatusCondition `json:"conditions,omitempty"` - ContainerID string `json:"containerId,omitempty"` - Endpoints []*PodEndpoint `json:"endpoints,omitempty"` - LastChanged string `json:"lastChanged,omitempty"` - LastUpdated string `json:"lastUpdated,omitempty"` - Message string `json:"message,omitempty"` - Name string `json:"name,omitempty"` - Resources *Resources `json:"resources,omitempty"` - Status string `json:"status,omitempty"` - StatusSince string `json:"statusSince,omitempty"` - Termination *ContainerTerminationState `json:"termination,omitempty"` -} - -// ContainerTerminationState describes why a container terminated -type ContainerTerminationState struct { - ExitCode int `json:"exitCode,omitempty"` - Message string `json:"message,omitempty"` -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_marshalling.go b/vendor/github.com/gambol99/go-marathon/pod_marshalling.go deleted file mode 100644 index de1cb5f4f..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_marshalling.go +++ /dev/null @@ -1,100 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" -) - -// PodAlias aliases the Pod struct so that it will be marshaled/unmarshaled automatically -type PodAlias Pod - -// UnmarshalJSON unmarshals the given Pod JSON as expected except for environment variables and secrets. -// Environment variables are stored in the Env field. Secrets, including the environment variable part, -// are stored in the Secrets field. -func (p *Pod) UnmarshalJSON(b []byte) error { - aux := &struct { - *PodAlias - Env map[string]interface{} `json:"environment"` - Secrets map[string]TmpSecret `json:"secrets"` - }{ - PodAlias: (*PodAlias)(p), - } - if err := json.Unmarshal(b, aux); err != nil { - return fmt.Errorf("malformed pod definition %v", err) - } - env := map[string]string{} - secrets := map[string]Secret{} - - for envName, genericEnvValue := range aux.Env { - switch envValOrSecret := genericEnvValue.(type) { - case string: - env[envName] = envValOrSecret - case map[string]interface{}: - for secret, secretStore := range envValOrSecret { - if secStore, ok := secretStore.(string); ok && secret == "secret" { - secrets[secStore] = Secret{EnvVar: envName} - break - } - return fmt.Errorf("unexpected secret field %v of value type %T", secret, envValOrSecret[secret]) - } - default: - return fmt.Errorf("unexpected environment variable type %T", envValOrSecret) - } - } - p.Env = env - for k, v := range aux.Secrets { - tmp := secrets[k] - tmp.Source = v.Source - secrets[k] = tmp - } - p.Secrets = secrets - return nil -} - -// MarshalJSON marshals the given Pod as expected except for environment variables and secrets, -// which are marshaled from specialized structs. The environment variable piece of the secrets and other -// normal environment variables are combined and marshaled to the env field. The secrets and the related -// source are marshaled into the secrets field. -func (p *Pod) MarshalJSON() ([]byte, error) { - env := make(map[string]interface{}) - secrets := make(map[string]TmpSecret) - - if p.Env != nil { - for k, v := range p.Env { - env[string(k)] = string(v) - } - } - if p.Secrets != nil { - for k, v := range p.Secrets { - // Only add it to the root level pod environment if it's used - // Otherwise it's likely in one of the container environments - if v.EnvVar != "" { - env[v.EnvVar] = TmpEnvSecret{Secret: k} - } - secrets[k] = TmpSecret{v.Source} - } - } - aux := &struct { - *PodAlias - Env map[string]interface{} `json:"environment,omitempty"` - Secrets map[string]TmpSecret `json:"secrets,omitempty"` - }{PodAlias: (*PodAlias)(p), Env: env, Secrets: secrets} - - return json.Marshal(aux) -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_scheduling.go b/vendor/github.com/gambol99/go-marathon/pod_scheduling.go deleted file mode 100644 index a63ce42d4..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_scheduling.go +++ /dev/null @@ -1,75 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PodBackoff describes the backoff for re-run attempts of a pod -type PodBackoff struct { - Backoff *int `json:"backoff,omitempty"` - BackoffFactor *float64 `json:"backoffFactor,omitempty"` - MaxLaunchDelay *int `json:"maxLaunchDelay,omitempty"` -} - -// PodUpgrade describes the policy for upgrading a pod in-place -type PodUpgrade struct { - MinimumHealthCapacity *float64 `json:"minimumHealthCapacity,omitempty"` - MaximumOverCapacity *float64 `json:"maximumOverCapacity,omitempty"` -} - -// PodPlacement supports constraining which hosts a pod is placed on -type PodPlacement struct { - Constraints *[]Constraint `json:"constraints"` - AcceptedResourceRoles []string `json:"acceptedResourceRoles,omitempty"` -} - -// PodSchedulingPolicy is the overarching pod scheduling policy -type PodSchedulingPolicy struct { - Backoff *PodBackoff `json:"backoff,omitempty"` - Upgrade *PodUpgrade `json:"upgrade,omitempty"` - Placement *PodPlacement `json:"placement,omitempty"` -} - -// Constraint describes the constraint for pod placement -type Constraint struct { - FieldName string `json:"fieldName"` - Operator string `json:"operator"` - Value string `json:"value,omitempty"` -} - -// NewPodPlacement creates an empty PodPlacement -func NewPodPlacement() *PodPlacement { - return &PodPlacement{ - Constraints: &[]Constraint{}, - AcceptedResourceRoles: []string{}, - } -} - -// AddConstraint adds a new constraint -// constraints: the constraint definition, one constraint per array element -func (r *PodPlacement) AddConstraint(constraint Constraint) *PodPlacement { - c := *r.Constraints - c = append(c, constraint) - r.Constraints = &c - - return r -} - -// NewPodSchedulingPolicy creates an empty PodSchedulingPolicy -func NewPodSchedulingPolicy() *PodSchedulingPolicy { - return &PodSchedulingPolicy{ - Placement: NewPodPlacement(), - } -} diff --git a/vendor/github.com/gambol99/go-marathon/pod_status.go b/vendor/github.com/gambol99/go-marathon/pod_status.go deleted file mode 100644 index 227868ef4..000000000 --- a/vendor/github.com/gambol99/go-marathon/pod_status.go +++ /dev/null @@ -1,108 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" - "time" -) - -// PodState defines the state of a pod -type PodState string - -const ( - // PodStateDegraded is a degraded pod - PodStateDegraded PodState = "DEGRADED" - - // PodStateStable is a stable pod - PodStateStable PodState = "STABLE" - - // PodStateTerminal is a terminal pod - PodStateTerminal PodState = "TERMINAL" -) - -// PodStatus describes the pod status -type PodStatus struct { - ID string `json:"id,omitempty"` - Spec *Pod `json:"spec,omitempty"` - Status PodState `json:"status,omitempty"` - StatusSince string `json:"statusSince,omitempty"` - Message string `json:"message,omitempty"` - Instances []*PodInstanceStatus `json:"instances,omitempty"` - TerminationHistory []*PodTerminationHistory `json:"terminationHistory,omitempty"` - LastUpdated string `json:"lastUpdated,omitempty"` - LastChanged string `json:"lastChanged,omitempty"` -} - -// PodTerminationHistory is the termination history of the pod -type PodTerminationHistory struct { - InstanceID string `json:"instanceId,omitempty"` - StartedAt string `json:"startedAt,omitempty"` - TerminatedAt string `json:"terminatedAt,omitempty"` - Message string `json:"message,omitempty"` - Containers []*ContainerTerminationHistory `json:"containers,omitempty"` -} - -// ContainerTerminationHistory is the termination history of a container in a pod -type ContainerTerminationHistory struct { - ContainerID string `json:"containerId,omitempty"` - LastKnownState string `json:"lastKnownState,omitempty"` - Termination *ContainerTerminationState `json:"termination,omitempty"` -} - -// PodStatus retrieves the pod configuration from marathon -func (r *marathonClient) PodStatus(name string) (*PodStatus, error) { - var podStatus PodStatus - - if err := r.apiGet(buildPodStatusURI(name), nil, &podStatus); err != nil { - return nil, err - } - - return &podStatus, nil -} - -// PodStatuses retrieves all pod configuration from marathon -func (r *marathonClient) PodStatuses() ([]*PodStatus, error) { - var podStatuses []*PodStatus - - if err := r.apiGet(buildPodStatusURI(""), nil, &podStatuses); err != nil { - return nil, err - } - - return podStatuses, nil -} - -// WaitOnPod blocks until a pod to be deployed -func (r *marathonClient) WaitOnPod(name string, timeout time.Duration) error { - return r.wait(name, timeout, r.PodIsRunning) -} - -// PodIsRunning returns whether the pod is stably running -func (r *marathonClient) PodIsRunning(name string) bool { - podStatus, err := r.PodStatus(name) - if apiErr, ok := err.(*APIError); ok && apiErr.ErrCode == ErrCodeNotFound { - return false - } - if err == nil && podStatus.Status == PodStateStable { - return true - } - return false -} - -func buildPodStatusURI(path string) string { - return fmt.Sprintf("%s/%s::status", marathonAPIPods, trimRootPath(path)) -} diff --git a/vendor/github.com/gambol99/go-marathon/port_definition.go b/vendor/github.com/gambol99/go-marathon/port_definition.go deleted file mode 100644 index 6a5dc6d95..000000000 --- a/vendor/github.com/gambol99/go-marathon/port_definition.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2016 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PortDefinition is a definition of a port that should be considered -// part of a resource. Port definitions are necessary when you are -// using HOST networking and no port mappings are specified. -type PortDefinition struct { - Port *int `json:"port,omitempty"` - Protocol string `json:"protocol,omitempty"` - Name string `json:"name,omitempty"` - Labels *map[string]string `json:"labels,omitempty"` -} - -// SetPort sets the given port for the PortDefinition -func (p *PortDefinition) SetPort(port int) *PortDefinition { - if p.Port == nil { - p.EmptyPort() - } - p.Port = &port - return p -} - -// EmptyPort sets the port to 0 for the PortDefinition -func (p *PortDefinition) EmptyPort() *PortDefinition { - port := 0 - p.Port = &port - return p -} - -// SetProtocol sets the protocol for the PortDefinition -// protocol: the protocol as a string -func (p *PortDefinition) SetProtocol(protocol string) *PortDefinition { - p.Protocol = protocol - return p -} - -// SetName sets the name for the PortDefinition -// name: the name of the PortDefinition -func (p *PortDefinition) SetName(name string) *PortDefinition { - p.Name = name - return p -} - -// AddLabel adds a label to the PortDefinition -// name: the name of the label -// value: value for this label -func (p *PortDefinition) AddLabel(name, value string) *PortDefinition { - if p.Labels == nil { - p.EmptyLabels() - } - (*p.Labels)[name] = value - - return p -} - -// EmptyLabels explicitly empties the labels -- use this if you need to empty -// the labels of a PortDefinition that already has labels set -// (setting labels to nill will keep the current value) -func (p *PortDefinition) EmptyLabels() *PortDefinition { - p.Labels = &map[string]string{} - - return p -} diff --git a/vendor/github.com/gambol99/go-marathon/queue.go b/vendor/github.com/gambol99/go-marathon/queue.go deleted file mode 100644 index b9cfa4827..000000000 --- a/vendor/github.com/gambol99/go-marathon/queue.go +++ /dev/null @@ -1,56 +0,0 @@ -/* -Copyright 2016 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" -) - -// Queue is the definition of marathon queue -type Queue struct { - Items []Item `json:"queue"` -} - -// Item is the definition of element in the queue -type Item struct { - Count int `json:"count"` - Delay Delay `json:"delay"` - Application Application `json:"app"` -} - -// Delay cotains the application postpone information -type Delay struct { - Overdue bool `json:"overdue"` - TimeLeftSeconds int `json:"timeLeftSeconds"` -} - -// Queue retrieves content of the marathon launch queue -func (r *marathonClient) Queue() (*Queue, error) { - var queue *Queue - err := r.apiGet(marathonAPIQueue, nil, &queue) - if err != nil { - return nil, err - } - return queue, nil -} - -// DeleteQueueDelay resets task launch delay of the specific application -// appID: the ID of the application -func (r *marathonClient) DeleteQueueDelay(appID string) error { - path := fmt.Sprintf("%s/%s/delay", marathonAPIQueue, trimRootPath(appID)) - return r.apiDelete(path, nil, nil) -} diff --git a/vendor/github.com/gambol99/go-marathon/readiness.go b/vendor/github.com/gambol99/go-marathon/readiness.go deleted file mode 100644 index ffb0aa149..000000000 --- a/vendor/github.com/gambol99/go-marathon/readiness.go +++ /dev/null @@ -1,99 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import "time" - -// ReadinessCheck represents a readiness check. -type ReadinessCheck struct { - Name *string `json:"name,omitempty"` - Protocol string `json:"protocol,omitempty"` - Path string `json:"path,omitempty"` - PortName string `json:"portName,omitempty"` - IntervalSeconds int `json:"intervalSeconds,omitempty"` - TimeoutSeconds int `json:"timeoutSeconds,omitempty"` - HTTPStatusCodesForReady *[]int `json:"httpStatusCodesForReady,omitempty"` - PreserveLastResponse *bool `json:"preserveLastResponse,omitempty"` -} - -// SetName sets the name on the readiness check. -func (rc *ReadinessCheck) SetName(name string) *ReadinessCheck { - rc.Name = &name - return rc -} - -// SetProtocol sets the protocol on the readiness check. -func (rc *ReadinessCheck) SetProtocol(proto string) *ReadinessCheck { - rc.Protocol = proto - return rc -} - -// SetPath sets the path on the readiness check. -func (rc *ReadinessCheck) SetPath(p string) *ReadinessCheck { - rc.Path = p - return rc -} - -// SetPortName sets the port name on the readiness check. -func (rc *ReadinessCheck) SetPortName(name string) *ReadinessCheck { - rc.PortName = name - return rc -} - -// SetInterval sets the interval on the readiness check. -func (rc *ReadinessCheck) SetInterval(interval time.Duration) *ReadinessCheck { - secs := int(interval.Seconds()) - rc.IntervalSeconds = secs - return rc -} - -// SetTimeout sets the timeout on the readiness check. -func (rc *ReadinessCheck) SetTimeout(timeout time.Duration) *ReadinessCheck { - secs := int(timeout.Seconds()) - rc.TimeoutSeconds = secs - return rc -} - -// SetHTTPStatusCodesForReady sets the HTTP status codes for ready on the -// readiness check. -func (rc *ReadinessCheck) SetHTTPStatusCodesForReady(codes []int) *ReadinessCheck { - rc.HTTPStatusCodesForReady = &codes - return rc -} - -// SetPreserveLastResponse sets the preserve last response flag on the -// readiness check. -func (rc *ReadinessCheck) SetPreserveLastResponse(preserve bool) *ReadinessCheck { - rc.PreserveLastResponse = &preserve - return rc -} - -// ReadinessLastResponse holds the result of the last response embedded in a -// readiness check result. -type ReadinessLastResponse struct { - Body string `json:"body"` - ContentType string `json:"contentType"` - Status int `json:"status"` -} - -// ReadinessCheckResult is the result of a readiness check. -type ReadinessCheckResult struct { - Name string `json:"name"` - TaskID string `json:"taskId"` - Ready bool `json:"ready"` - LastResponse ReadinessLastResponse `json:"lastResponse,omitempty"` -} diff --git a/vendor/github.com/gambol99/go-marathon/residency.go b/vendor/github.com/gambol99/go-marathon/residency.go deleted file mode 100644 index 9fc94cea4..000000000 --- a/vendor/github.com/gambol99/go-marathon/residency.go +++ /dev/null @@ -1,48 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import "time" - -// TaskLostBehaviorType sets action taken when the resident task is lost -type TaskLostBehaviorType string - -const ( - // TaskLostBehaviorTypeWaitForever indicates to not take any action when the resident task is lost - TaskLostBehaviorTypeWaitForever TaskLostBehaviorType = "WAIT_FOREVER" - // TaskLostBehaviorTypeRelaunchAfterTimeout indicates to try relaunching the lost resident task on - // another node after the relaunch escalation timeout has elapsed - TaskLostBehaviorTypeRelaunchAfterTimeout TaskLostBehaviorType = "RELAUNCH_AFTER_TIMEOUT" -) - -// Residency defines how terminal states of tasks with local persistent volumes are handled -type Residency struct { - TaskLostBehavior TaskLostBehaviorType `json:"taskLostBehavior,omitempty"` - RelaunchEscalationTimeoutSeconds int `json:"relaunchEscalationTimeoutSeconds,omitempty"` -} - -// SetTaskLostBehavior sets the residency behavior -func (r *Residency) SetTaskLostBehavior(behavior TaskLostBehaviorType) *Residency { - r.TaskLostBehavior = behavior - return r -} - -// SetRelaunchEscalationTimeout sets the residency relaunch escalation timeout with seconds precision -func (r *Residency) SetRelaunchEscalationTimeout(timeout time.Duration) *Residency { - r.RelaunchEscalationTimeoutSeconds = int(timeout.Seconds()) - return r -} diff --git a/vendor/github.com/gambol99/go-marathon/resources.go b/vendor/github.com/gambol99/go-marathon/resources.go deleted file mode 100644 index a2aaeed06..000000000 --- a/vendor/github.com/gambol99/go-marathon/resources.go +++ /dev/null @@ -1,37 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// ExecutorResources are the resources supported by an executor (a task running a pod) -type ExecutorResources struct { - Cpus float64 `json:"cpus,omitempty"` - Mem float64 `json:"mem,omitempty"` - Disk float64 `json:"disk,omitempty"` -} - -// Resources are the full set of resources for a task -type Resources struct { - Cpus float64 `json:"cpus"` - Mem float64 `json:"mem"` - Disk float64 `json:"disk,omitempty"` - Gpus int32 `json:"gpus,omitempty"` -} - -// NewResources creates an empty Resources -func NewResources() *Resources { - return &Resources{} -} diff --git a/vendor/github.com/gambol99/go-marathon/subscription.go b/vendor/github.com/gambol99/go-marathon/subscription.go deleted file mode 100644 index 561026f28..000000000 --- a/vendor/github.com/gambol99/go-marathon/subscription.go +++ /dev/null @@ -1,336 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net" - "net/http" - "strings" - "sync" - "time" - - "github.com/donovanhide/eventsource" -) - -// Subscriptions is a collection to urls that marathon is implementing a callback on -type Subscriptions struct { - CallbackURLs []string `json:"callbackUrls"` -} - -// Subscriptions retrieves a list of registered subscriptions -func (r *marathonClient) Subscriptions() (*Subscriptions, error) { - subscriptions := new(Subscriptions) - if err := r.apiGet(marathonAPISubscription, nil, subscriptions); err != nil { - return nil, err - } - - return subscriptions, nil -} - -// AddEventsListener adds your self as a listener to events from Marathon -// channel: a EventsChannel used to receive event on -func (r *marathonClient) AddEventsListener(filter int) (EventsChannel, error) { - r.Lock() - defer r.Unlock() - - // step: someone has asked to start listening to event, we need to register for events - // if we haven't done so already - if err := r.registerSubscription(); err != nil { - return nil, err - } - - channel := make(EventsChannel) - r.listeners[channel] = EventsChannelContext{ - filter: filter, - done: make(chan struct{}, 1), - completion: &sync.WaitGroup{}, - } - return channel, nil -} - -// RemoveEventsListener removes the channel from the events listeners -// channel: the channel you are removing -func (r *marathonClient) RemoveEventsListener(channel EventsChannel) { - r.Lock() - defer r.Unlock() - - if context, found := r.listeners[channel]; found { - close(context.done) - delete(r.listeners, channel) - // step: if there is no one else listening, let's remove ourselves - // from the events callback - if r.config.EventsTransport == EventsTransportCallback && len(r.listeners) == 0 { - r.Unsubscribe(r.SubscriptionURL()) - } - - // step: wait for pending goroutines to finish and close channel - go func(completion *sync.WaitGroup) { - completion.Wait() - close(channel) - }(context.completion) - } -} - -// SubscriptionURL retrieves the subscription callback URL used when registering -func (r *marathonClient) SubscriptionURL() string { - if r.config.CallbackURL != "" { - return fmt.Sprintf("%s%s", r.config.CallbackURL, defaultEventsURL) - } - - return fmt.Sprintf("http://%s:%d%s", r.ipAddress, r.config.EventsPort, defaultEventsURL) -} - -// registerSubscription registers ourselves with Marathon to receive events from configured transport facility -func (r *marathonClient) registerSubscription() error { - switch r.config.EventsTransport { - case EventsTransportCallback: - return r.registerCallbackSubscription() - case EventsTransportSSE: - return r.registerSSESubscription() - default: - return fmt.Errorf("the events transport: %d is not supported", r.config.EventsTransport) - } -} - -func (r *marathonClient) registerCallbackSubscription() error { - if r.eventsHTTP == nil { - ipAddress, err := getInterfaceAddress(r.config.EventsInterface) - if err != nil { - return fmt.Errorf("Unable to get the ip address from the interface: %s, error: %s", - r.config.EventsInterface, err) - } - - // step: set the ip address - r.ipAddress = ipAddress - binding := fmt.Sprintf("%s:%d", ipAddress, r.config.EventsPort) - // step: register the handler - http.HandleFunc(defaultEventsURL, r.handleCallbackEvent) - // step: create the http server - r.eventsHTTP = &http.Server{ - Addr: binding, - Handler: nil, - ReadTimeout: 10 * time.Second, - WriteTimeout: 10 * time.Second, - MaxHeaderBytes: 1 << 20, - } - - // @todo need to add a timeout value here - listener, err := net.Listen("tcp", binding) - if err != nil { - return nil - } - - go func() { - for { - r.eventsHTTP.Serve(listener) - } - }() - } - - // step: get the callback url - callback := r.SubscriptionURL() - - // step: check if the callback is registered - found, err := r.HasSubscription(callback) - if err != nil { - return err - } - if !found { - // step: we need to register ourselves - if err := r.Subscribe(callback); err != nil { - return err - } - } - - return nil -} - -// registerSSESubscription starts a go routine that continuously tries to -// connect to the SSE stream and to process the received events. To establish -// the connection it tries the active cluster members until no more member is -// active. When this happens it will retry to get a connection every 5 seconds. -func (r *marathonClient) registerSSESubscription() error { - if r.subscribedToSSE { - return nil - } - - if r.config.HTTPSSEClient.Timeout != 0 { - return fmt.Errorf( - "global timeout must not be set for SSE connections (found %s) -- remove global timeout from HTTP client or provide separate SSE HTTP client without global timeout", - r.config.HTTPSSEClient.Timeout, - ) - } - - go func() { - for { - stream, err := r.connectToSSE() - if err != nil { - r.debugLog("Error connecting SSE subscription: %s", err) - <-time.After(5 * time.Second) - continue - } - err = r.listenToSSE(stream) - stream.Close() - r.debugLog("Error on SSE subscription: %s", err) - } - }() - - r.subscribedToSSE = true - return nil -} - -// connectToSSE tries to establish an *eventsource.Stream to any of the Marathon cluster members, marking the -// member as down on connection failure, until there is no more active member in the cluster. -// Given the http request can not be built, it will panic as this case should never happen. -func (r *marathonClient) connectToSSE() (*eventsource.Stream, error) { - for { - request, member, err := r.buildAPIRequest("GET", marathonAPIEventStream, nil) - if err != nil { - switch err.(type) { - case newRequestError: - panic(fmt.Sprintf("Requests for SSE subscriptions should never fail to be created: %s", err.Error())) - default: - return nil, err - } - } - - // The event source library manipulates the HTTPClient. So we create a new one and copy - // its underlying fields for performance reasons. See note that at least the Transport - // should be reused here: https://golang.org/pkg/net/http/#Client - httpClient := &http.Client{ - Transport: r.config.HTTPSSEClient.Transport, - CheckRedirect: r.config.HTTPSSEClient.CheckRedirect, - Jar: r.config.HTTPSSEClient.Jar, - Timeout: r.config.HTTPSSEClient.Timeout, - } - - stream, err := eventsource.SubscribeWith("", httpClient, request) - if err != nil { - r.debugLog("Error subscribing to Marathon event stream: %s", err) - r.hosts.markDown(member) - continue - } - - return stream, nil - } -} - -func (r *marathonClient) listenToSSE(stream *eventsource.Stream) error { - for { - select { - case ev := <-stream.Events: - if err := r.handleEvent(ev.Data()); err != nil { - r.debugLog("listenToSSE(): failed to handle event: %v", err) - } - case err := <-stream.Errors: - return err - - } - } -} - -// Subscribe adds a URL to Marathon's callback facility -// callback : the URL you wish to subscribe -func (r *marathonClient) Subscribe(callback string) error { - path := fmt.Sprintf("%s?callbackUrl=%s", marathonAPISubscription, callback) - return r.apiPost(path, "", nil) - -} - -// Unsubscribe removes a URL from Marathon's callback facility -// callback : the URL you wish to unsubscribe -func (r *marathonClient) Unsubscribe(callback string) error { - // step: remove from the list of subscriptions - return r.apiDelete(fmt.Sprintf("%s?callbackUrl=%s", marathonAPISubscription, callback), nil, nil) -} - -// HasSubscription checks to see a subscription already exists with Marathon -// callback: the url of the callback -func (r *marathonClient) HasSubscription(callback string) (bool, error) { - // step: generate our events callback - subscriptions, err := r.Subscriptions() - if err != nil { - return false, err - } - - for _, subscription := range subscriptions.CallbackURLs { - if callback == subscription { - return true, nil - } - } - - return false, nil -} - -func (r *marathonClient) handleEvent(content string) error { - // step: process and decode the event - eventType := new(EventType) - err := json.NewDecoder(strings.NewReader(content)).Decode(eventType) - if err != nil { - return fmt.Errorf("failed to decode the event type, content: %s, error: %s", content, err) - } - - // step: check whether event type is handled - event, err := GetEvent(eventType.EventType) - if err != nil { - return fmt.Errorf("unable to handle event, type: %s, error: %s", eventType.EventType, err) - } - - // step: let's decode message - err = json.NewDecoder(strings.NewReader(content)).Decode(event.Event) - if err != nil { - return fmt.Errorf("failed to decode the event, id: %d, error: %s", event.ID, err) - } - - r.RLock() - defer r.RUnlock() - - // step: check if anyone is listen for this event - for channel, context := range r.listeners { - // step: check if this listener wants this event type - if event.ID&context.filter != 0 { - context.completion.Add(1) - go func(ch EventsChannel, context EventsChannelContext, e *Event) { - defer context.completion.Done() - select { - case ch <- e: - case <-context.done: - // Terminates goroutine. - } - }(channel, context, event) - } - } - - return nil -} - -func (r *marathonClient) handleCallbackEvent(writer http.ResponseWriter, request *http.Request) { - body, err := ioutil.ReadAll(request.Body) - if err != nil { - // TODO should this return a 500? - r.debugLog("handleCallbackEvent(): failed to read request body, error: %s", err) - return - } - - if err := r.handleEvent(string(body[:])); err != nil { - // TODO should this return a 500? - r.debugLog("handleCallbackEvent(): failed to handle event: %v", err) - } -} diff --git a/vendor/github.com/gambol99/go-marathon/task.go b/vendor/github.com/gambol99/go-marathon/task.go deleted file mode 100644 index e17cf24ed..000000000 --- a/vendor/github.com/gambol99/go-marathon/task.go +++ /dev/null @@ -1,229 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "fmt" - "strings" -) - -// Tasks is a collection of marathon tasks -type Tasks struct { - Tasks []Task `json:"tasks"` -} - -// Task is the definition for a marathon task -type Task struct { - ID string `json:"id"` - AppID string `json:"appId"` - Host string `json:"host"` - HealthCheckResults []*HealthCheckResult `json:"healthCheckResults"` - Ports []int `json:"ports"` - ServicePorts []int `json:"servicePorts"` - SlaveID string `json:"slaveId"` - StagedAt string `json:"stagedAt"` - StartedAt string `json:"startedAt"` - State string `json:"state"` - IPAddresses []*IPAddress `json:"ipAddresses"` - Version string `json:"version"` -} - -// IPAddress represents a task's IP address and protocol. -type IPAddress struct { - IPAddress string `json:"ipAddress"` - Protocol string `json:"protocol"` -} - -// AllTasksOpts contains a payload for AllTasks method -// status: Return only those tasks whose status matches this parameter. -// If not specified, all tasks are returned. Possible values: running, staging. Default: none. -type AllTasksOpts struct { - Status string `url:"status,omitempty"` -} - -// KillApplicationTasksOpts contains a payload for KillApplicationTasks method -// host: kill only those tasks on a specific host (optional) -// scale: Scale the app down (i.e. decrement its instances setting by the number of tasks killed) after killing the specified tasks -type KillApplicationTasksOpts struct { - Host string `url:"host,omitempty"` - Scale bool `url:"scale,omitempty"` - Force bool `url:"force,omitempty"` -} - -// KillTaskOpts contains a payload for task killing methods -// scale: Scale the app down -type KillTaskOpts struct { - Scale bool `url:"scale,omitempty"` - Force bool `url:"force,omitempty"` -} - -// HasHealthCheckResults checks if the task has any health checks -func (r *Task) HasHealthCheckResults() bool { - return r.HealthCheckResults != nil && len(r.HealthCheckResults) > 0 -} - -// AllTasks lists tasks of all applications. -// opts: AllTasksOpts request payload -func (r *marathonClient) AllTasks(opts *AllTasksOpts) (*Tasks, error) { - path, err := addOptions(marathonAPITasks, opts) - if err != nil { - return nil, err - } - - tasks := new(Tasks) - if err := r.apiGet(path, nil, tasks); err != nil { - return nil, err - } - - return tasks, nil -} - -// Tasks retrieves a list of tasks for an application -// id: the id of the application -func (r *marathonClient) Tasks(id string) (*Tasks, error) { - tasks := new(Tasks) - if err := r.apiGet(fmt.Sprintf("%s/%s/tasks", marathonAPIApps, trimRootPath(id)), nil, tasks); err != nil { - return nil, err - } - - return tasks, nil -} - -// KillApplicationTasks kills all tasks relating to an application -// id: the id of the application -// opts: KillApplicationTasksOpts request payload -func (r *marathonClient) KillApplicationTasks(id string, opts *KillApplicationTasksOpts) (*Tasks, error) { - path := fmt.Sprintf("%s/%s/tasks", marathonAPIApps, trimRootPath(id)) - path, err := addOptions(path, opts) - if err != nil { - return nil, err - } - - tasks := new(Tasks) - if err := r.apiDelete(path, nil, tasks); err != nil { - return nil, err - } - - return tasks, nil -} - -// KillTask kills the task associated with a given ID -// taskID: the id for the task -// opts: KillTaskOpts request payload -func (r *marathonClient) KillTask(taskID string, opts *KillTaskOpts) (*Task, error) { - appName := taskID[0:strings.LastIndex(taskID, ".")] - appName = strings.Replace(appName, "_", "/", -1) - taskID = strings.Replace(taskID, "/", "_", -1) - - path := fmt.Sprintf("%s/%s/tasks/%s", marathonAPIApps, appName, taskID) - path, err := addOptions(path, opts) - if err != nil { - return nil, err - } - - wrappedTask := new(struct { - Task Task `json:"task"` - }) - - if err := r.apiDelete(path, nil, wrappedTask); err != nil { - return nil, err - } - - return &wrappedTask.Task, nil -} - -// KillTasks kills tasks associated with given array of ids -// tasks: the array of task ids -// opts: KillTaskOpts request payload -func (r *marathonClient) KillTasks(tasks []string, opts *KillTaskOpts) error { - path := fmt.Sprintf("%s/delete", marathonAPITasks) - path, err := addOptions(path, opts) - if err != nil { - return nil - } - - var post struct { - IDs []string `json:"ids"` - } - post.IDs = tasks - - return r.apiPost(path, &post, nil) -} - -// TaskEndpoints gets the endpoints i.e. HOST_IP:DYNAMIC_PORT for a specific application service -// I.e. a container running apache, might have ports 80/443 (translated to X dynamic ports), but i want -// port 80 only and i only want those whom have passed the health check -// -// Note: I've NO IDEA how to associate the health_check_result to the actual port, I don't think it's -// possible at the moment, however, given marathon will fail and restart an application even if one of x ports of a task is -// down, the per port check is redundant??? .. personally, I like it anyhow, but hey -// - -// name: the identifier for the application -// port: the container port you are interested in -// health: whether to check the health or not -func (r *marathonClient) TaskEndpoints(name string, port int, healthCheck bool) ([]string, error) { - // step: get the application details - application, err := r.Application(name) - if err != nil { - return nil, err - } - - // step: we need to get the port index of the service we are interested in - portIndex, err := application.Container.Docker.ServicePortIndex(port) - if err != nil { - portIndex, err = application.Container.ServicePortIndex(port) - if err != nil { - return nil, err - } - } - - // step: do we have any tasks? - if application.Tasks == nil || len(application.Tasks) == 0 { - return nil, nil - } - - // step: if we are checking health the 'service' has a health check? - healthCheck = healthCheck && application.HasHealthChecks() - - // step: iterate the tasks and extract the dynamic ports - var list []string - for _, task := range application.Tasks { - if !healthCheck || task.allHealthChecksAlive() { - endpoint := fmt.Sprintf("%s:%d", task.Host, task.Ports[portIndex]) - list = append(list, endpoint) - } - } - - return list, nil -} - -func (r *Task) allHealthChecksAlive() bool { - // check: does the task have a health check result, if NOT, it's because the - // health of the task hasn't yet been performed, hence we assume it as DOWN - if !r.HasHealthCheckResults() { - return false - } - // step: check the health results then - for _, check := range r.HealthCheckResults { - if !check.Alive { - return false - } - } - - return true -} diff --git a/vendor/github.com/gambol99/go-marathon/unreachable_strategy.go b/vendor/github.com/gambol99/go-marathon/unreachable_strategy.go deleted file mode 100644 index 6563239ab..000000000 --- a/vendor/github.com/gambol99/go-marathon/unreachable_strategy.go +++ /dev/null @@ -1,78 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "encoding/json" - "fmt" -) - -// UnreachableStrategyAbsenceReasonDisabled signifies the reason of disabled unreachable strategy -const UnreachableStrategyAbsenceReasonDisabled = "disabled" - -// UnreachableStrategy is the unreachable strategy applied to an application. -type UnreachableStrategy struct { - EnabledUnreachableStrategy - AbsenceReason string -} - -// EnabledUnreachableStrategy covers parameters pertaining to present unreachable strategies. -type EnabledUnreachableStrategy struct { - InactiveAfterSeconds *float64 `json:"inactiveAfterSeconds,omitempty"` - ExpungeAfterSeconds *float64 `json:"expungeAfterSeconds,omitempty"` -} - -type unreachableStrategy UnreachableStrategy - -// UnmarshalJSON unmarshals the given JSON into an UnreachableStrategy. It -// populates parameters for present strategies, and otherwise only sets the -// absence reason. -func (us *UnreachableStrategy) UnmarshalJSON(b []byte) error { - var u unreachableStrategy - var errEnabledUS, errNonEnabledUS error - if errEnabledUS = json.Unmarshal(b, &u); errEnabledUS == nil { - *us = UnreachableStrategy(u) - return nil - } - - if errNonEnabledUS = json.Unmarshal(b, &us.AbsenceReason); errNonEnabledUS == nil { - return nil - } - - return fmt.Errorf("failed to unmarshal unreachable strategy: unmarshaling into enabled returned error '%s'; unmarshaling into non-enabled returned error '%s'", errEnabledUS, errNonEnabledUS) -} - -// MarshalJSON marshals the unreachable strategy. -func (us *UnreachableStrategy) MarshalJSON() ([]byte, error) { - if us.AbsenceReason == "" { - return json.Marshal(us.EnabledUnreachableStrategy) - } - - return json.Marshal(us.AbsenceReason) -} - -// SetInactiveAfterSeconds sets the period after which instance will be marked as inactive. -func (us *UnreachableStrategy) SetInactiveAfterSeconds(cap float64) *UnreachableStrategy { - us.InactiveAfterSeconds = &cap - return us -} - -// SetExpungeAfterSeconds sets the period after which instance will be expunged. -func (us *UnreachableStrategy) SetExpungeAfterSeconds(cap float64) *UnreachableStrategy { - us.ExpungeAfterSeconds = &cap - return us -} diff --git a/vendor/github.com/gambol99/go-marathon/upgrade_strategy.go b/vendor/github.com/gambol99/go-marathon/upgrade_strategy.go deleted file mode 100644 index d4d7598a6..000000000 --- a/vendor/github.com/gambol99/go-marathon/upgrade_strategy.go +++ /dev/null @@ -1,35 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// UpgradeStrategy is the upgrade strategy applied to an application. -type UpgradeStrategy struct { - MinimumHealthCapacity *float64 `json:"minimumHealthCapacity,omitempty"` - MaximumOverCapacity *float64 `json:"maximumOverCapacity,omitempty"` -} - -// SetMinimumHealthCapacity sets the minimum health capacity. -func (us *UpgradeStrategy) SetMinimumHealthCapacity(cap float64) *UpgradeStrategy { - us.MinimumHealthCapacity = &cap - return us -} - -// SetMaximumOverCapacity sets the maximum over capacity. -func (us *UpgradeStrategy) SetMaximumOverCapacity(cap float64) *UpgradeStrategy { - us.MaximumOverCapacity = &cap - return us -} diff --git a/vendor/github.com/gambol99/go-marathon/utils.go b/vendor/github.com/gambol99/go-marathon/utils.go deleted file mode 100644 index 718d57bb4..000000000 --- a/vendor/github.com/gambol99/go-marathon/utils.go +++ /dev/null @@ -1,135 +0,0 @@ -/* -Copyright 2014 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -import ( - "errors" - "fmt" - "net" - "net/url" - "reflect" - "strings" - "sync/atomic" - "time" - - "github.com/google/go-querystring/query" -) - -type atomicSwitch int64 - -func (r *atomicSwitch) IsSwitched() bool { - return atomic.LoadInt64((*int64)(r)) != 0 -} - -func (r *atomicSwitch) SwitchOn() { - atomic.StoreInt64((*int64)(r), 1) -} - -func (r *atomicSwitch) SwitchedOff() { - atomic.StoreInt64((*int64)(r), 0) -} - -func validateID(id string) string { - if !strings.HasPrefix(id, "/") { - return fmt.Sprintf("/%s", id) - } - return id -} - -func trimRootPath(id string) string { - if strings.HasPrefix(id, "/") { - return strings.TrimPrefix(id, "/") - } - return id -} - -func deadline(timeout time.Duration, work func(chan bool) error) error { - result := make(chan error) - timer := time.After(timeout) - stopChannel := make(chan bool, 1) - - // allow the method to attempt - go func() { - result <- work(stopChannel) - }() - for { - select { - case err := <-result: - return err - case <-timer: - stopChannel <- true - return ErrTimeoutError - } - } -} - -func getInterfaceAddress(name string) (string, error) { - interfaces, err := net.Interfaces() - if err != nil { - return "", err - } - for _, iface := range interfaces { - // step: get only the interface we're interested in - if iface.Name == name { - addrs, err := iface.Addrs() - if err != nil { - return "", err - } - // step: return the first address - if len(addrs) > 0 { - return parseIPAddr(addrs[0]), nil - } - } - } - - return "", errors.New("Unable to determine or find the interface") -} - -func contains(elements []string, value string) bool { - for _, element := range elements { - if element == value { - return true - } - } - return false -} - -func parseIPAddr(addr net.Addr) string { - return strings.SplitN(addr.String(), "/", 2)[0] -} - -// addOptions adds the parameters in opt as URL query parameters to s. -// opt must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) - if v.Kind() == reflect.Ptr && v.IsNil() { - return s, nil - } - - u, err := url.Parse(s) - if err != nil { - return s, err - } - - qs, err := query.Values(opt) - if err != nil { - return s, err - } - - u.RawQuery = qs.Encode() - return u.String(), nil -} diff --git a/vendor/github.com/gambol99/go-marathon/volume.go b/vendor/github.com/gambol99/go-marathon/volume.go deleted file mode 100644 index 89a2d97a4..000000000 --- a/vendor/github.com/gambol99/go-marathon/volume.go +++ /dev/null @@ -1,45 +0,0 @@ -/* -Copyright 2017 The go-marathon Authors All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. -*/ - -package marathon - -// PodVolume describes a volume on the host -type PodVolume struct { - Name string `json:"name,omitempty"` - Host string `json:"host,omitempty"` -} - -// PodVolumeMount describes how to mount a volume into a task -type PodVolumeMount struct { - Name string `json:"name,omitempty"` - MountPath string `json:"mountPath,omitempty"` -} - -// NewPodVolume creates a new PodVolume -func NewPodVolume(name, path string) *PodVolume { - return &PodVolume{ - Name: name, - Host: path, - } -} - -// NewPodVolumeMount creates a new PodVolumeMount -func NewPodVolumeMount(name, mount string) *PodVolumeMount { - return &PodVolumeMount{ - Name: name, - MountPath: mount, - } -} diff --git a/vendor/github.com/go-acme/lego/LICENSE b/vendor/github.com/go-acme/lego/LICENSE deleted file mode 100644 index 270cba089..000000000 --- a/vendor/github.com/go-acme/lego/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015-2017 Sebastian Erhart - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/github.com/go-acme/lego/acme/api/account.go b/vendor/github.com/go-acme/lego/acme/api/account.go deleted file mode 100644 index fd2331424..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/account.go +++ /dev/null @@ -1,69 +0,0 @@ -package api - -import ( - "encoding/base64" - "errors" - "fmt" - - "github.com/go-acme/lego/acme" -) - -type AccountService service - -// New Creates a new account. -func (a *AccountService) New(req acme.Account) (acme.ExtendedAccount, error) { - var account acme.Account - resp, err := a.core.post(a.core.GetDirectory().NewAccountURL, req, &account) - location := getLocation(resp) - - if len(location) > 0 { - a.core.jws.SetKid(location) - } - - if err != nil { - return acme.ExtendedAccount{Location: location}, err - } - - return acme.ExtendedAccount{Account: account, Location: location}, nil -} - -// NewEAB Creates a new account with an External Account Binding. -func (a *AccountService) NewEAB(accMsg acme.Account, kid string, hmacEncoded string) (acme.ExtendedAccount, error) { - hmac, err := base64.RawURLEncoding.DecodeString(hmacEncoded) - if err != nil { - return acme.ExtendedAccount{}, fmt.Errorf("acme: could not decode hmac key: %v", err) - } - - eabJWS, err := a.core.signEABContent(a.core.GetDirectory().NewAccountURL, kid, hmac) - if err != nil { - return acme.ExtendedAccount{}, fmt.Errorf("acme: error signing eab content: %v", err) - } - accMsg.ExternalAccountBinding = eabJWS - - return a.New(accMsg) -} - -// Get Retrieves an account. -func (a *AccountService) Get(accountURL string) (acme.Account, error) { - if len(accountURL) == 0 { - return acme.Account{}, errors.New("account[get]: empty URL") - } - - var account acme.Account - _, err := a.core.post(accountURL, acme.Account{}, &account) - if err != nil { - return acme.Account{}, err - } - return account, nil -} - -// Deactivate Deactivates an account. -func (a *AccountService) Deactivate(accountURL string) error { - if len(accountURL) == 0 { - return errors.New("account[deactivate]: empty URL") - } - - req := acme.Account{Status: acme.StatusDeactivated} - _, err := a.core.post(accountURL, req, nil) - return err -} diff --git a/vendor/github.com/go-acme/lego/acme/api/api.go b/vendor/github.com/go-acme/lego/acme/api/api.go deleted file mode 100644 index 912e7c5ae..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/api.go +++ /dev/null @@ -1,166 +0,0 @@ -package api - -import ( - "bytes" - "context" - "crypto" - "encoding/json" - "errors" - "fmt" - "net/http" - "time" - - "github.com/cenkalti/backoff" - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api/internal/nonces" - "github.com/go-acme/lego/acme/api/internal/secure" - "github.com/go-acme/lego/acme/api/internal/sender" - "github.com/go-acme/lego/log" -) - -// Core ACME/LE core API. -type Core struct { - doer *sender.Doer - nonceManager *nonces.Manager - jws *secure.JWS - directory acme.Directory - HTTPClient *http.Client - - common service // Reuse a single struct instead of allocating one for each service on the heap. - Accounts *AccountService - Authorizations *AuthorizationService - Certificates *CertificateService - Challenges *ChallengeService - Orders *OrderService -} - -// New Creates a new Core. -func New(httpClient *http.Client, userAgent string, caDirURL, kid string, privateKey crypto.PrivateKey) (*Core, error) { - doer := sender.NewDoer(httpClient, userAgent) - - dir, err := getDirectory(doer, caDirURL) - if err != nil { - return nil, err - } - - nonceManager := nonces.NewManager(doer, dir.NewNonceURL) - - jws := secure.NewJWS(privateKey, kid, nonceManager) - - c := &Core{doer: doer, nonceManager: nonceManager, jws: jws, directory: dir, HTTPClient: httpClient} - - c.common.core = c - c.Accounts = (*AccountService)(&c.common) - c.Authorizations = (*AuthorizationService)(&c.common) - c.Certificates = (*CertificateService)(&c.common) - c.Challenges = (*ChallengeService)(&c.common) - c.Orders = (*OrderService)(&c.common) - - return c, nil -} - -// post performs an HTTP POST request and parses the response body as JSON, -// into the provided respBody object. -func (a *Core) post(uri string, reqBody, response interface{}) (*http.Response, error) { - content, err := json.Marshal(reqBody) - if err != nil { - return nil, errors.New("failed to marshal message") - } - - return a.retrievablePost(uri, content, response) -} - -// postAsGet performs an HTTP POST ("POST-as-GET") request. -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-6.3 -func (a *Core) postAsGet(uri string, response interface{}) (*http.Response, error) { - return a.retrievablePost(uri, []byte{}, response) -} - -func (a *Core) retrievablePost(uri string, content []byte, response interface{}) (*http.Response, error) { - // during tests, allow to support ~90% of bad nonce with a minimum of attempts. - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = 200 * time.Millisecond - bo.MaxInterval = 5 * time.Second - bo.MaxElapsedTime = 20 * time.Second - - ctx, cancel := context.WithCancel(context.Background()) - - var resp *http.Response - operation := func() error { - var err error - resp, err = a.signedPost(uri, content, response) - if err != nil { - switch err.(type) { - // Retry if the nonce was invalidated - case *acme.NonceError: - log.Infof("nonce error retry: %s", err) - return err - default: - cancel() - return err - } - } - - return nil - } - - err := backoff.Retry(operation, backoff.WithContext(bo, ctx)) - if err != nil { - return nil, err - } - - return resp, nil -} - -func (a *Core) signedPost(uri string, content []byte, response interface{}) (*http.Response, error) { - signedContent, err := a.jws.SignContent(uri, content) - if err != nil { - return nil, fmt.Errorf("failed to post JWS message -> failed to sign content -> %v", err) - } - - signedBody := bytes.NewBuffer([]byte(signedContent.FullSerialize())) - - resp, err := a.doer.Post(uri, signedBody, "application/jose+json", response) - - // nonceErr is ignored to keep the root error. - nonce, nonceErr := nonces.GetFromResponse(resp) - if nonceErr == nil { - a.nonceManager.Push(nonce) - } - - return resp, err -} - -func (a *Core) signEABContent(newAccountURL, kid string, hmac []byte) ([]byte, error) { - eabJWS, err := a.jws.SignEABContent(newAccountURL, kid, hmac) - if err != nil { - return nil, err - } - - return []byte(eabJWS.FullSerialize()), nil -} - -// GetKeyAuthorization Gets the key authorization -func (a *Core) GetKeyAuthorization(token string) (string, error) { - return a.jws.GetKeyAuthorization(token) -} - -func (a *Core) GetDirectory() acme.Directory { - return a.directory -} - -func getDirectory(do *sender.Doer, caDirURL string) (acme.Directory, error) { - var dir acme.Directory - if _, err := do.Get(caDirURL, &dir); err != nil { - return dir, fmt.Errorf("get directory at '%s': %v", caDirURL, err) - } - - if dir.NewAccountURL == "" { - return dir, errors.New("directory missing new registration URL") - } - if dir.NewOrderURL == "" { - return dir, errors.New("directory missing new order URL") - } - - return dir, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/authorization.go b/vendor/github.com/go-acme/lego/acme/api/authorization.go deleted file mode 100644 index a59fa0d25..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/authorization.go +++ /dev/null @@ -1,34 +0,0 @@ -package api - -import ( - "errors" - - "github.com/go-acme/lego/acme" -) - -type AuthorizationService service - -// Get Gets an authorization. -func (c *AuthorizationService) Get(authzURL string) (acme.Authorization, error) { - if len(authzURL) == 0 { - return acme.Authorization{}, errors.New("authorization[get]: empty URL") - } - - var authz acme.Authorization - _, err := c.core.postAsGet(authzURL, &authz) - if err != nil { - return acme.Authorization{}, err - } - return authz, nil -} - -// Deactivate Deactivates an authorization. -func (c *AuthorizationService) Deactivate(authzURL string) error { - if len(authzURL) == 0 { - return errors.New("authorization[deactivate]: empty URL") - } - - var disabledAuth acme.Authorization - _, err := c.core.post(authzURL, acme.Authorization{Status: acme.StatusDeactivated}, &disabledAuth) - return err -} diff --git a/vendor/github.com/go-acme/lego/acme/api/certificate.go b/vendor/github.com/go-acme/lego/acme/api/certificate.go deleted file mode 100644 index 65904e76d..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/certificate.go +++ /dev/null @@ -1,99 +0,0 @@ -package api - -import ( - "crypto/x509" - "encoding/pem" - "errors" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/log" -) - -// maxBodySize is the maximum size of body that we will read. -const maxBodySize = 1024 * 1024 - -type CertificateService service - -// Get Returns the certificate and the issuer certificate. -// 'bundle' is only applied if the issuer is provided by the 'up' link. -func (c *CertificateService) Get(certURL string, bundle bool) ([]byte, []byte, error) { - cert, up, err := c.get(certURL) - if err != nil { - return nil, nil, err - } - - // Get issuerCert from bundled response from Let's Encrypt - // See https://community.letsencrypt.org/t/acme-v2-no-up-link-in-response/64962 - _, issuer := pem.Decode(cert) - if issuer != nil { - return cert, issuer, nil - } - - issuer, err = c.getIssuerFromLink(up) - if err != nil { - // If we fail to acquire the issuer cert, return the issued certificate - do not fail. - log.Warnf("acme: Could not bundle issuer certificate [%s]: %v", certURL, err) - } else if len(issuer) > 0 { - // If bundle is true, we want to return a certificate bundle. - // To do this, we append the issuer cert to the issued cert. - if bundle { - cert = append(cert, issuer...) - } - } - - return cert, issuer, nil -} - -// Revoke Revokes a certificate. -func (c *CertificateService) Revoke(req acme.RevokeCertMessage) error { - _, err := c.core.post(c.core.GetDirectory().RevokeCertURL, req, nil) - return err -} - -// get Returns the certificate and the "up" link. -func (c *CertificateService) get(certURL string) ([]byte, string, error) { - if len(certURL) == 0 { - return nil, "", errors.New("certificate[get]: empty URL") - } - - resp, err := c.core.postAsGet(certURL, nil) - if err != nil { - return nil, "", err - } - - cert, err := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if err != nil { - return nil, "", err - } - - // The issuer certificate link may be supplied via an "up" link - // in the response headers of a new certificate. - // See https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.4.2 - up := getLink(resp.Header, "up") - - return cert, up, err -} - -// getIssuerFromLink requests the issuer certificate -func (c *CertificateService) getIssuerFromLink(up string) ([]byte, error) { - if len(up) == 0 { - return nil, nil - } - - log.Infof("acme: Requesting issuer cert from %s", up) - - cert, _, err := c.get(up) - if err != nil { - return nil, err - } - - _, err = x509.ParseCertificate(cert) - if err != nil { - return nil, err - } - - return certcrypto.PEMEncode(certcrypto.DERCertificateBytes(cert)), nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/challenge.go b/vendor/github.com/go-acme/lego/acme/api/challenge.go deleted file mode 100644 index f4e8dbeeb..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/challenge.go +++ /dev/null @@ -1,45 +0,0 @@ -package api - -import ( - "errors" - - "github.com/go-acme/lego/acme" -) - -type ChallengeService service - -// New Creates a challenge. -func (c *ChallengeService) New(chlgURL string) (acme.ExtendedChallenge, error) { - if len(chlgURL) == 0 { - return acme.ExtendedChallenge{}, errors.New("challenge[new]: empty URL") - } - - // Challenge initiation is done by sending a JWS payload containing the trivial JSON object `{}`. - // We use an empty struct instance as the postJSON payload here to achieve this result. - var chlng acme.ExtendedChallenge - resp, err := c.core.post(chlgURL, struct{}{}, &chlng) - if err != nil { - return acme.ExtendedChallenge{}, err - } - - chlng.AuthorizationURL = getLink(resp.Header, "up") - chlng.RetryAfter = getRetryAfter(resp) - return chlng, nil -} - -// Get Gets a challenge. -func (c *ChallengeService) Get(chlgURL string) (acme.ExtendedChallenge, error) { - if len(chlgURL) == 0 { - return acme.ExtendedChallenge{}, errors.New("challenge[get]: empty URL") - } - - var chlng acme.ExtendedChallenge - resp, err := c.core.postAsGet(chlgURL, &chlng) - if err != nil { - return acme.ExtendedChallenge{}, err - } - - chlng.AuthorizationURL = getLink(resp.Header, "up") - chlng.RetryAfter = getRetryAfter(resp) - return chlng, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go b/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go deleted file mode 100644 index c08f6d493..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/nonces/nonce_manager.go +++ /dev/null @@ -1,78 +0,0 @@ -package nonces - -import ( - "errors" - "fmt" - "net/http" - "sync" - - "github.com/go-acme/lego/acme/api/internal/sender" -) - -// Manager Manages nonces. -type Manager struct { - do *sender.Doer - nonceURL string - nonces []string - sync.Mutex -} - -// NewManager Creates a new Manager. -func NewManager(do *sender.Doer, nonceURL string) *Manager { - return &Manager{ - do: do, - nonceURL: nonceURL, - } -} - -// Pop Pops a nonce. -func (n *Manager) Pop() (string, bool) { - n.Lock() - defer n.Unlock() - - if len(n.nonces) == 0 { - return "", false - } - - nonce := n.nonces[len(n.nonces)-1] - n.nonces = n.nonces[:len(n.nonces)-1] - return nonce, true -} - -// Push Pushes a nonce. -func (n *Manager) Push(nonce string) { - n.Lock() - defer n.Unlock() - n.nonces = append(n.nonces, nonce) -} - -// Nonce implement jose.NonceSource -func (n *Manager) Nonce() (string, error) { - if nonce, ok := n.Pop(); ok { - return nonce, nil - } - return n.getNonce() -} - -func (n *Manager) getNonce() (string, error) { - resp, err := n.do.Head(n.nonceURL) - if err != nil { - return "", fmt.Errorf("failed to get nonce from HTTP HEAD -> %v", err) - } - - return GetFromResponse(resp) -} - -// GetFromResponse Extracts a nonce from a HTTP response. -func GetFromResponse(resp *http.Response) (string, error) { - if resp == nil { - return "", errors.New("nil response") - } - - nonce := resp.Header.Get("Replay-Nonce") - if nonce == "" { - return "", fmt.Errorf("server did not respond with a proper nonce header") - } - - return nonce, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go b/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go deleted file mode 100644 index 213aeda0a..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/secure/jws.go +++ /dev/null @@ -1,130 +0,0 @@ -package secure - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/base64" - "fmt" - - "github.com/go-acme/lego/acme/api/internal/nonces" - jose "gopkg.in/square/go-jose.v2" -) - -// JWS Represents a JWS. -type JWS struct { - privKey crypto.PrivateKey - kid string // Key identifier - nonces *nonces.Manager -} - -// NewJWS Create a new JWS. -func NewJWS(privateKey crypto.PrivateKey, kid string, nonceManager *nonces.Manager) *JWS { - return &JWS{ - privKey: privateKey, - nonces: nonceManager, - kid: kid, - } -} - -// SetKid Sets a key identifier. -func (j *JWS) SetKid(kid string) { - j.kid = kid -} - -// SignContent Signs a content with the JWS. -func (j *JWS) SignContent(url string, content []byte) (*jose.JSONWebSignature, error) { - var alg jose.SignatureAlgorithm - switch k := j.privKey.(type) { - case *rsa.PrivateKey: - alg = jose.RS256 - case *ecdsa.PrivateKey: - if k.Curve == elliptic.P256() { - alg = jose.ES256 - } else if k.Curve == elliptic.P384() { - alg = jose.ES384 - } - } - - signKey := jose.SigningKey{ - Algorithm: alg, - Key: jose.JSONWebKey{Key: j.privKey, KeyID: j.kid}, - } - - options := jose.SignerOptions{ - NonceSource: j.nonces, - ExtraHeaders: map[jose.HeaderKey]interface{}{ - "url": url, - }, - } - - if j.kid == "" { - options.EmbedJWK = true - } - - signer, err := jose.NewSigner(signKey, &options) - if err != nil { - return nil, fmt.Errorf("failed to create jose signer -> %v", err) - } - - signed, err := signer.Sign(content) - if err != nil { - return nil, fmt.Errorf("failed to sign content -> %v", err) - } - return signed, nil -} - -// SignEABContent Signs an external account binding content with the JWS. -func (j *JWS) SignEABContent(url, kid string, hmac []byte) (*jose.JSONWebSignature, error) { - jwk := jose.JSONWebKey{Key: j.privKey} - jwkJSON, err := jwk.Public().MarshalJSON() - if err != nil { - return nil, fmt.Errorf("acme: error encoding eab jwk key: %v", err) - } - - signer, err := jose.NewSigner( - jose.SigningKey{Algorithm: jose.HS256, Key: hmac}, - &jose.SignerOptions{ - EmbedJWK: false, - ExtraHeaders: map[jose.HeaderKey]interface{}{ - "kid": kid, - "url": url, - }, - }, - ) - if err != nil { - return nil, fmt.Errorf("failed to create External Account Binding jose signer -> %v", err) - } - - signed, err := signer.Sign(jwkJSON) - if err != nil { - return nil, fmt.Errorf("failed to External Account Binding sign content -> %v", err) - } - - return signed, nil -} - -// GetKeyAuthorization Gets the key authorization for a token. -func (j *JWS) GetKeyAuthorization(token string) (string, error) { - var publicKey crypto.PublicKey - switch k := j.privKey.(type) { - case *ecdsa.PrivateKey: - publicKey = k.Public() - case *rsa.PrivateKey: - publicKey = k.Public() - } - - // Generate the Key Authorization for the challenge - jwk := &jose.JSONWebKey{Key: publicKey} - - thumbBytes, err := jwk.Thumbprint(crypto.SHA256) - if err != nil { - return "", err - } - - // unpad the base64URL - keyThumb := base64.RawURLEncoding.EncodeToString(thumbBytes) - - return token + "." + keyThumb, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go b/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go deleted file mode 100644 index e08f2ffba..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/sender/sender.go +++ /dev/null @@ -1,146 +0,0 @@ -package sender - -import ( - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "runtime" - "strings" - - "github.com/go-acme/lego/acme" -) - -type RequestOption func(*http.Request) error - -func contentType(ct string) RequestOption { - return func(req *http.Request) error { - req.Header.Set("Content-Type", ct) - return nil - } -} - -type Doer struct { - httpClient *http.Client - userAgent string -} - -// NewDoer Creates a new Doer. -func NewDoer(client *http.Client, userAgent string) *Doer { - return &Doer{ - httpClient: client, - userAgent: userAgent, - } -} - -// Get performs a GET request with a proper User-Agent string. -// If "response" is not provided, callers should close resp.Body when done reading from it. -func (d *Doer) Get(url string, response interface{}) (*http.Response, error) { - req, err := d.newRequest(http.MethodGet, url, nil) - if err != nil { - return nil, err - } - - return d.do(req, response) -} - -// Head performs a HEAD request with a proper User-Agent string. -// The response body (resp.Body) is already closed when this function returns. -func (d *Doer) Head(url string) (*http.Response, error) { - req, err := d.newRequest(http.MethodHead, url, nil) - if err != nil { - return nil, err - } - - return d.do(req, nil) -} - -// Post performs a POST request with a proper User-Agent string. -// If "response" is not provided, callers should close resp.Body when done reading from it. -func (d *Doer) Post(url string, body io.Reader, bodyType string, response interface{}) (*http.Response, error) { - req, err := d.newRequest(http.MethodPost, url, body, contentType(bodyType)) - if err != nil { - return nil, err - } - - return d.do(req, response) -} - -func (d *Doer) newRequest(method, uri string, body io.Reader, opts ...RequestOption) (*http.Request, error) { - req, err := http.NewRequest(method, uri, body) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - - req.Header.Set("User-Agent", d.formatUserAgent()) - - for _, opt := range opts { - err = opt(req) - if err != nil { - return nil, fmt.Errorf("failed to create request: %v", err) - } - } - - return req, nil -} - -func (d *Doer) do(req *http.Request, response interface{}) (*http.Response, error) { - resp, err := d.httpClient.Do(req) - if err != nil { - return nil, err - } - - if err = checkError(req, resp); err != nil { - return resp, err - } - - if response != nil { - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return resp, err - } - - defer resp.Body.Close() - - err = json.Unmarshal(raw, response) - if err != nil { - return resp, fmt.Errorf("failed to unmarshal %q to type %T: %v", raw, response, err) - } - } - - return resp, nil -} - -// formatUserAgent builds and returns the User-Agent string to use in requests. -func (d *Doer) formatUserAgent() string { - ua := fmt.Sprintf("%s %s (%s; %s; %s)", d.userAgent, ourUserAgent, ourUserAgentComment, runtime.GOOS, runtime.GOARCH) - return strings.TrimSpace(ua) -} - -func checkError(req *http.Request, resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest { - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("%d :: %s :: %s :: %v", resp.StatusCode, req.Method, req.URL, err) - } - - var errorDetails *acme.ProblemDetails - err = json.Unmarshal(body, &errorDetails) - if err != nil { - return fmt.Errorf("%d ::%s :: %s :: %v :: %s", resp.StatusCode, req.Method, req.URL, err, string(body)) - } - - errorDetails.Method = req.Method - errorDetails.URL = req.URL.String() - - // Check for errors we handle specifically - if errorDetails.HTTPStatus == http.StatusBadRequest && errorDetails.Type == acme.BadNonceErr { - return &acme.NonceError{ProblemDetails: errorDetails} - } - - return errorDetails - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go b/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go deleted file mode 100644 index 9671434cf..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/internal/sender/useragent.go +++ /dev/null @@ -1,14 +0,0 @@ -package sender - -// CODE GENERATED AUTOMATICALLY -// THIS FILE MUST NOT BE EDITED BY HAND - -const ( - // ourUserAgent is the User-Agent of this underlying library package. - ourUserAgent = "xenolf-acme/2.6.0" - - // ourUserAgentComment is part of the UA comment linked to the version status of this underlying library package. - // values: detach|release - // NOTE: Update this with each tagged release. - ourUserAgentComment = "release" -) diff --git a/vendor/github.com/go-acme/lego/acme/api/order.go b/vendor/github.com/go-acme/lego/acme/api/order.go deleted file mode 100644 index 11240b4cd..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/order.go +++ /dev/null @@ -1,65 +0,0 @@ -package api - -import ( - "encoding/base64" - "errors" - - "github.com/go-acme/lego/acme" -) - -type OrderService service - -// New Creates a new order. -func (o *OrderService) New(domains []string) (acme.ExtendedOrder, error) { - var identifiers []acme.Identifier - for _, domain := range domains { - identifiers = append(identifiers, acme.Identifier{Type: "dns", Value: domain}) - } - - orderReq := acme.Order{Identifiers: identifiers} - - var order acme.Order - resp, err := o.core.post(o.core.GetDirectory().NewOrderURL, orderReq, &order) - if err != nil { - return acme.ExtendedOrder{}, err - } - - return acme.ExtendedOrder{ - Location: resp.Header.Get("Location"), - Order: order, - }, nil -} - -// Get Gets an order. -func (o *OrderService) Get(orderURL string) (acme.Order, error) { - if len(orderURL) == 0 { - return acme.Order{}, errors.New("order[get]: empty URL") - } - - var order acme.Order - _, err := o.core.postAsGet(orderURL, &order) - if err != nil { - return acme.Order{}, err - } - - return order, nil -} - -// UpdateForCSR Updates an order for a CSR. -func (o *OrderService) UpdateForCSR(orderURL string, csr []byte) (acme.Order, error) { - csrMsg := acme.CSRMessage{ - Csr: base64.RawURLEncoding.EncodeToString(csr), - } - - var order acme.Order - _, err := o.core.post(orderURL, csrMsg, &order) - if err != nil { - return acme.Order{}, err - } - - if order.Status == acme.StatusInvalid { - return acme.Order{}, order.Error - } - - return order, nil -} diff --git a/vendor/github.com/go-acme/lego/acme/api/service.go b/vendor/github.com/go-acme/lego/acme/api/service.go deleted file mode 100644 index ff043bc7b..000000000 --- a/vendor/github.com/go-acme/lego/acme/api/service.go +++ /dev/null @@ -1,45 +0,0 @@ -package api - -import ( - "net/http" - "regexp" -) - -type service struct { - core *Core -} - -// getLink get a rel into the Link header -func getLink(header http.Header, rel string) string { - var linkExpr = regexp.MustCompile(`<(.+?)>;\s*rel="(.+?)"`) - - for _, link := range header["Link"] { - for _, m := range linkExpr.FindAllStringSubmatch(link, -1) { - if len(m) != 3 { - continue - } - if m[2] == rel { - return m[1] - } - } - } - return "" -} - -// getLocation get the value of the header Location -func getLocation(resp *http.Response) string { - if resp == nil { - return "" - } - - return resp.Header.Get("Location") -} - -// getRetryAfter get the value of the header Retry-After -func getRetryAfter(resp *http.Response) string { - if resp == nil { - return "" - } - - return resp.Header.Get("Retry-After") -} diff --git a/vendor/github.com/go-acme/lego/acme/commons.go b/vendor/github.com/go-acme/lego/acme/commons.go deleted file mode 100644 index c4493696a..000000000 --- a/vendor/github.com/go-acme/lego/acme/commons.go +++ /dev/null @@ -1,284 +0,0 @@ -// Package acme contains all objects related the ACME endpoints. -// https://tools.ietf.org/html/draft-ietf-acme-acme-16 -package acme - -import ( - "encoding/json" - "time" -) - -// Challenge statuses -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.6 -const ( - StatusPending = "pending" - StatusInvalid = "invalid" - StatusValid = "valid" - StatusProcessing = "processing" - StatusDeactivated = "deactivated" - StatusExpired = "expired" - StatusRevoked = "revoked" -) - -// Directory the ACME directory object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.1 -type Directory struct { - NewNonceURL string `json:"newNonce"` - NewAccountURL string `json:"newAccount"` - NewOrderURL string `json:"newOrder"` - NewAuthzURL string `json:"newAuthz"` - RevokeCertURL string `json:"revokeCert"` - KeyChangeURL string `json:"keyChange"` - Meta Meta `json:"meta"` -} - -// Meta the ACME meta object (related to Directory). -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.1 -type Meta struct { - // termsOfService (optional, string): - // A URL identifying the current terms of service. - TermsOfService string `json:"termsOfService"` - - // website (optional, string): - // An HTTP or HTTPS URL locating a website providing more information about the ACME server. - Website string `json:"website"` - - // caaIdentities (optional, array of string): - // The hostnames that the ACME server recognizes as referring to itself - // for the purposes of CAA record validation as defined in [RFC6844]. - // Each string MUST represent the same sequence of ASCII code points - // that the server will expect to see as the "Issuer Domain Name" in a CAA issue or issuewild property tag. - // This allows clients to determine the correct issuer domain name to use when configuring CAA records. - CaaIdentities []string `json:"caaIdentities"` - - // externalAccountRequired (optional, boolean): - // If this field is present and set to "true", - // then the CA requires that all new- account requests include an "externalAccountBinding" field - // associating the new account with an external account. - ExternalAccountRequired bool `json:"externalAccountRequired"` -} - -// ExtendedAccount a extended Account. -type ExtendedAccount struct { - Account - // Contains the value of the response header `Location` - Location string `json:"-"` -} - -// Account the ACME account Object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.2 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.3 -type Account struct { - // status (required, string): - // The status of this account. - // Possible values are: "valid", "deactivated", and "revoked". - // The value "deactivated" should be used to indicate client-initiated deactivation - // whereas "revoked" should be used to indicate server- initiated deactivation. (See Section 7.1.6) - Status string `json:"status,omitempty"` - - // contact (optional, array of string): - // An array of URLs that the server can use to contact the client for issues related to this account. - // For example, the server may wish to notify the client about server-initiated revocation or certificate expiration. - // For information on supported URL schemes, see Section 7.3 - Contact []string `json:"contact,omitempty"` - - // termsOfServiceAgreed (optional, boolean): - // Including this field in a new-account request, - // with a value of true, indicates the client's agreement with the terms of service. - // This field is not updateable by the client. - TermsOfServiceAgreed bool `json:"termsOfServiceAgreed,omitempty"` - - // orders (required, string): - // A URL from which a list of orders submitted by this account can be fetched via a POST-as-GET request, - // as described in Section 7.1.2.1. - Orders string `json:"orders,omitempty"` - - // onlyReturnExisting (optional, boolean): - // If this field is present with the value "true", - // then the server MUST NOT create a new account if one does not already exist. - // This allows a client to look up an account URL based on an account key (see Section 7.3.1). - OnlyReturnExisting bool `json:"onlyReturnExisting,omitempty"` - - // externalAccountBinding (optional, object): - // An optional field for binding the new account with an existing non-ACME account (see Section 7.3.4). - ExternalAccountBinding json.RawMessage `json:"externalAccountBinding,omitempty"` -} - -// ExtendedOrder a extended Order. -type ExtendedOrder struct { - Order - // The order URL, contains the value of the response header `Location` - Location string `json:"-"` -} - -// Order the ACME order Object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.3 -type Order struct { - // status (required, string): - // The status of this order. - // Possible values are: "pending", "ready", "processing", "valid", and "invalid". - Status string `json:"status,omitempty"` - - // expires (optional, string): - // The timestamp after which the server will consider this order invalid, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED for objects with "pending" or "valid" in the status field. - Expires string `json:"expires,omitempty"` - - // identifiers (required, array of object): - // An array of identifier objects that the order pertains to. - Identifiers []Identifier `json:"identifiers"` - - // notBefore (optional, string): - // The requested value of the notBefore field in the certificate, - // in the date format defined in [RFC3339]. - NotBefore string `json:"notBefore,omitempty"` - - // notAfter (optional, string): - // The requested value of the notAfter field in the certificate, - // in the date format defined in [RFC3339]. - NotAfter string `json:"notAfter,omitempty"` - - // error (optional, object): - // The error that occurred while processing the order, if any. - // This field is structured as a problem document [RFC7807]. - Error *ProblemDetails `json:"error,omitempty"` - - // authorizations (required, array of string): - // For pending orders, - // the authorizations that the client needs to complete before the requested certificate can be issued (see Section 7.5), - // including unexpired authorizations that the client has completed in the past for identifiers specified in the order. - // The authorizations required are dictated by server policy - // and there may not be a 1:1 relationship between the order identifiers and the authorizations required. - // For final orders (in the "valid" or "invalid" state), the authorizations that were completed. - // Each entry is a URL from which an authorization can be fetched with a POST-as-GET request. - Authorizations []string `json:"authorizations,omitempty"` - - // finalize (required, string): - // A URL that a CSR must be POSTed to once all of the order's authorizations are satisfied to finalize the order. - // The result of a successful finalization will be the population of the certificate URL for the order. - Finalize string `json:"finalize,omitempty"` - - // certificate (optional, string): - // A URL for the certificate that has been issued in response to this order - Certificate string `json:"certificate,omitempty"` -} - -// Authorization the ACME authorization object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.4 -type Authorization struct { - // status (required, string): - // The status of this authorization. - // Possible values are: "pending", "valid", "invalid", "deactivated", "expired", and "revoked". - Status string `json:"status"` - - // expires (optional, string): - // The timestamp after which the server will consider this authorization invalid, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED for objects with "valid" in the "status" field. - Expires time.Time `json:"expires,omitempty"` - - // identifier (required, object): - // The identifier that the account is authorized to represent - Identifier Identifier `json:"identifier,omitempty"` - - // challenges (required, array of objects): - // For pending authorizations, the challenges that the client can fulfill in order to prove possession of the identifier. - // For valid authorizations, the challenge that was validated. - // For invalid authorizations, the challenge that was attempted and failed. - // Each array entry is an object with parameters required to validate the challenge. - // A client should attempt to fulfill one of these challenges, - // and a server should consider any one of the challenges sufficient to make the authorization valid. - Challenges []Challenge `json:"challenges,omitempty"` - - // wildcard (optional, boolean): - // For authorizations created as a result of a newOrder request containing a DNS identifier - // with a value that contained a wildcard prefix this field MUST be present, and true. - Wildcard bool `json:"wildcard,omitempty"` -} - -// ExtendedChallenge a extended Challenge. -type ExtendedChallenge struct { - Challenge - // Contains the value of the response header `Retry-After` - RetryAfter string `json:"-"` - // Contains the value of the response header `Link` rel="up" - AuthorizationURL string `json:"-"` -} - -// Challenge the ACME challenge object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.5 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8 -type Challenge struct { - // type (required, string): - // The type of challenge encoded in the object. - Type string `json:"type"` - - // url (required, string): - // The URL to which a response can be posted. - URL string `json:"url"` - - // status (required, string): - // The status of this challenge. Possible values are: "pending", "processing", "valid", and "invalid". - Status string `json:"status"` - - // validated (optional, string): - // The time at which the server validated this challenge, - // encoded in the format specified in RFC 3339 [RFC3339]. - // This field is REQUIRED if the "status" field is "valid". - Validated time.Time `json:"validated,omitempty"` - - // error (optional, object): - // Error that occurred while the server was validating the challenge, if any, - // structured as a problem document [RFC7807]. - // Multiple errors can be indicated by using subproblems Section 6.7.1. - // A challenge object with an error MUST have status equal to "invalid". - Error *ProblemDetails `json:"error,omitempty"` - - // token (required, string): - // A random value that uniquely identifies the challenge. - // This value MUST have at least 128 bits of entropy. - // It MUST NOT contain any characters outside the base64url alphabet, - // and MUST NOT include base64 padding characters ("="). - // See [RFC4086] for additional information on randomness requirements. - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.3 - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.4 - Token string `json:"token"` - - // https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.1 - KeyAuthorization string `json:"keyAuthorization"` -} - -// Identifier the ACME identifier object. -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-9.7.7 -type Identifier struct { - Type string `json:"type"` - Value string `json:"value"` -} - -// CSRMessage Certificate Signing Request -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.4 -type CSRMessage struct { - // csr (required, string): - // A CSR encoding the parameters for the certificate being requested [RFC2986]. - // The CSR is sent in the base64url-encoded version of the DER format. - // (Note: Because this field uses base64url, and does not include headers, it is different from PEM.). - Csr string `json:"csr"` -} - -// RevokeCertMessage a certificate revocation message -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.6 -// - https://tools.ietf.org/html/rfc5280#section-5.3.1 -type RevokeCertMessage struct { - // certificate (required, string): - // The certificate to be revoked, in the base64url-encoded version of the DER format. - // (Note: Because this field uses base64url, and does not include headers, it is different from PEM.) - Certificate string `json:"certificate"` - - // reason (optional, int): - // One of the revocation reasonCodes defined in Section 5.3.1 of [RFC5280] to be used when generating OCSP responses and CRLs. - // If this field is not set the server SHOULD omit the reasonCode CRL entry extension when generating OCSP responses and CRLs. - // The server MAY disallow a subset of reasonCodes from being used by the user. - // If a request contains a disallowed reasonCode the server MUST reject it with the error type "urn:ietf:params:acme:error:badRevocationReason". - // The problem document detail SHOULD indicate which reasonCodes are allowed. - Reason *uint `json:"reason,omitempty"` -} diff --git a/vendor/github.com/go-acme/lego/acme/errors.go b/vendor/github.com/go-acme/lego/acme/errors.go deleted file mode 100644 index 1658fe8d1..000000000 --- a/vendor/github.com/go-acme/lego/acme/errors.go +++ /dev/null @@ -1,58 +0,0 @@ -package acme - -import ( - "fmt" -) - -// Errors types -const ( - errNS = "urn:ietf:params:acme:error:" - BadNonceErr = errNS + "badNonce" -) - -// ProblemDetails the problem details object -// - https://tools.ietf.org/html/rfc7807#section-3.1 -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.3.3 -type ProblemDetails struct { - Type string `json:"type,omitempty"` - Detail string `json:"detail,omitempty"` - HTTPStatus int `json:"status,omitempty"` - Instance string `json:"instance,omitempty"` - SubProblems []SubProblem `json:"subproblems,omitempty"` - - // additional values to have a better error message (Not defined by the RFC) - Method string `json:"method,omitempty"` - URL string `json:"url,omitempty"` -} - -// SubProblem a "subproblems" -// - https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-6.7.1 -type SubProblem struct { - Type string `json:"type,omitempty"` - Detail string `json:"detail,omitempty"` - Identifier Identifier `json:"identifier,omitempty"` -} - -func (p ProblemDetails) Error() string { - msg := fmt.Sprintf("acme: error: %d", p.HTTPStatus) - if len(p.Method) != 0 || len(p.URL) != 0 { - msg += fmt.Sprintf(" :: %s :: %s", p.Method, p.URL) - } - msg += fmt.Sprintf(" :: %s :: %s", p.Type, p.Detail) - - for _, sub := range p.SubProblems { - msg += fmt.Sprintf(", problem: %q :: %s", sub.Type, sub.Detail) - } - - if len(p.Instance) == 0 { - msg += ", url: " + p.Instance - } - - return msg -} - -// NonceError represents the error which is returned -// if the nonce sent by the client was not accepted by the server. -type NonceError struct { - *ProblemDetails -} diff --git a/vendor/github.com/go-acme/lego/certcrypto/crypto.go b/vendor/github.com/go-acme/lego/certcrypto/crypto.go deleted file mode 100644 index c9d0c1098..000000000 --- a/vendor/github.com/go-acme/lego/certcrypto/crypto.go +++ /dev/null @@ -1,256 +0,0 @@ -package certcrypto - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "errors" - "fmt" - "math/big" - "time" - - "golang.org/x/crypto/ocsp" -) - -// Constants for all key types we support. -const ( - EC256 = KeyType("P256") - EC384 = KeyType("P384") - RSA2048 = KeyType("2048") - RSA4096 = KeyType("4096") - RSA8192 = KeyType("8192") -) - -const ( - // OCSPGood means that the certificate is valid. - OCSPGood = ocsp.Good - // OCSPRevoked means that the certificate has been deliberately revoked. - OCSPRevoked = ocsp.Revoked - // OCSPUnknown means that the OCSP responder doesn't know about the certificate. - OCSPUnknown = ocsp.Unknown - // OCSPServerFailed means that the OCSP responder failed to process the request. - OCSPServerFailed = ocsp.ServerFailed -) - -// Constants for OCSP must staple -var ( - tlsFeatureExtensionOID = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 24} - ocspMustStapleFeature = []byte{0x30, 0x03, 0x02, 0x01, 0x05} -) - -// KeyType represents the key algo as well as the key size or curve to use. -type KeyType string - -type DERCertificateBytes []byte - -// ParsePEMBundle parses a certificate bundle from top to bottom and returns -// a slice of x509 certificates. This function will error if no certificates are found. -func ParsePEMBundle(bundle []byte) ([]*x509.Certificate, error) { - var certificates []*x509.Certificate - var certDERBlock *pem.Block - - for { - certDERBlock, bundle = pem.Decode(bundle) - if certDERBlock == nil { - break - } - - if certDERBlock.Type == "CERTIFICATE" { - cert, err := x509.ParseCertificate(certDERBlock.Bytes) - if err != nil { - return nil, err - } - certificates = append(certificates, cert) - } - } - - if len(certificates) == 0 { - return nil, errors.New("no certificates were found while parsing the bundle") - } - - return certificates, nil -} - -func ParsePEMPrivateKey(key []byte) (crypto.PrivateKey, error) { - keyBlock, _ := pem.Decode(key) - - switch keyBlock.Type { - case "RSA PRIVATE KEY": - return x509.ParsePKCS1PrivateKey(keyBlock.Bytes) - case "EC PRIVATE KEY": - return x509.ParseECPrivateKey(keyBlock.Bytes) - default: - return nil, errors.New("unknown PEM header value") - } -} - -func GeneratePrivateKey(keyType KeyType) (crypto.PrivateKey, error) { - switch keyType { - case EC256: - return ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - case EC384: - return ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - case RSA2048: - return rsa.GenerateKey(rand.Reader, 2048) - case RSA4096: - return rsa.GenerateKey(rand.Reader, 4096) - case RSA8192: - return rsa.GenerateKey(rand.Reader, 8192) - } - - return nil, fmt.Errorf("invalid KeyType: %s", keyType) -} - -func GenerateCSR(privateKey crypto.PrivateKey, domain string, san []string, mustStaple bool) ([]byte, error) { - template := x509.CertificateRequest{ - Subject: pkix.Name{CommonName: domain}, - DNSNames: san, - } - - if mustStaple { - template.ExtraExtensions = append(template.ExtraExtensions, pkix.Extension{ - Id: tlsFeatureExtensionOID, - Value: ocspMustStapleFeature, - }) - } - - return x509.CreateCertificateRequest(rand.Reader, &template, privateKey) -} - -func PEMEncode(data interface{}) []byte { - return pem.EncodeToMemory(PEMBlock(data)) -} - -func PEMBlock(data interface{}) *pem.Block { - var pemBlock *pem.Block - switch key := data.(type) { - case *ecdsa.PrivateKey: - keyBytes, _ := x509.MarshalECPrivateKey(key) - pemBlock = &pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes} - case *rsa.PrivateKey: - pemBlock = &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)} - case *x509.CertificateRequest: - pemBlock = &pem.Block{Type: "CERTIFICATE REQUEST", Bytes: key.Raw} - case DERCertificateBytes: - pemBlock = &pem.Block{Type: "CERTIFICATE", Bytes: []byte(data.(DERCertificateBytes))} - } - - return pemBlock -} - -func pemDecode(data []byte) (*pem.Block, error) { - pemBlock, _ := pem.Decode(data) - if pemBlock == nil { - return nil, fmt.Errorf("PEM decode did not yield a valid block. Is the certificate in the right format?") - } - - return pemBlock, nil -} - -func PemDecodeTox509CSR(pem []byte) (*x509.CertificateRequest, error) { - pemBlock, err := pemDecode(pem) - if pemBlock == nil { - return nil, err - } - - if pemBlock.Type != "CERTIFICATE REQUEST" { - return nil, fmt.Errorf("PEM block is not a certificate request") - } - - return x509.ParseCertificateRequest(pemBlock.Bytes) -} - -// ParsePEMCertificate returns Certificate from a PEM encoded certificate. -// The certificate has to be PEM encoded. Any other encodings like DER will fail. -func ParsePEMCertificate(cert []byte) (*x509.Certificate, error) { - pemBlock, err := pemDecode(cert) - if pemBlock == nil { - return nil, err - } - - // from a DER encoded certificate - return x509.ParseCertificate(pemBlock.Bytes) -} - -func ExtractDomains(cert *x509.Certificate) []string { - domains := []string{cert.Subject.CommonName} - - // Check for SAN certificate - for _, sanDomain := range cert.DNSNames { - if sanDomain == cert.Subject.CommonName { - continue - } - domains = append(domains, sanDomain) - } - - return domains -} - -func ExtractDomainsCSR(csr *x509.CertificateRequest) []string { - domains := []string{csr.Subject.CommonName} - - // loop over the SubjectAltName DNS names - for _, sanName := range csr.DNSNames { - if containsSAN(domains, sanName) { - // Duplicate; skip this name - continue - } - - // Name is unique - domains = append(domains, sanName) - } - - return domains -} - -func containsSAN(domains []string, sanName string) bool { - for _, existingName := range domains { - if existingName == sanName { - return true - } - } - return false -} - -func GeneratePemCert(privateKey *rsa.PrivateKey, domain string, extensions []pkix.Extension) ([]byte, error) { - derBytes, err := generateDerCert(privateKey, time.Time{}, domain, extensions) - if err != nil { - return nil, err - } - - return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil -} - -func generateDerCert(privateKey *rsa.PrivateKey, expiration time.Time, domain string, extensions []pkix.Extension) ([]byte, error) { - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - return nil, err - } - - if expiration.IsZero() { - expiration = time.Now().Add(365) - } - - template := x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - CommonName: "ACME Challenge TEMP", - }, - NotBefore: time.Now(), - NotAfter: expiration, - - KeyUsage: x509.KeyUsageKeyEncipherment, - BasicConstraintsValid: true, - DNSNames: []string{domain}, - ExtraExtensions: extensions, - } - - return x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey) -} diff --git a/vendor/github.com/go-acme/lego/certificate/authorization.go b/vendor/github.com/go-acme/lego/certificate/authorization.go deleted file mode 100644 index 00062504b..000000000 --- a/vendor/github.com/go-acme/lego/certificate/authorization.go +++ /dev/null @@ -1,69 +0,0 @@ -package certificate - -import ( - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/log" -) - -const ( - // overallRequestLimit is the overall number of request per second - // limited on the "new-reg", "new-authz" and "new-cert" endpoints. - // From the documentation the limitation is 20 requests per second, - // but using 20 as value doesn't work but 18 do - overallRequestLimit = 18 -) - -func (c *Certifier) getAuthorizations(order acme.ExtendedOrder) ([]acme.Authorization, error) { - resc, errc := make(chan acme.Authorization), make(chan domainError) - - delay := time.Second / overallRequestLimit - - for _, authzURL := range order.Authorizations { - time.Sleep(delay) - - go func(authzURL string) { - authz, err := c.core.Authorizations.Get(authzURL) - if err != nil { - errc <- domainError{Domain: authz.Identifier.Value, Error: err} - return - } - - resc <- authz - }(authzURL) - } - - var responses []acme.Authorization - failures := make(obtainError) - for i := 0; i < len(order.Authorizations); i++ { - select { - case res := <-resc: - responses = append(responses, res) - case err := <-errc: - failures[err.Domain] = err.Error - } - } - - for i, auth := range order.Authorizations { - log.Infof("[%s] AuthURL: %s", order.Identifiers[i].Value, auth) - } - - close(resc) - close(errc) - - // be careful to not return an empty failures map; - // even if empty, they become non-nil error values - if len(failures) > 0 { - return responses, failures - } - return responses, nil -} - -func (c *Certifier) deactivateAuthorizations(order acme.ExtendedOrder) { - for _, auth := range order.Authorizations { - if err := c.core.Authorizations.Deactivate(auth); err != nil { - log.Infof("Unable to deactivated authorizations: %s", auth) - } - } -} diff --git a/vendor/github.com/go-acme/lego/certificate/certificates.go b/vendor/github.com/go-acme/lego/certificate/certificates.go deleted file mode 100644 index 79765e712..000000000 --- a/vendor/github.com/go-acme/lego/certificate/certificates.go +++ /dev/null @@ -1,522 +0,0 @@ -package certificate - -import ( - "bytes" - "crypto" - "crypto/x509" - "encoding/base64" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/wait" - "golang.org/x/crypto/ocsp" - "golang.org/x/net/idna" -) - -// maxBodySize is the maximum size of body that we will read. -const maxBodySize = 1024 * 1024 - -// Resource represents a CA issued certificate. -// PrivateKey, Certificate and IssuerCertificate are all -// already PEM encoded and can be directly written to disk. -// Certificate may be a certificate bundle, -// depending on the options supplied to create it. -type Resource struct { - Domain string `json:"domain"` - CertURL string `json:"certUrl"` - CertStableURL string `json:"certStableUrl"` - PrivateKey []byte `json:"-"` - Certificate []byte `json:"-"` - IssuerCertificate []byte `json:"-"` - CSR []byte `json:"-"` -} - -// ObtainRequest The request to obtain certificate. -// -// The first domain in domains is used for the CommonName field of the certificate, -// all other domains are added using the Subject Alternate Names extension. -// -// A new private key is generated for every invocation of the function Obtain. -// If you do not want that you can supply your own private key in the privateKey parameter. -// If this parameter is non-nil it will be used instead of generating a new one. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -type ObtainRequest struct { - Domains []string - Bundle bool - PrivateKey crypto.PrivateKey - MustStaple bool -} - -type resolver interface { - Solve(authorizations []acme.Authorization) error -} - -type CertifierOptions struct { - KeyType certcrypto.KeyType - Timeout time.Duration -} - -// Certifier A service to obtain/renew/revoke certificates. -type Certifier struct { - core *api.Core - resolver resolver - options CertifierOptions -} - -// NewCertifier creates a Certifier. -func NewCertifier(core *api.Core, resolver resolver, options CertifierOptions) *Certifier { - return &Certifier{ - core: core, - resolver: resolver, - options: options, - } -} - -// Obtain tries to obtain a single certificate using all domains passed into it. -// -// This function will never return a partial certificate. -// If one domain in the list fails, the whole certificate will fail. -func (c *Certifier) Obtain(request ObtainRequest) (*Resource, error) { - if len(request.Domains) == 0 { - return nil, errors.New("no domains to obtain a certificate for") - } - - domains := sanitizeDomain(request.Domains) - - if request.Bundle { - log.Infof("[%s] acme: Obtaining bundled SAN certificate", strings.Join(domains, ", ")) - } else { - log.Infof("[%s] acme: Obtaining SAN certificate", strings.Join(domains, ", ")) - } - - order, err := c.core.Orders.New(domains) - if err != nil { - return nil, err - } - - authz, err := c.getAuthorizations(order) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - err = c.resolver.Solve(authz) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - - failures := make(obtainError) - cert, err := c.getForOrder(domains, order, request.Bundle, request.PrivateKey, request.MustStaple) - if err != nil { - for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err - } - } - - // Do not return an empty failures map, because - // it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil -} - -// ObtainForCSR tries to obtain a certificate matching the CSR passed into it. -// -// The domains are inferred from the CommonName and SubjectAltNames, if any. -// The private key for this CSR is not required. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -// -// This function will never return a partial certificate. -// If one domain in the list fails, the whole certificate will fail. -func (c *Certifier) ObtainForCSR(csr x509.CertificateRequest, bundle bool) (*Resource, error) { - // figure out what domains it concerns - // start with the common name - domains := certcrypto.ExtractDomainsCSR(&csr) - - if bundle { - log.Infof("[%s] acme: Obtaining bundled SAN certificate given a CSR", strings.Join(domains, ", ")) - } else { - log.Infof("[%s] acme: Obtaining SAN certificate given a CSR", strings.Join(domains, ", ")) - } - - order, err := c.core.Orders.New(domains) - if err != nil { - return nil, err - } - - authz, err := c.getAuthorizations(order) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - err = c.resolver.Solve(authz) - if err != nil { - // If any challenge fails, return. Do not generate partial SAN certificates. - c.deactivateAuthorizations(order) - return nil, err - } - - log.Infof("[%s] acme: Validations succeeded; requesting certificates", strings.Join(domains, ", ")) - - failures := make(obtainError) - cert, err := c.getForCSR(domains, order, bundle, csr.Raw, nil) - if err != nil { - for _, auth := range authz { - failures[challenge.GetTargetedDomain(auth)] = err - } - } - - if cert != nil { - // Add the CSR to the certificate so that it can be used for renewals. - cert.CSR = certcrypto.PEMEncode(&csr) - } - - // Do not return an empty failures map, - // because it would still be a non-nil error value - if len(failures) > 0 { - return cert, failures - } - return cert, nil -} - -func (c *Certifier) getForOrder(domains []string, order acme.ExtendedOrder, bundle bool, privateKey crypto.PrivateKey, mustStaple bool) (*Resource, error) { - if privateKey == nil { - var err error - privateKey, err = certcrypto.GeneratePrivateKey(c.options.KeyType) - if err != nil { - return nil, err - } - } - - // Determine certificate name(s) based on the authorization resources - commonName := domains[0] - - // ACME draft Section 7.4 "Applying for Certificate Issuance" - // https://tools.ietf.org/html/draft-ietf-acme-acme-12#section-7.4 - // says: - // Clients SHOULD NOT make any assumptions about the sort order of - // "identifiers" or "authorizations" elements in the returned order - // object. - san := []string{commonName} - for _, auth := range order.Identifiers { - if auth.Value != commonName { - san = append(san, auth.Value) - } - } - - // TODO: should the CSR be customizable? - csr, err := certcrypto.GenerateCSR(privateKey, commonName, san, mustStaple) - if err != nil { - return nil, err - } - - return c.getForCSR(domains, order, bundle, csr, certcrypto.PEMEncode(privateKey)) -} - -func (c *Certifier) getForCSR(domains []string, order acme.ExtendedOrder, bundle bool, csr []byte, privateKeyPem []byte) (*Resource, error) { - respOrder, err := c.core.Orders.UpdateForCSR(order.Finalize, csr) - if err != nil { - return nil, err - } - - commonName := domains[0] - certRes := &Resource{ - Domain: commonName, - CertURL: respOrder.Certificate, - PrivateKey: privateKeyPem, - } - - if respOrder.Status == acme.StatusValid { - // if the certificate is available right away, short cut! - ok, errR := c.checkResponse(respOrder, certRes, bundle) - if errR != nil { - return nil, errR - } - - if ok { - return certRes, nil - } - } - - timeout := c.options.Timeout - if c.options.Timeout <= 0 { - timeout = 30 * time.Second - } - - err = wait.For("certificate", timeout, timeout/60, func() (bool, error) { - ord, errW := c.core.Orders.Get(order.Location) - if errW != nil { - return false, errW - } - - done, errW := c.checkResponse(ord, certRes, bundle) - if errW != nil { - return false, errW - } - - return done, nil - }) - - return certRes, err -} - -// checkResponse checks to see if the certificate is ready and a link is contained in the response. -// -// If so, loads it into certRes and returns true. -// If the cert is not yet ready, it returns false. -// -// The certRes input should already have the Domain (common name) field populated. -// -// If bundle is true, the certificate will be bundled with the issuer's cert. -func (c *Certifier) checkResponse(order acme.Order, certRes *Resource, bundle bool) (bool, error) { - valid, err := checkOrderStatus(order) - if err != nil || !valid { - return valid, err - } - - cert, issuer, err := c.core.Certificates.Get(order.Certificate, bundle) - if err != nil { - return false, err - } - - log.Infof("[%s] Server responded with a certificate.", certRes.Domain) - - certRes.IssuerCertificate = issuer - certRes.Certificate = cert - certRes.CertURL = order.Certificate - certRes.CertStableURL = order.Certificate - - return true, nil -} - -// Revoke takes a PEM encoded certificate or bundle and tries to revoke it at the CA. -func (c *Certifier) Revoke(cert []byte) error { - certificates, err := certcrypto.ParsePEMBundle(cert) - if err != nil { - return err - } - - x509Cert := certificates[0] - if x509Cert.IsCA { - return fmt.Errorf("certificate bundle starts with a CA certificate") - } - - revokeMsg := acme.RevokeCertMessage{ - Certificate: base64.RawURLEncoding.EncodeToString(x509Cert.Raw), - } - - return c.core.Certificates.Revoke(revokeMsg) -} - -// Renew takes a Resource and tries to renew the certificate. -// -// If the renewal process succeeds, the new certificate will ge returned in a new CertResource. -// Please be aware that this function will return a new certificate in ANY case that is not an error. -// If the server does not provide us with a new cert on a GET request to the CertURL -// this function will start a new-cert flow where a new certificate gets generated. -// -// If bundle is true, the []byte contains both the issuer certificate and your issued certificate as a bundle. -// -// For private key reuse the PrivateKey property of the passed in Resource should be non-nil. -func (c *Certifier) Renew(certRes Resource, bundle, mustStaple bool) (*Resource, error) { - // Input certificate is PEM encoded. - // Decode it here as we may need the decoded cert later on in the renewal process. - // The input may be a bundle or a single certificate. - certificates, err := certcrypto.ParsePEMBundle(certRes.Certificate) - if err != nil { - return nil, err - } - - x509Cert := certificates[0] - if x509Cert.IsCA { - return nil, fmt.Errorf("[%s] Certificate bundle starts with a CA certificate", certRes.Domain) - } - - // This is just meant to be informal for the user. - timeLeft := x509Cert.NotAfter.Sub(time.Now().UTC()) - log.Infof("[%s] acme: Trying renewal with %d hours remaining", certRes.Domain, int(timeLeft.Hours())) - - // We always need to request a new certificate to renew. - // Start by checking to see if the certificate was based off a CSR, - // and use that if it's defined. - if len(certRes.CSR) > 0 { - csr, errP := certcrypto.PemDecodeTox509CSR(certRes.CSR) - if errP != nil { - return nil, errP - } - - return c.ObtainForCSR(*csr, bundle) - } - - var privateKey crypto.PrivateKey - if certRes.PrivateKey != nil { - privateKey, err = certcrypto.ParsePEMPrivateKey(certRes.PrivateKey) - if err != nil { - return nil, err - } - } - - query := ObtainRequest{ - Domains: certcrypto.ExtractDomains(x509Cert), - Bundle: bundle, - PrivateKey: privateKey, - MustStaple: mustStaple, - } - return c.Obtain(query) -} - -// GetOCSP takes a PEM encoded cert or cert bundle returning the raw OCSP response, -// the parsed response, and an error, if any. -// -// The returned []byte can be passed directly into the OCSPStaple property of a tls.Certificate. -// If the bundle only contains the issued certificate, -// this function will try to get the issuer certificate from the IssuingCertificateURL in the certificate. -// -// If the []byte and/or ocsp.Response return values are nil, the OCSP status may be assumed OCSPUnknown. -func (c *Certifier) GetOCSP(bundle []byte) ([]byte, *ocsp.Response, error) { - certificates, err := certcrypto.ParsePEMBundle(bundle) - if err != nil { - return nil, nil, err - } - - // We expect the certificate slice to be ordered downwards the chain. - // SRV CRT -> CA. We need to pull the leaf and issuer certs out of it, - // which should always be the first two certificates. - // If there's no OCSP server listed in the leaf cert, there's nothing to do. - // And if we have only one certificate so far, we need to get the issuer cert. - - issuedCert := certificates[0] - - if len(issuedCert.OCSPServer) == 0 { - return nil, nil, errors.New("no OCSP server specified in cert") - } - - if len(certificates) == 1 { - // TODO: build fallback. If this fails, check the remaining array entries. - if len(issuedCert.IssuingCertificateURL) == 0 { - return nil, nil, errors.New("no issuing certificate URL") - } - - resp, errC := c.core.HTTPClient.Get(issuedCert.IssuingCertificateURL[0]) - if errC != nil { - return nil, nil, errC - } - defer resp.Body.Close() - - issuerBytes, errC := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if errC != nil { - return nil, nil, errC - } - - issuerCert, errC := x509.ParseCertificate(issuerBytes) - if errC != nil { - return nil, nil, errC - } - - // Insert it into the slice on position 0 - // We want it ordered right SRV CRT -> CA - certificates = append(certificates, issuerCert) - } - - issuerCert := certificates[1] - - // Finally kick off the OCSP request. - ocspReq, err := ocsp.CreateRequest(issuedCert, issuerCert, nil) - if err != nil { - return nil, nil, err - } - - resp, err := c.core.HTTPClient.Post(issuedCert.OCSPServer[0], "application/ocsp-request", bytes.NewReader(ocspReq)) - if err != nil { - return nil, nil, err - } - defer resp.Body.Close() - - ocspResBytes, err := ioutil.ReadAll(http.MaxBytesReader(nil, resp.Body, maxBodySize)) - if err != nil { - return nil, nil, err - } - - ocspRes, err := ocsp.ParseResponse(ocspResBytes, issuerCert) - if err != nil { - return nil, nil, err - } - - return ocspResBytes, ocspRes, nil -} - -// Get attempts to fetch the certificate at the supplied URL. -// The URL is the same as what would normally be supplied at the Resource's CertURL. -// -// The returned Resource will not have the PrivateKey and CSR fields populated as these will not be available. -// -// If bundle is true, the Certificate field in the returned Resource includes the issuer certificate. -func (c *Certifier) Get(url string, bundle bool) (*Resource, error) { - cert, issuer, err := c.core.Certificates.Get(url, bundle) - if err != nil { - return nil, err - } - - // Parse the returned cert bundle so that we can grab the domain from the common name. - x509Certs, err := certcrypto.ParsePEMBundle(cert) - if err != nil { - return nil, err - } - - return &Resource{ - Domain: x509Certs[0].Subject.CommonName, - Certificate: cert, - IssuerCertificate: issuer, - CertURL: url, - CertStableURL: url, - }, nil -} - -func checkOrderStatus(order acme.Order) (bool, error) { - switch order.Status { - case acme.StatusValid: - return true, nil - case acme.StatusInvalid: - return false, order.Error - default: - return false, nil - } -} - -// https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-7.1.4 -// The domain name MUST be encoded -// in the form in which it would appear in a certificate. That is, it -// MUST be encoded according to the rules in Section 7 of [RFC5280]. -// -// https://tools.ietf.org/html/rfc5280#section-7 -func sanitizeDomain(domains []string) []string { - var sanitizedDomains []string - for _, domain := range domains { - sanitizedDomain, err := idna.ToASCII(domain) - if err != nil { - log.Infof("skip domain %q: unable to sanitize (punnycode): %v", domain, err) - } else { - sanitizedDomains = append(sanitizedDomains, sanitizedDomain) - } - } - return sanitizedDomains -} diff --git a/vendor/github.com/go-acme/lego/certificate/errors.go b/vendor/github.com/go-acme/lego/certificate/errors.go deleted file mode 100644 index 0fec7c16a..000000000 --- a/vendor/github.com/go-acme/lego/certificate/errors.go +++ /dev/null @@ -1,30 +0,0 @@ -package certificate - -import ( - "bytes" - "fmt" - "sort" -) - -// obtainError is returned when there are specific errors available per domain. -type obtainError map[string]error - -func (e obtainError) Error() string { - buffer := bytes.NewBufferString("acme: Error -> One or more domains had a problem:\n") - - var domains []string - for domain := range e { - domains = append(domains, domain) - } - sort.Strings(domains) - - for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) - } - return buffer.String() -} - -type domainError struct { - Domain string - Error error -} diff --git a/vendor/github.com/go-acme/lego/challenge/challenges.go b/vendor/github.com/go-acme/lego/challenge/challenges.go deleted file mode 100644 index b3281402f..000000000 --- a/vendor/github.com/go-acme/lego/challenge/challenges.go +++ /dev/null @@ -1,44 +0,0 @@ -package challenge - -import ( - "fmt" - - "github.com/go-acme/lego/acme" -) - -// Type is a string that identifies a particular challenge type and version of ACME challenge. -type Type string - -const ( - // HTTP01 is the "http-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.3 - // Note: ChallengePath returns the URL path to fulfill this challenge - HTTP01 = Type("http-01") - - // DNS01 is the "dns-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-acme-16#section-8.4 - // Note: GetRecord returns a DNS record which will fulfill this challenge - DNS01 = Type("dns-01") - - // TLSALPN01 is the "tls-alpn-01" ACME challenge https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05 - TLSALPN01 = Type("tls-alpn-01") -) - -func (t Type) String() string { - return string(t) -} - -func FindChallenge(chlgType Type, authz acme.Authorization) (acme.Challenge, error) { - for _, chlg := range authz.Challenges { - if chlg.Type == string(chlgType) { - return chlg, nil - } - } - - return acme.Challenge{}, fmt.Errorf("[%s] acme: unable to find challenge %s", GetTargetedDomain(authz), chlgType) -} - -func GetTargetedDomain(authz acme.Authorization) string { - if authz.Wildcard { - return "*." + authz.Identifier.Value - } - return authz.Identifier.Value -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/cname.go b/vendor/github.com/go-acme/lego/challenge/dns01/cname.go deleted file mode 100644 index 619c84763..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/cname.go +++ /dev/null @@ -1,16 +0,0 @@ -package dns01 - -import "github.com/miekg/dns" - -// Update FQDN with CNAME if any -func updateDomainWithCName(r *dns.Msg, fqdn string) string { - for _, rr := range r.Answer { - if cn, ok := rr.(*dns.CNAME); ok { - if cn.Hdr.Name == fqdn { - return cn.Target - } - } - } - - return fqdn -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go deleted file mode 100644 index 9500305f8..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge.go +++ /dev/null @@ -1,188 +0,0 @@ -package dns01 - -import ( - "crypto/sha256" - "encoding/base64" - "fmt" - "os" - "strconv" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/wait" - "github.com/miekg/dns" -) - -const ( - // DefaultPropagationTimeout default propagation timeout - DefaultPropagationTimeout = 60 * time.Second - - // DefaultPollingInterval default polling interval - DefaultPollingInterval = 2 * time.Second - - // DefaultTTL default TTL - DefaultTTL = 120 -) - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -type ChallengeOption func(*Challenge) error - -// CondOption Conditional challenge option. -func CondOption(condition bool, opt ChallengeOption) ChallengeOption { - if !condition { - // NoOp options - return func(*Challenge) error { - return nil - } - } - return opt -} - -// Challenge implements the dns-01 challenge -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider - preCheck preCheck - dnsTimeout time.Duration -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider, opts ...ChallengeOption) *Challenge { - chlg := &Challenge{ - core: core, - validate: validate, - provider: provider, - preCheck: newPreCheck(), - dnsTimeout: 10 * time.Second, - } - - for _, opt := range opts { - err := opt(chlg) - if err != nil { - log.Infof("challenge option error: %v", err) - } - } - - return chlg -} - -// PreSolve just submits the txt record to the dns provider. -// It does not validate record propagation, or do anything at all with the acme server. -func (c *Challenge) PreSolve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Preparing to solve DNS-01", domain) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - if c.provider == nil { - return fmt.Errorf("[%s] acme: no DNS Provider configured", domain) - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %s", domain, err) - } - - return nil -} - -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Trying to solve DNS-01", domain) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - fqdn, value := GetRecord(authz.Identifier.Value, keyAuth) - - var timeout, interval time.Duration - switch provider := c.provider.(type) { - case challenge.ProviderTimeout: - timeout, interval = provider.Timeout() - default: - timeout, interval = DefaultPropagationTimeout, DefaultPollingInterval - } - - log.Infof("[%s] acme: Checking DNS record propagation using %+v", domain, recursiveNameservers) - - err = wait.For("propagation", timeout, interval, func() (bool, error) { - stop, errP := c.preCheck.call(domain, fqdn, value) - if !stop || errP != nil { - log.Infof("[%s] acme: Waiting for DNS record propagation.", domain) - } - return stop, errP - }) - if err != nil { - return err - } - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} - -// CleanUp cleans the challenge. -func (c *Challenge) CleanUp(authz acme.Authorization) error { - log.Infof("[%s] acme: Cleaning DNS-01 challenge", challenge.GetTargetedDomain(authz)) - - chlng, err := challenge.FindChallenge(challenge.DNS01, authz) - if err != nil { - return err - } - - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - return c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth) -} - -func (c *Challenge) Sequential() (bool, time.Duration) { - if p, ok := c.provider.(sequential); ok { - return ok, p.Sequential() - } - return false, 0 -} - -type sequential interface { - Sequential() time.Duration -} - -// GetRecord returns a DNS record which will fulfill the `dns-01` challenge -func GetRecord(domain, keyAuth string) (fqdn string, value string) { - keyAuthShaBytes := sha256.Sum256([]byte(keyAuth)) - // base64URL encoding without padding - value = base64.RawURLEncoding.EncodeToString(keyAuthShaBytes[:sha256.Size]) - fqdn = fmt.Sprintf("_acme-challenge.%s.", domain) - - if ok, _ := strconv.ParseBool(os.Getenv("LEGO_EXPERIMENTAL_CNAME_SUPPORT")); ok { - r, err := dnsQuery(fqdn, dns.TypeCNAME, recursiveNameservers, true) - // Check if the domain has CNAME then return that - if err == nil && r.Rcode == dns.RcodeSuccess { - fqdn = updateDomainWithCName(r, fqdn) - } - } - - return -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go b/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go deleted file mode 100644 index 85da7d0eb..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/dns_challenge_manual.go +++ /dev/null @@ -1,59 +0,0 @@ -package dns01 - -import ( - "bufio" - "fmt" - "os" - "time" -) - -const ( - dnsTemplate = `%s %d IN TXT "%s"` -) - -// DNSProviderManual is an implementation of the ChallengeProvider interface -type DNSProviderManual struct{} - -// NewDNSProviderManual returns a DNSProviderManual instance. -func NewDNSProviderManual() (*DNSProviderManual, error) { - return &DNSProviderManual{}, nil -} - -// Present prints instructions for manually creating the TXT record -func (*DNSProviderManual) Present(domain, token, keyAuth string) error { - fqdn, value := GetRecord(domain, keyAuth) - - authZone, err := FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - fmt.Printf("lego: Please create the following TXT record in your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, value) - fmt.Printf("lego: Press 'Enter' when you are done\n") - - _, err = bufio.NewReader(os.Stdin).ReadBytes('\n') - - return err -} - -// CleanUp prints instructions for manually removing the TXT record -func (*DNSProviderManual) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := GetRecord(domain, keyAuth) - - authZone, err := FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - fmt.Printf("lego: You can now remove this TXT record from your %s zone:\n", authZone) - fmt.Printf(dnsTemplate+"\n", fqdn, DefaultTTL, "...") - - return nil -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProviderManual) Sequential() time.Duration { - return DefaultPropagationTimeout -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go b/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go deleted file mode 100644 index c238c8cf5..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/fqdn.go +++ /dev/null @@ -1,19 +0,0 @@ -package dns01 - -// ToFqdn converts the name into a fqdn appending a trailing dot. -func ToFqdn(name string) string { - n := len(name) - if n == 0 || name[n-1] == '.' { - return name - } - return name + "." -} - -// UnFqdn converts the fqdn into a name removing the trailing dot. -func UnFqdn(name string) string { - n := len(name) - if n != 0 && name[n-1] == '.' { - return name[:n-1] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go b/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go deleted file mode 100644 index 03f1a8d12..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/nameserver.go +++ /dev/null @@ -1,232 +0,0 @@ -package dns01 - -import ( - "fmt" - "net" - "strings" - "sync" - "time" - - "github.com/miekg/dns" -) - -const defaultResolvConf = "/etc/resolv.conf" - -// dnsTimeout is used to override the default DNS timeout of 10 seconds. -var dnsTimeout = 10 * time.Second - -var ( - fqdnToZone = map[string]string{} - muFqdnToZone sync.Mutex -) - -var defaultNameservers = []string{ - "google-public-dns-a.google.com:53", - "google-public-dns-b.google.com:53", -} - -// recursiveNameservers are used to pre-check DNS propagation -var recursiveNameservers = getNameservers(defaultResolvConf, defaultNameservers) - -// ClearFqdnCache clears the cache of fqdn to zone mappings. Primarily used in testing. -func ClearFqdnCache() { - muFqdnToZone.Lock() - fqdnToZone = map[string]string{} - muFqdnToZone.Unlock() -} - -func AddDNSTimeout(timeout time.Duration) ChallengeOption { - return func(_ *Challenge) error { - dnsTimeout = timeout - return nil - } -} - -func AddRecursiveNameservers(nameservers []string) ChallengeOption { - return func(_ *Challenge) error { - recursiveNameservers = ParseNameservers(nameservers) - return nil - } -} - -// getNameservers attempts to get systems nameservers before falling back to the defaults -func getNameservers(path string, defaults []string) []string { - config, err := dns.ClientConfigFromFile(path) - if err != nil || len(config.Servers) == 0 { - return defaults - } - - return ParseNameservers(config.Servers) -} - -func ParseNameservers(servers []string) []string { - var resolvers []string - for _, resolver := range servers { - // ensure all servers have a port number - if _, _, err := net.SplitHostPort(resolver); err != nil { - resolvers = append(resolvers, net.JoinHostPort(resolver, "53")) - } else { - resolvers = append(resolvers, resolver) - } - } - return resolvers -} - -// lookupNameservers returns the authoritative nameservers for the given fqdn. -func lookupNameservers(fqdn string) ([]string, error) { - var authoritativeNss []string - - zone, err := FindZoneByFqdn(fqdn) - if err != nil { - return nil, fmt.Errorf("could not determine the zone: %v", err) - } - - r, err := dnsQuery(zone, dns.TypeNS, recursiveNameservers, true) - if err != nil { - return nil, err - } - - for _, rr := range r.Answer { - if ns, ok := rr.(*dns.NS); ok { - authoritativeNss = append(authoritativeNss, strings.ToLower(ns.Ns)) - } - } - - if len(authoritativeNss) > 0 { - return authoritativeNss, nil - } - return nil, fmt.Errorf("could not determine authoritative nameservers") -} - -// FindZoneByFqdn determines the zone apex for the given fqdn -// by recursing up the domain labels until the nameserver returns a SOA record in the answer section. -func FindZoneByFqdn(fqdn string) (string, error) { - return FindZoneByFqdnCustom(fqdn, recursiveNameservers) -} - -// FindZoneByFqdnCustom determines the zone apex for the given fqdn -// by recursing up the domain labels until the nameserver returns a SOA record in the answer section. -func FindZoneByFqdnCustom(fqdn string, nameservers []string) (string, error) { - muFqdnToZone.Lock() - defer muFqdnToZone.Unlock() - - // Do we have it cached? - if zone, ok := fqdnToZone[fqdn]; ok { - return zone, nil - } - - var err error - var in *dns.Msg - - labelIndexes := dns.Split(fqdn) - for _, index := range labelIndexes { - domain := fqdn[index:] - - in, err = dnsQuery(domain, dns.TypeSOA, nameservers, true) - if err != nil { - continue - } - - if in == nil { - continue - } - - switch in.Rcode { - case dns.RcodeSuccess: - // Check if we got a SOA RR in the answer section - - if len(in.Answer) == 0 { - continue - } - - // CNAME records cannot/should not exist at the root of a zone. - // So we skip a domain when a CNAME is found. - if dnsMsgContainsCNAME(in) { - continue - } - - for _, ans := range in.Answer { - if soa, ok := ans.(*dns.SOA); ok { - zone := soa.Hdr.Name - fqdnToZone[fqdn] = zone - return zone, nil - } - } - case dns.RcodeNameError: - // NXDOMAIN - default: - // Any response code other than NOERROR and NXDOMAIN is treated as error - return "", fmt.Errorf("unexpected response code '%s' for %s", dns.RcodeToString[in.Rcode], domain) - } - } - - return "", fmt.Errorf("could not find the start of authority for %s%s", fqdn, formatDNSError(in, err)) -} - -// dnsMsgContainsCNAME checks for a CNAME answer in msg -func dnsMsgContainsCNAME(msg *dns.Msg) bool { - for _, ans := range msg.Answer { - if _, ok := ans.(*dns.CNAME); ok { - return true - } - } - return false -} - -func dnsQuery(fqdn string, rtype uint16, nameservers []string, recursive bool) (*dns.Msg, error) { - m := createDNSMsg(fqdn, rtype, recursive) - - var in *dns.Msg - var err error - - for _, ns := range nameservers { - in, err = sendDNSQuery(m, ns) - if err == nil && len(in.Answer) > 0 { - break - } - } - return in, err -} - -func createDNSMsg(fqdn string, rtype uint16, recursive bool) *dns.Msg { - m := new(dns.Msg) - m.SetQuestion(fqdn, rtype) - m.SetEdns0(4096, false) - - if !recursive { - m.RecursionDesired = false - } - - return m -} - -func sendDNSQuery(m *dns.Msg, ns string) (*dns.Msg, error) { - udp := &dns.Client{Net: "udp", Timeout: dnsTimeout} - in, _, err := udp.Exchange(m, ns) - - if in != nil && in.Truncated { - tcp := &dns.Client{Net: "tcp", Timeout: dnsTimeout} - // If the TCP request succeeds, the err will reset to nil - in, _, err = tcp.Exchange(m, ns) - } - - return in, err -} - -func formatDNSError(msg *dns.Msg, err error) string { - var parts []string - - if msg != nil { - parts = append(parts, dns.RcodeToString[msg.Rcode]) - } - - if err != nil { - parts = append(parts, fmt.Sprintf("%v", err)) - } - - if len(parts) > 0 { - return ": " + strings.Join(parts, " ") - } - - return "" -} diff --git a/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go b/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go deleted file mode 100644 index 00e09854d..000000000 --- a/vendor/github.com/go-acme/lego/challenge/dns01/precheck.go +++ /dev/null @@ -1,127 +0,0 @@ -package dns01 - -import ( - "errors" - "fmt" - "net" - "strings" - - "github.com/miekg/dns" -) - -// PreCheckFunc checks DNS propagation before notifying ACME that the DNS challenge is ready. -type PreCheckFunc func(fqdn, value string) (bool, error) - -// WrapPreCheckFunc wraps a PreCheckFunc in order to do extra operations before or after -// the main check, put it in a loop, etc. -type WrapPreCheckFunc func(domain, fqdn, value string, check PreCheckFunc) (bool, error) - -// WrapPreCheck Allow to define checks before notifying ACME that the DNS challenge is ready. -func WrapPreCheck(wrap WrapPreCheckFunc) ChallengeOption { - return func(chlg *Challenge) error { - chlg.preCheck.checkFunc = wrap - return nil - } -} - -// AddPreCheck Allow to define checks before notifying ACME that the DNS challenge is ready. -// Deprecated: use WrapPreCheck instead. -func AddPreCheck(preCheck PreCheckFunc) ChallengeOption { - // Prevent race condition - check := preCheck - return func(chlg *Challenge) error { - chlg.preCheck.checkFunc = func(_, fqdn, value string, _ PreCheckFunc) (bool, error) { - if check == nil { - return false, errors.New("invalid preCheck: preCheck is nil") - } - return check(fqdn, value) - } - return nil - } -} - -func DisableCompletePropagationRequirement() ChallengeOption { - return func(chlg *Challenge) error { - chlg.preCheck.requireCompletePropagation = false - return nil - } -} - -type preCheck struct { - // checks DNS propagation before notifying ACME that the DNS challenge is ready. - checkFunc WrapPreCheckFunc - // require the TXT record to be propagated to all authoritative name servers - requireCompletePropagation bool -} - -func newPreCheck() preCheck { - return preCheck{ - requireCompletePropagation: true, - } -} - -func (p preCheck) call(domain, fqdn, value string) (bool, error) { - if p.checkFunc == nil { - return p.checkDNSPropagation(fqdn, value) - } - - return p.checkFunc(domain, fqdn, value, p.checkDNSPropagation) -} - -// checkDNSPropagation checks if the expected TXT record has been propagated to all authoritative nameservers. -func (p preCheck) checkDNSPropagation(fqdn, value string) (bool, error) { - // Initial attempt to resolve at the recursive NS - r, err := dnsQuery(fqdn, dns.TypeTXT, recursiveNameservers, true) - if err != nil { - return false, err - } - - if !p.requireCompletePropagation { - return true, nil - } - - if r.Rcode == dns.RcodeSuccess { - fqdn = updateDomainWithCName(r, fqdn) - } - - authoritativeNss, err := lookupNameservers(fqdn) - if err != nil { - return false, err - } - - return checkAuthoritativeNss(fqdn, value, authoritativeNss) -} - -// checkAuthoritativeNss queries each of the given nameservers for the expected TXT record. -func checkAuthoritativeNss(fqdn, value string, nameservers []string) (bool, error) { - for _, ns := range nameservers { - r, err := dnsQuery(fqdn, dns.TypeTXT, []string{net.JoinHostPort(ns, "53")}, false) - if err != nil { - return false, err - } - - if r.Rcode != dns.RcodeSuccess { - return false, fmt.Errorf("NS %s returned %s for %s", ns, dns.RcodeToString[r.Rcode], fqdn) - } - - var records []string - - var found bool - for _, rr := range r.Answer { - if txt, ok := rr.(*dns.TXT); ok { - record := strings.Join(txt.Txt, "") - records = append(records, record) - if record == value { - found = true - break - } - } - } - - if !found { - return false, fmt.Errorf("NS %s did not return the expected TXT record [fqdn: %s, value: %s]: %s", ns, fqdn, value, strings.Join(records, " ,")) - } - } - - return true, nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go b/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go deleted file mode 100644 index c1cf3d45e..000000000 --- a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge.go +++ /dev/null @@ -1,65 +0,0 @@ -package http01 - -import ( - "fmt" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -// ChallengePath returns the URL path for the `http-01` challenge -func ChallengePath(token string) string { - return "/.well-known/acme-challenge/" + token -} - -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge { - return &Challenge{ - core: core, - validate: validate, - provider: provider, - } -} - -func (c *Challenge) SetProvider(provider challenge.Provider) { - c.provider = provider -} - -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := challenge.GetTargetedDomain(authz) - log.Infof("[%s] acme: Trying to solve HTTP-01", domain) - - chlng, err := challenge.FindChallenge(challenge.HTTP01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %v", domain, err) - } - defer func() { - err := c.provider.CleanUp(authz.Identifier.Value, chlng.Token, keyAuth) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v", domain, err) - } - }() - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} diff --git a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go b/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go deleted file mode 100644 index 9f4429111..000000000 --- a/vendor/github.com/go-acme/lego/challenge/http01/http_challenge_server.go +++ /dev/null @@ -1,96 +0,0 @@ -package http01 - -import ( - "fmt" - "net" - "net/http" - "strings" - - "github.com/go-acme/lego/log" -) - -// ProviderServer implements ChallengeProvider for `http-01` challenge -// It may be instantiated without using the NewProviderServer function if -// you want only to use the default values. -type ProviderServer struct { - iface string - port string - done chan bool - listener net.Listener -} - -// NewProviderServer creates a new ProviderServer on the selected interface and port. -// Setting iface and / or port to an empty string will make the server fall back to -// the "any" interface and port 80 respectively. -func NewProviderServer(iface, port string) *ProviderServer { - return &ProviderServer{iface: iface, port: port} -} - -// Present starts a web server and makes the token available at `ChallengePath(token)` for web requests. -func (s *ProviderServer) Present(domain, token, keyAuth string) error { - if s.port == "" { - s.port = "80" - } - - var err error - s.listener, err = net.Listen("tcp", s.GetAddress()) - if err != nil { - return fmt.Errorf("could not start HTTP server for challenge -> %v", err) - } - - s.done = make(chan bool) - go s.serve(domain, token, keyAuth) - return nil -} - -func (s *ProviderServer) GetAddress() string { - return net.JoinHostPort(s.iface, s.port) -} - -// CleanUp closes the HTTP server and removes the token from `ChallengePath(token)` -func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error { - if s.listener == nil { - return nil - } - s.listener.Close() - <-s.done - return nil -} - -func (s *ProviderServer) serve(domain, token, keyAuth string) { - path := ChallengePath(token) - - // The handler validates the HOST header and request type. - // For validation it then writes the token the server returned with the challenge - mux := http.NewServeMux() - mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) { - if strings.HasPrefix(r.Host, domain) && r.Method == http.MethodGet { - w.Header().Add("Content-Type", "text/plain") - _, err := w.Write([]byte(keyAuth)) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - log.Infof("[%s] Served key authentication", domain) - } else { - log.Warnf("Received request for domain %s with method %s but the domain did not match any challenge. Please ensure your are passing the HOST header properly.", r.Host, r.Method) - _, err := w.Write([]byte("TEST")) - if err != nil { - http.Error(w, err.Error(), http.StatusInternalServerError) - return - } - } - }) - - httpServer := &http.Server{Handler: mux} - - // Once httpServer is shut down - // we don't want any lingering connections, so disable KeepAlives. - httpServer.SetKeepAlivesEnabled(false) - - err := httpServer.Serve(s.listener) - if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - log.Println(err) - } - s.done <- true -} diff --git a/vendor/github.com/go-acme/lego/challenge/provider.go b/vendor/github.com/go-acme/lego/challenge/provider.go deleted file mode 100644 index d7cc213f7..000000000 --- a/vendor/github.com/go-acme/lego/challenge/provider.go +++ /dev/null @@ -1,28 +0,0 @@ -package challenge - -import "time" - -// Provider enables implementing a custom challenge -// provider. Present presents the solution to a challenge available to -// be solved. CleanUp will be called by the challenge if Present ends -// in a non-error state. -type Provider interface { - Present(domain, token, keyAuth string) error - CleanUp(domain, token, keyAuth string) error -} - -// ProviderTimeout allows for implementing a -// Provider where an unusually long timeout is required when -// waiting for an ACME challenge to be satisfied, such as when -// checking for DNS record propagation. If an implementor of a -// Provider provides a Timeout method, then the return values -// of the Timeout method will be used when appropriate by the acme -// package. The interval value is the time between checks. -// -// The default values used for timeout and interval are 60 seconds and -// 2 seconds respectively. These are used when no Timeout method is -// defined for the Provider. -type ProviderTimeout interface { - Provider - Timeout() (timeout, interval time.Duration) -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/errors.go b/vendor/github.com/go-acme/lego/challenge/resolver/errors.go deleted file mode 100644 index 9d6091432..000000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/errors.go +++ /dev/null @@ -1,25 +0,0 @@ -package resolver - -import ( - "bytes" - "fmt" - "sort" -) - -// obtainError is returned when there are specific errors available per domain. -type obtainError map[string]error - -func (e obtainError) Error() string { - buffer := bytes.NewBufferString("acme: Error -> One or more domains had a problem:\n") - - var domains []string - for domain := range e { - domains = append(domains, domain) - } - sort.Strings(domains) - - for _, domain := range domains { - buffer.WriteString(fmt.Sprintf("[%s] %s\n", domain, e[domain])) - } - return buffer.String() -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/prober.go b/vendor/github.com/go-acme/lego/challenge/resolver/prober.go deleted file mode 100644 index b787caf13..000000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/prober.go +++ /dev/null @@ -1,173 +0,0 @@ -package resolver - -import ( - "fmt" - "time" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -// Interface for all challenge solvers to implement. -type solver interface { - Solve(authorization acme.Authorization) error -} - -// Interface for challenges like dns, where we can set a record in advance for ALL challenges. -// This saves quite a bit of time vs creating the records and solving them serially. -type preSolver interface { - PreSolve(authorization acme.Authorization) error -} - -// Interface for challenges like dns, where we can solve all the challenges before to delete them. -type cleanup interface { - CleanUp(authorization acme.Authorization) error -} - -type sequential interface { - Sequential() (bool, time.Duration) -} - -// an authz with the solver we have chosen and the index of the challenge associated with it -type selectedAuthSolver struct { - authz acme.Authorization - solver solver -} - -type Prober struct { - solverManager *SolverManager -} - -func NewProber(solverManager *SolverManager) *Prober { - return &Prober{ - solverManager: solverManager, - } -} - -// Solve Looks through the challenge combinations to find a solvable match. -// Then solves the challenges in series and returns. -func (p *Prober) Solve(authorizations []acme.Authorization) error { - failures := make(obtainError) - - var authSolvers []*selectedAuthSolver - var authSolversSequential []*selectedAuthSolver - - // Loop through the resources, basically through the domains. - // First pass just selects a solver for each authz. - for _, authz := range authorizations { - domain := challenge.GetTargetedDomain(authz) - if authz.Status == acme.StatusValid { - // Boulder might recycle recent validated authz (see issue #267) - log.Infof("[%s] acme: authorization already valid; skipping challenge", domain) - continue - } - - if solvr := p.solverManager.chooseSolver(authz); solvr != nil { - authSolver := &selectedAuthSolver{authz: authz, solver: solvr} - - switch s := solvr.(type) { - case sequential: - if ok, _ := s.Sequential(); ok { - authSolversSequential = append(authSolversSequential, authSolver) - } else { - authSolvers = append(authSolvers, authSolver) - } - default: - authSolvers = append(authSolvers, authSolver) - } - } else { - failures[domain] = fmt.Errorf("[%s] acme: could not determine solvers", domain) - } - } - - parallelSolve(authSolvers, failures) - - sequentialSolve(authSolversSequential, failures) - - // Be careful not to return an empty failures map, - // for even an empty obtainError is a non-nil error value - if len(failures) > 0 { - return failures - } - return nil -} - -func sequentialSolve(authSolvers []*selectedAuthSolver, failures obtainError) { - for i, authSolver := range authSolvers { - // Submit the challenge - domain := challenge.GetTargetedDomain(authSolver.authz) - - if solvr, ok := authSolver.solver.(preSolver); ok { - err := solvr.PreSolve(authSolver.authz) - if err != nil { - failures[domain] = err - cleanUp(authSolver.solver, authSolver.authz) - continue - } - } - - // Solve challenge - err := authSolver.solver.Solve(authSolver.authz) - if err != nil { - failures[domain] = err - cleanUp(authSolver.solver, authSolver.authz) - continue - } - - // Clean challenge - cleanUp(authSolver.solver, authSolver.authz) - - if len(authSolvers)-1 > i { - solvr := authSolver.solver.(sequential) - _, interval := solvr.Sequential() - log.Infof("sequence: wait for %s", interval) - time.Sleep(interval) - } - } -} - -func parallelSolve(authSolvers []*selectedAuthSolver, failures obtainError) { - // For all valid preSolvers, first submit the challenges so they have max time to propagate - for _, authSolver := range authSolvers { - authz := authSolver.authz - if solvr, ok := authSolver.solver.(preSolver); ok { - err := solvr.PreSolve(authz) - if err != nil { - failures[challenge.GetTargetedDomain(authz)] = err - } - } - } - - defer func() { - // Clean all created TXT records - for _, authSolver := range authSolvers { - cleanUp(authSolver.solver, authSolver.authz) - } - }() - - // Finally solve all challenges for real - for _, authSolver := range authSolvers { - authz := authSolver.authz - domain := challenge.GetTargetedDomain(authz) - if failures[domain] != nil { - // already failed in previous loop - continue - } - - err := authSolver.solver.Solve(authz) - if err != nil { - failures[domain] = err - } - } -} - -func cleanUp(solvr solver, authz acme.Authorization) { - if solvr, ok := solvr.(cleanup); ok { - domain := challenge.GetTargetedDomain(authz) - err := solvr.CleanUp(authz) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v ", domain, err) - } - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go b/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go deleted file mode 100644 index de6f02db8..000000000 --- a/vendor/github.com/go-acme/lego/challenge/resolver/solver_manager.go +++ /dev/null @@ -1,169 +0,0 @@ -package resolver - -import ( - "context" - "errors" - "fmt" - "sort" - "strconv" - "time" - - "github.com/cenkalti/backoff" - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/challenge/http01" - "github.com/go-acme/lego/challenge/tlsalpn01" - "github.com/go-acme/lego/log" -) - -type byType []acme.Challenge - -func (a byType) Len() int { return len(a) } -func (a byType) Swap(i, j int) { a[i], a[j] = a[j], a[i] } -func (a byType) Less(i, j int) bool { return a[i].Type > a[j].Type } - -type SolverManager struct { - core *api.Core - solvers map[challenge.Type]solver -} - -func NewSolversManager(core *api.Core) *SolverManager { - return &SolverManager{ - solvers: map[challenge.Type]solver{}, - core: core, - } -} - -// SetHTTP01Provider specifies a custom provider p that can solve the given HTTP-01 challenge. -func (c *SolverManager) SetHTTP01Provider(p challenge.Provider) error { - c.solvers[challenge.HTTP01] = http01.NewChallenge(c.core, validate, p) - return nil -} - -// SetTLSALPN01Provider specifies a custom provider p that can solve the given TLS-ALPN-01 challenge. -func (c *SolverManager) SetTLSALPN01Provider(p challenge.Provider) error { - c.solvers[challenge.TLSALPN01] = tlsalpn01.NewChallenge(c.core, validate, p) - return nil -} - -// SetDNS01Provider specifies a custom provider p that can solve the given DNS-01 challenge. -func (c *SolverManager) SetDNS01Provider(p challenge.Provider, opts ...dns01.ChallengeOption) error { - c.solvers[challenge.DNS01] = dns01.NewChallenge(c.core, validate, p, opts...) - return nil -} - -// Remove Remove a challenge type from the available solvers. -func (c *SolverManager) Remove(chlgType challenge.Type) { - delete(c.solvers, chlgType) -} - -// Checks all challenges from the server in order and returns the first matching solver. -func (c *SolverManager) chooseSolver(authz acme.Authorization) solver { - // Allow to have a deterministic challenge order - sort.Sort(byType(authz.Challenges)) - - domain := challenge.GetTargetedDomain(authz) - for _, chlg := range authz.Challenges { - if solvr, ok := c.solvers[challenge.Type(chlg.Type)]; ok { - log.Infof("[%s] acme: use %s solver", domain, chlg.Type) - return solvr - } - log.Infof("[%s] acme: Could not find solver for: %s", domain, chlg.Type) - } - - return nil -} - -func validate(core *api.Core, domain string, chlg acme.Challenge) error { - chlng, err := core.Challenges.New(chlg.URL) - if err != nil { - return fmt.Errorf("failed to initiate challenge: %v", err) - } - - valid, err := checkChallengeStatus(chlng) - if err != nil { - return err - } - - if valid { - log.Infof("[%s] The server validated our request", domain) - return nil - } - - ra, err := strconv.Atoi(chlng.RetryAfter) - if err != nil { - // The ACME server MUST return a Retry-After. - // If it doesn't, we'll just poll hard. - // Boulder does not implement the ability to retry challenges or the Retry-After header. - // https://github.com/letsencrypt/boulder/blob/master/docs/acme-divergences.md#section-82 - ra = 5 - } - initialInterval := time.Duration(ra) * time.Second - - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = initialInterval - bo.MaxInterval = 10 * initialInterval - bo.MaxElapsedTime = 100 * initialInterval - - ctx, cancel := context.WithCancel(context.Background()) - - // After the path is sent, the ACME server will access our server. - // Repeatedly check the server for an updated status on our request. - operation := func() error { - authz, err := core.Authorizations.Get(chlng.AuthorizationURL) - if err != nil { - cancel() - return err - } - - valid, err := checkAuthorizationStatus(authz) - if err != nil { - cancel() - return err - } - - if valid { - log.Infof("[%s] The server validated our request", domain) - return nil - } - - return errors.New("the server didn't respond to our request") - } - - return backoff.Retry(operation, backoff.WithContext(bo, ctx)) -} - -func checkChallengeStatus(chlng acme.ExtendedChallenge) (bool, error) { - switch chlng.Status { - case acme.StatusValid: - return true, nil - case acme.StatusPending, acme.StatusProcessing: - return false, nil - case acme.StatusInvalid: - return false, chlng.Error - default: - return false, errors.New("the server returned an unexpected state") - } -} - -func checkAuthorizationStatus(authz acme.Authorization) (bool, error) { - switch authz.Status { - case acme.StatusValid: - return true, nil - case acme.StatusPending, acme.StatusProcessing: - return false, nil - case acme.StatusDeactivated, acme.StatusExpired, acme.StatusRevoked: - return false, fmt.Errorf("the authorization state %s", authz.Status) - case acme.StatusInvalid: - for _, chlg := range authz.Challenges { - if chlg.Status == acme.StatusInvalid && chlg.Error != nil { - return false, chlg.Error - } - } - return false, fmt.Errorf("the authorization state %s", authz.Status) - default: - return false, errors.New("the server returned an unexpected state") - } -} diff --git a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go b/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go deleted file mode 100644 index a3fa7ef46..000000000 --- a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge.go +++ /dev/null @@ -1,129 +0,0 @@ -package tlsalpn01 - -import ( - "crypto/rsa" - "crypto/sha256" - "crypto/tls" - "crypto/x509/pkix" - "encoding/asn1" - "fmt" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/log" -) - -// idPeAcmeIdentifierV1 is the SMI Security for PKIX Certification Extension OID referencing the ACME extension. -// Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-5.1 -var idPeAcmeIdentifierV1 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31} - -type ValidateFunc func(core *api.Core, domain string, chlng acme.Challenge) error - -type Challenge struct { - core *api.Core - validate ValidateFunc - provider challenge.Provider -} - -func NewChallenge(core *api.Core, validate ValidateFunc, provider challenge.Provider) *Challenge { - return &Challenge{ - core: core, - validate: validate, - provider: provider, - } -} - -func (c *Challenge) SetProvider(provider challenge.Provider) { - c.provider = provider -} - -// Solve manages the provider to validate and solve the challenge. -func (c *Challenge) Solve(authz acme.Authorization) error { - domain := authz.Identifier.Value - log.Infof("[%s] acme: Trying to solve TLS-ALPN-01", challenge.GetTargetedDomain(authz)) - - chlng, err := challenge.FindChallenge(challenge.TLSALPN01, authz) - if err != nil { - return err - } - - // Generate the Key Authorization for the challenge - keyAuth, err := c.core.GetKeyAuthorization(chlng.Token) - if err != nil { - return err - } - - err = c.provider.Present(domain, chlng.Token, keyAuth) - if err != nil { - return fmt.Errorf("[%s] acme: error presenting token: %v", challenge.GetTargetedDomain(authz), err) - } - defer func() { - err := c.provider.CleanUp(domain, chlng.Token, keyAuth) - if err != nil { - log.Warnf("[%s] acme: error cleaning up: %v", challenge.GetTargetedDomain(authz), err) - } - }() - - chlng.KeyAuthorization = keyAuth - return c.validate(c.core, domain, chlng) -} - -// ChallengeBlocks returns PEM blocks (certPEMBlock, keyPEMBlock) with the acmeValidation-v1 extension -// and domain name for the `tls-alpn-01` challenge. -func ChallengeBlocks(domain, keyAuth string) ([]byte, []byte, error) { - // Compute the SHA-256 digest of the key authorization. - zBytes := sha256.Sum256([]byte(keyAuth)) - - value, err := asn1.Marshal(zBytes[:sha256.Size]) - if err != nil { - return nil, nil, err - } - - // Add the keyAuth digest as the acmeValidation-v1 extension - // (marked as critical such that it won't be used by non-ACME software). - // Reference: https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-05#section-3 - extensions := []pkix.Extension{ - { - Id: idPeAcmeIdentifierV1, - Critical: true, - Value: value, - }, - } - - // Generate a new RSA key for the certificates. - tempPrivateKey, err := certcrypto.GeneratePrivateKey(certcrypto.RSA2048) - if err != nil { - return nil, nil, err - } - - rsaPrivateKey := tempPrivateKey.(*rsa.PrivateKey) - - // Generate the PEM certificate using the provided private key, domain, and extra extensions. - tempCertPEM, err := certcrypto.GeneratePemCert(rsaPrivateKey, domain, extensions) - if err != nil { - return nil, nil, err - } - - // Encode the private key into a PEM format. We'll need to use it to generate the x509 keypair. - rsaPrivatePEM := certcrypto.PEMEncode(rsaPrivateKey) - - return tempCertPEM, rsaPrivatePEM, nil -} - -// ChallengeCert returns a certificate with the acmeValidation-v1 extension -// and domain name for the `tls-alpn-01` challenge. -func ChallengeCert(domain, keyAuth string) (*tls.Certificate, error) { - tempCertPEM, rsaPrivatePEM, err := ChallengeBlocks(domain, keyAuth) - if err != nil { - return nil, err - } - - cert, err := tls.X509KeyPair(tempCertPEM, rsaPrivatePEM) - if err != nil { - return nil, err - } - - return &cert, nil -} diff --git a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go b/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go deleted file mode 100644 index 61e353bef..000000000 --- a/vendor/github.com/go-acme/lego/challenge/tlsalpn01/tls_alpn_challenge_server.go +++ /dev/null @@ -1,95 +0,0 @@ -package tlsalpn01 - -import ( - "crypto/tls" - "fmt" - "net" - "net/http" - "strings" - - "github.com/go-acme/lego/log" -) - -const ( - // ACMETLS1Protocol is the ALPN Protocol ID for the ACME-TLS/1 Protocol. - ACMETLS1Protocol = "acme-tls/1" - - // defaultTLSPort is the port that the ProviderServer will default to - // when no other port is provided. - defaultTLSPort = "443" -) - -// ProviderServer implements ChallengeProvider for `TLS-ALPN-01` challenge. -// It may be instantiated without using the NewProviderServer -// if you want only to use the default values. -type ProviderServer struct { - iface string - port string - listener net.Listener -} - -// NewProviderServer creates a new ProviderServer on the selected interface and port. -// Setting iface and / or port to an empty string will make the server fall back to -// the "any" interface and port 443 respectively. -func NewProviderServer(iface, port string) *ProviderServer { - return &ProviderServer{iface: iface, port: port} -} - -func (s *ProviderServer) GetAddress() string { - return net.JoinHostPort(s.iface, s.port) -} - -// Present generates a certificate with a SHA-256 digest of the keyAuth provided -// as the acmeValidation-v1 extension value to conform to the ACME-TLS-ALPN spec. -func (s *ProviderServer) Present(domain, token, keyAuth string) error { - if s.port == "" { - // Fallback to port 443 if the port was not provided. - s.port = defaultTLSPort - } - - // Generate the challenge certificate using the provided keyAuth and domain. - cert, err := ChallengeCert(domain, keyAuth) - if err != nil { - return err - } - - // Place the generated certificate with the extension into the TLS config - // so that it can serve the correct details. - tlsConf := new(tls.Config) - tlsConf.Certificates = []tls.Certificate{*cert} - - // We must set that the `acme-tls/1` application level protocol is supported - // so that the protocol negotiation can succeed. Reference: - // https://tools.ietf.org/html/draft-ietf-acme-tls-alpn-01#section-5.2 - tlsConf.NextProtos = []string{ACMETLS1Protocol} - - // Create the listener with the created tls.Config. - s.listener, err = tls.Listen("tcp", s.GetAddress(), tlsConf) - if err != nil { - return fmt.Errorf("could not start HTTPS server for challenge -> %v", err) - } - - // Shut the server down when we're finished. - go func() { - err := http.Serve(s.listener, nil) - if err != nil && !strings.Contains(err.Error(), "use of closed network connection") { - log.Println(err) - } - }() - - return nil -} - -// CleanUp closes the HTTPS server. -func (s *ProviderServer) CleanUp(domain, token, keyAuth string) error { - if s.listener == nil { - return nil - } - - // Server was created, close it. - if err := s.listener.Close(); err != nil && err != http.ErrServerClosed { - return err - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/lego/client.go b/vendor/github.com/go-acme/lego/lego/client.go deleted file mode 100644 index c55dd25d3..000000000 --- a/vendor/github.com/go-acme/lego/lego/client.go +++ /dev/null @@ -1,74 +0,0 @@ -package lego - -import ( - "errors" - "net/url" - - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/certificate" - "github.com/go-acme/lego/challenge/resolver" - "github.com/go-acme/lego/registration" -) - -// Client is the user-friendly way to ACME -type Client struct { - Certificate *certificate.Certifier - Challenge *resolver.SolverManager - Registration *registration.Registrar - core *api.Core -} - -// NewClient creates a new ACME client on behalf of the user. -// The client will depend on the ACME directory located at CADirURL for the rest of its actions. -// A private key of type keyType (see KeyType constants) will be generated when requesting a new certificate if one isn't provided. -func NewClient(config *Config) (*Client, error) { - if config == nil { - return nil, errors.New("a configuration must be provided") - } - - _, err := url.Parse(config.CADirURL) - if err != nil { - return nil, err - } - - if config.HTTPClient == nil { - return nil, errors.New("the HTTP client cannot be nil") - } - - privateKey := config.User.GetPrivateKey() - if privateKey == nil { - return nil, errors.New("private key was nil") - } - - var kid string - if reg := config.User.GetRegistration(); reg != nil { - kid = reg.URI - } - - core, err := api.New(config.HTTPClient, config.UserAgent, config.CADirURL, kid, privateKey) - if err != nil { - return nil, err - } - - solversManager := resolver.NewSolversManager(core) - - prober := resolver.NewProber(solversManager) - certifier := certificate.NewCertifier(core, prober, certificate.CertifierOptions{KeyType: config.Certificate.KeyType, Timeout: config.Certificate.Timeout}) - - return &Client{ - Certificate: certifier, - Challenge: solversManager, - Registration: registration.NewRegistrar(core, config.User), - core: core, - }, nil -} - -// GetToSURL returns the current ToS URL from the Directory -func (c *Client) GetToSURL() string { - return c.core.GetDirectory().Meta.TermsOfService -} - -// GetExternalAccountRequired returns the External Account Binding requirement of the Directory -func (c *Client) GetExternalAccountRequired() bool { - return c.core.GetDirectory().Meta.ExternalAccountRequired -} diff --git a/vendor/github.com/go-acme/lego/lego/client_config.go b/vendor/github.com/go-acme/lego/lego/client_config.go deleted file mode 100644 index 2421d7fa3..000000000 --- a/vendor/github.com/go-acme/lego/lego/client_config.go +++ /dev/null @@ -1,104 +0,0 @@ -package lego - -import ( - "crypto/tls" - "crypto/x509" - "fmt" - "io/ioutil" - "net" - "net/http" - "os" - "time" - - "github.com/go-acme/lego/certcrypto" - "github.com/go-acme/lego/registration" -) - -const ( - // caCertificatesEnvVar is the environment variable name that can be used to - // specify the path to PEM encoded CA Certificates that can be used to - // authenticate an ACME server with a HTTPS certificate not issued by a CA in - // the system-wide trusted root list. - caCertificatesEnvVar = "LEGO_CA_CERTIFICATES" - - // caServerNameEnvVar is the environment variable name that can be used to - // specify the CA server name that can be used to - // authenticate an ACME server with a HTTPS certificate not issued by a CA in - // the system-wide trusted root list. - caServerNameEnvVar = "LEGO_CA_SERVER_NAME" - - // LEDirectoryProduction URL to the Let's Encrypt production - LEDirectoryProduction = "https://acme-v02.api.letsencrypt.org/directory" - - // LEDirectoryStaging URL to the Let's Encrypt staging - LEDirectoryStaging = "https://acme-staging-v02.api.letsencrypt.org/directory" -) - -type Config struct { - CADirURL string - User registration.User - UserAgent string - HTTPClient *http.Client - Certificate CertificateConfig -} - -func NewConfig(user registration.User) *Config { - return &Config{ - CADirURL: LEDirectoryProduction, - User: user, - HTTPClient: createDefaultHTTPClient(), - Certificate: CertificateConfig{ - KeyType: certcrypto.RSA2048, - Timeout: 30 * time.Second, - }, - } -} - -type CertificateConfig struct { - KeyType certcrypto.KeyType - Timeout time.Duration -} - -// createDefaultHTTPClient Creates an HTTP client with a reasonable timeout value -// and potentially a custom *x509.CertPool -// based on the caCertificatesEnvVar environment variable (see the `initCertPool` function) -func createDefaultHTTPClient() *http.Client { - return &http.Client{ - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - }).DialContext, - TLSHandshakeTimeout: 15 * time.Second, - ResponseHeaderTimeout: 15 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - TLSClientConfig: &tls.Config{ - ServerName: os.Getenv(caServerNameEnvVar), - RootCAs: initCertPool(), - }, - }, - } -} - -// initCertPool creates a *x509.CertPool populated with the PEM certificates -// found in the filepath specified in the caCertificatesEnvVar OS environment -// variable. If the caCertificatesEnvVar is not set then initCertPool will -// return nil. If there is an error creating a *x509.CertPool from the provided -// caCertificatesEnvVar value then initCertPool will panic. -func initCertPool() *x509.CertPool { - if customCACertsPath := os.Getenv(caCertificatesEnvVar); customCACertsPath != "" { - customCAs, err := ioutil.ReadFile(customCACertsPath) - if err != nil { - panic(fmt.Sprintf("error reading %s=%q: %v", - caCertificatesEnvVar, customCACertsPath, err)) - } - certPool := x509.NewCertPool() - if ok := certPool.AppendCertsFromPEM(customCAs); !ok { - panic(fmt.Sprintf("error creating x509 cert pool from %s=%q: %v", - caCertificatesEnvVar, customCACertsPath, err)) - } - return certPool - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/log/logger.go b/vendor/github.com/go-acme/lego/log/logger.go deleted file mode 100644 index 22ec98f0a..000000000 --- a/vendor/github.com/go-acme/lego/log/logger.go +++ /dev/null @@ -1,59 +0,0 @@ -package log - -import ( - "log" - "os" -) - -// Logger is an optional custom logger. -var Logger StdLogger = log.New(os.Stdout, "", log.LstdFlags) - -// StdLogger interface for Standard Logger. -type StdLogger interface { - Fatal(args ...interface{}) - Fatalln(args ...interface{}) - Fatalf(format string, args ...interface{}) - Print(args ...interface{}) - Println(args ...interface{}) - Printf(format string, args ...interface{}) -} - -// Fatal writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Fatal(args ...interface{}) { - Logger.Fatal(args...) -} - -// Fatalf writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Fatalf(format string, args ...interface{}) { - Logger.Fatalf(format, args...) -} - -// Print writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Print(args ...interface{}) { - Logger.Print(args...) -} - -// Println writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Println(args ...interface{}) { - Logger.Println(args...) -} - -// Printf writes a log entry. -// It uses Logger if not nil, otherwise it uses the default log.Logger. -func Printf(format string, args ...interface{}) { - Logger.Printf(format, args...) -} - -// Warnf writes a log entry. -func Warnf(format string, args ...interface{}) { - Printf("[WARN] "+format, args...) -} - -// Infof writes a log entry. -func Infof(format string, args ...interface{}) { - Printf("[INFO] "+format, args...) -} diff --git a/vendor/github.com/go-acme/lego/platform/config/env/env.go b/vendor/github.com/go-acme/lego/platform/config/env/env.go deleted file mode 100644 index f489c657a..000000000 --- a/vendor/github.com/go-acme/lego/platform/config/env/env.go +++ /dev/null @@ -1,163 +0,0 @@ -package env - -import ( - "errors" - "fmt" - "io/ioutil" - "os" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/log" -) - -// Get environment variables -func Get(names ...string) (map[string]string, error) { - values := map[string]string{} - - var missingEnvVars []string - for _, envVar := range names { - value := GetOrFile(envVar) - if value == "" { - missingEnvVars = append(missingEnvVars, envVar) - } - values[envVar] = value - } - - if len(missingEnvVars) > 0 { - return nil, fmt.Errorf("some credentials information are missing: %s", strings.Join(missingEnvVars, ",")) - } - - return values, nil -} - -// GetWithFallback Get environment variable values -// The first name in each group is use as key in the result map -// -// // LEGO_ONE="ONE" -// // LEGO_TWO="TWO" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => "LEGO_ONE" = "ONE" -// -// ---- -// -// // LEGO_ONE="" -// // LEGO_TWO="TWO" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => "LEGO_ONE" = "TWO" -// -// ---- -// -// // LEGO_ONE="" -// // LEGO_TWO="" -// env.GetWithFallback([]string{"LEGO_ONE", "LEGO_TWO"}) -// // => error -// -func GetWithFallback(groups ...[]string) (map[string]string, error) { - values := map[string]string{} - - var missingEnvVars []string - for _, names := range groups { - if len(names) == 0 { - return nil, errors.New("undefined environment variable names") - } - - value, envVar := getOneWithFallback(names[0], names[1:]...) - if len(value) == 0 { - missingEnvVars = append(missingEnvVars, envVar) - continue - } - values[envVar] = value - } - - if len(missingEnvVars) > 0 { - return nil, fmt.Errorf("some credentials information are missing: %s", strings.Join(missingEnvVars, ",")) - } - - return values, nil -} - -func getOneWithFallback(main string, names ...string) (string, string) { - value := GetOrFile(main) - if len(value) > 0 { - return value, main - } - - for _, name := range names { - value := GetOrFile(name) - if len(value) > 0 { - return value, main - } - } - - return "", main -} - -// GetOrDefaultInt returns the given environment variable value as an integer. -// Returns the default if the envvar cannot be coopered to an int, or is not found. -func GetOrDefaultInt(envVar string, defaultValue int) int { - v, err := strconv.Atoi(GetOrFile(envVar)) - if err != nil { - return defaultValue - } - - return v -} - -// GetOrDefaultSecond returns the given environment variable value as an time.Duration (second). -// Returns the default if the envvar cannot be coopered to an int, or is not found. -func GetOrDefaultSecond(envVar string, defaultValue time.Duration) time.Duration { - v := GetOrDefaultInt(envVar, -1) - if v < 0 { - return defaultValue - } - - return time.Duration(v) * time.Second -} - -// GetOrDefaultString returns the given environment variable value as a string. -// Returns the default if the envvar cannot be find. -func GetOrDefaultString(envVar string, defaultValue string) string { - v := GetOrFile(envVar) - if len(v) == 0 { - return defaultValue - } - - return v -} - -// GetOrDefaultBool returns the given environment variable value as a boolean. -// Returns the default if the envvar cannot be coopered to a boolean, or is not found. -func GetOrDefaultBool(envVar string, defaultValue bool) bool { - v, err := strconv.ParseBool(GetOrFile(envVar)) - if err != nil { - return defaultValue - } - - return v -} - -// GetOrFile Attempts to resolve 'key' as an environment variable. -// Failing that, it will check to see if '_FILE' exists. -// If so, it will attempt to read from the referenced file to populate a value. -func GetOrFile(envVar string) string { - envVarValue := os.Getenv(envVar) - if envVarValue != "" { - return envVarValue - } - - fileVar := envVar + "_FILE" - fileVarValue := os.Getenv(fileVar) - if fileVarValue == "" { - return envVarValue - } - - fileContents, err := ioutil.ReadFile(fileVarValue) - if err != nil { - log.Printf("Failed to read the file %s (defined by env var %s): %s", fileVarValue, fileVar, err) - return "" - } - - return strings.TrimSuffix(string(fileContents), "\n") -} diff --git a/vendor/github.com/go-acme/lego/platform/wait/wait.go b/vendor/github.com/go-acme/lego/platform/wait/wait.go deleted file mode 100644 index 97af5dceb..000000000 --- a/vendor/github.com/go-acme/lego/platform/wait/wait.go +++ /dev/null @@ -1,33 +0,0 @@ -package wait - -import ( - "fmt" - "time" - - "github.com/go-acme/lego/log" -) - -// For polls the given function 'f', once every 'interval', up to 'timeout'. -func For(msg string, timeout, interval time.Duration, f func() (bool, error)) error { - log.Infof("Wait for %s [timeout: %s, interval: %s]", msg, timeout, interval) - - var lastErr string - timeUp := time.After(timeout) - for { - select { - case <-timeUp: - return fmt.Errorf("time limit exceeded: last error: %s", lastErr) - default: - } - - stop, err := f() - if stop { - return nil - } - if err != nil { - lastErr = err.Error() - } - - time.Sleep(interval) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go b/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go deleted file mode 100644 index 3edac7875..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/acmedns/acmedns.go +++ /dev/null @@ -1,162 +0,0 @@ -// Package acmedns implements a DNS provider for solving DNS-01 challenges using Joohoi's acme-dns project. -// For more information see the ACME-DNS homepage: https://github.com/joohoi/acme-dns -package acmedns - -import ( - "errors" - "fmt" - - "github.com/cpu/goacmedns" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // envNamespace is the prefix for ACME-DNS environment variables. - envNamespace = "ACME_DNS_" - // apiBaseEnvVar is the environment variable name for the ACME-DNS API address - // (e.g. https://acmedns.your-domain.com). - apiBaseEnvVar = envNamespace + "API_BASE" - // storagePathEnvVar is the environment variable name for the ACME-DNS JSON account data file. - // A per-domain account will be registered/persisted to this file and used for TXT updates. - storagePathEnvVar = envNamespace + "STORAGE_PATH" -) - -// acmeDNSClient is an interface describing the goacmedns.Client functions the DNSProvider uses. -// It makes it easier for tests to shim a mock Client into the DNSProvider. -type acmeDNSClient interface { - // UpdateTXTRecord updates the provided account's TXT record - // to the given value or returns an error. - UpdateTXTRecord(goacmedns.Account, string) error - // RegisterAccount registers and returns a new account - // with the given allowFrom restriction or returns an error. - RegisterAccount([]string) (goacmedns.Account, error) -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface for -// an ACME-DNS server. -type DNSProvider struct { - client acmeDNSClient - storage goacmedns.Storage -} - -// NewDNSProvider creates an ACME-DNS provider using file based account storage. -// Its configuration is loaded from the environment by reading apiBaseEnvVar and storagePathEnvVar. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiBaseEnvVar, storagePathEnvVar) - if err != nil { - return nil, fmt.Errorf("acme-dns: %v", err) - } - - client := goacmedns.NewClient(values[apiBaseEnvVar]) - storage := goacmedns.NewFileStorage(values[storagePathEnvVar], 0600) - return NewDNSProviderClient(client, storage) -} - -// NewDNSProviderClient creates an ACME-DNS DNSProvider with the given acmeDNSClient and goacmedns.Storage. -func NewDNSProviderClient(client acmeDNSClient, storage goacmedns.Storage) (*DNSProvider, error) { - if client == nil { - return nil, errors.New("ACME-DNS Client must be not nil") - } - - if storage == nil { - return nil, errors.New("ACME-DNS Storage must be not nil") - } - - return &DNSProvider{ - client: client, - storage: storage, - }, nil -} - -// ErrCNAMERequired is returned by Present when the Domain indicated had no -// existing ACME-DNS account in the Storage and additional setup is required. -// The user must create a CNAME in the DNS zone for Domain that aliases FQDN -// to Target in order to complete setup for the ACME-DNS account that was created. -type ErrCNAMERequired struct { - // The Domain that is being issued for. - Domain string - // The alias of the CNAME (left hand DNS label). - FQDN string - // The RDATA of the CNAME (right hand side, canonical name). - Target string -} - -// Error returns a descriptive message for the ErrCNAMERequired instance telling -// the user that a CNAME needs to be added to the DNS zone of c.Domain before -// the ACME-DNS hook will work. The CNAME to be created should be of the form: -// {{ c.FQDN }} CNAME {{ c.Target }} -func (e ErrCNAMERequired) Error() string { - return fmt.Sprintf("acme-dns: new account created for %q. "+ - "To complete setup for %q you must provision the following "+ - "CNAME in your DNS zone and re-run this provider when it is "+ - "in place:\n"+ - "%s CNAME %s.", - e.Domain, e.Domain, e.FQDN, e.Target) -} - -// Present creates a TXT record to fulfill the DNS-01 challenge. -// If there is an existing account for the domain in the provider's storage -// then it will be used to set the challenge response TXT record with the ACME-DNS server and issuance will continue. -// If there is not an account for the given domain present in the DNSProvider storage -// one will be created and registered with the ACME DNS server and an ErrCNAMERequired error is returned. -// This will halt issuance and indicate to the user that a one-time manual setup is required for the domain. -func (d *DNSProvider) Present(domain, _, keyAuth string) error { - // Compute the challenge response FQDN and TXT value for the domain based - // on the keyAuth. - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // Check if credentials were previously saved for this domain. - account, err := d.storage.Fetch(domain) - // Errors other than goacmeDNS.ErrDomainNotFound are unexpected. - if err != nil && err != goacmedns.ErrDomainNotFound { - return err - } - if err == goacmedns.ErrDomainNotFound { - // The account did not exist. Create a new one and return an error - // indicating the required one-time manual CNAME setup. - return d.register(domain, fqdn) - } - - // Update the acme-dns TXT record. - return d.client.UpdateTXTRecord(account, value) -} - -// CleanUp removes the record matching the specified parameters. It is not -// implemented for the ACME-DNS provider. -func (d *DNSProvider) CleanUp(_, _, _ string) error { - // ACME-DNS doesn't support the notion of removing a record. - // For users of ACME-DNS it is expected the stale records remain in-place. - return nil -} - -// register creates a new ACME-DNS account for the given domain. -// If account creation works as expected a ErrCNAMERequired error is returned describing -// the one-time manual CNAME setup required to complete setup of the ACME-DNS hook for the domain. -// If any other error occurs it is returned as-is. -func (d *DNSProvider) register(domain, fqdn string) error { - // TODO(@cpu): Read CIDR whitelists from the environment - newAcct, err := d.client.RegisterAccount(nil) - if err != nil { - return err - } - - // Store the new account in the storage and call save to persist the data. - err = d.storage.Put(domain, newAcct) - if err != nil { - return err - } - err = d.storage.Save() - if err != nil { - return err - } - - // Stop issuance by returning an error. - // The user needs to perform a manual one-time CNAME setup in their DNS zone - // to complete the setup of the new account we created. - return ErrCNAMERequired{ - Domain: domain, - FQDN: fqdn, - Target: newAcct.FullDomain, - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go b/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go deleted file mode 100644 index 76c8ec7ad..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/alidns/alidns.go +++ /dev/null @@ -1,220 +0,0 @@ -// Package alidns implements a DNS provider for solving the DNS-01 challenge using Alibaba Cloud DNS. -package alidns - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/aliyun/alibaba-cloud-sdk-go/sdk" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/auth/credentials" - "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests" - "github.com/aliyun/alibaba-cloud-sdk-go/services/alidns" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultRegionID = "cn-hangzhou" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - SecretKey string - RegionID string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("ALICLOUD_TTL", 600), - PropagationTimeout: env.GetOrDefaultSecond("ALICLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("ALICLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPTimeout: env.GetOrDefaultSecond("ALICLOUD_HTTP_TIMEOUT", 10*time.Second), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *alidns.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Alibaba Cloud DNS. -// Credentials must be passed in the environment variables: ALICLOUD_ACCESS_KEY and ALICLOUD_SECRET_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("ALICLOUD_ACCESS_KEY", "ALICLOUD_SECRET_KEY") - if err != nil { - return nil, fmt.Errorf("alicloud: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["ALICLOUD_ACCESS_KEY"] - config.SecretKey = values["ALICLOUD_SECRET_KEY"] - config.RegionID = env.GetOrFile("ALICLOUD_REGION_ID") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for alidns. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("alicloud: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.SecretKey == "" { - return nil, fmt.Errorf("alicloud: credentials missing") - } - - if len(config.RegionID) == 0 { - config.RegionID = defaultRegionID - } - - conf := sdk.NewConfig().WithTimeout(config.HTTPTimeout) - credential := credentials.NewAccessKeyCredential(config.APIKey, config.SecretKey) - - client, err := alidns.NewClientWithOptions(config.RegionID, conf, credential) - if err != nil { - return nil, fmt.Errorf("alicloud: credentials failed: %v", err) - } - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - _, zoneName, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - recordAttributes := d.newTxtRecord(zoneName, fqdn, value) - - _, err = d.client.AddDomainRecord(recordAttributes) - if err != nil { - return fmt.Errorf("alicloud: API call failed: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - _, _, err = d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - - for _, rec := range records { - request := alidns.CreateDeleteDomainRecordRequest() - request.RecordId = rec.RecordId - _, err = d.client.DeleteDomainRecord(request) - if err != nil { - return fmt.Errorf("alicloud: %v", err) - } - } - return nil -} - -func (d *DNSProvider) getHostedZone(domain string) (string, string, error) { - request := alidns.CreateDescribeDomainsRequest() - - var domains []alidns.Domain - startPage := 1 - - for { - request.PageNumber = requests.NewInteger(startPage) - - response, err := d.client.DescribeDomains(request) - if err != nil { - return "", "", fmt.Errorf("API call failed: %v", err) - } - - domains = append(domains, response.Domains.Domain...) - - if response.PageNumber*response.PageSize >= response.TotalCount { - break - } - - startPage++ - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - - var hostedZone alidns.Domain - for _, zone := range domains { - if zone.DomainName == dns01.UnFqdn(authZone) { - hostedZone = zone - } - } - - if hostedZone.DomainId == "" { - return "", "", fmt.Errorf("zone %s not found in AliDNS for domain %s", authZone, domain) - } - return fmt.Sprintf("%v", hostedZone.DomainId), hostedZone.DomainName, nil -} - -func (d *DNSProvider) newTxtRecord(zone, fqdn, value string) *alidns.AddDomainRecordRequest { - request := alidns.CreateAddDomainRecordRequest() - request.Type = "TXT" - request.DomainName = zone - request.RR = d.extractRecordName(fqdn, zone) - request.Value = value - request.TTL = requests.NewInteger(d.config.TTL) - return request -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]alidns.Record, error) { - _, zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - request := alidns.CreateDescribeDomainRecordsRequest() - request.DomainName = zoneName - request.PageSize = requests.NewInteger(500) - - var records []alidns.Record - - result, err := d.client.DescribeDomainRecords(request) - if err != nil { - return records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneName) - for _, record := range result.DomainRecords.Record { - if record.RR == recordName { - records = append(records, record) - } - } - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go b/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go deleted file mode 100644 index 0d46f587f..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/auroradns/auroradns.go +++ /dev/null @@ -1,191 +0,0 @@ -// Package auroradns implements a DNS provider for solving the DNS-01 challenge using Aurora DNS. -package auroradns - -import ( - "errors" - "fmt" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/nrdcg/auroradns" -) - -const defaultBaseURL = "https://api.auroradns.eu" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - UserID string - Key string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("AURORA_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("AURORA_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("AURORA_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider describes a provider for AuroraDNS -type DNSProvider struct { - recordIDs map[string]string - recordIDsMu sync.Mutex - config *Config - client *auroradns.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for AuroraDNS. -// Credentials must be passed in the environment variables: -// AURORA_USER_ID and AURORA_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("AURORA_USER_ID", "AURORA_KEY") - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = env.GetOrFile("AURORA_ENDPOINT") - config.UserID = values["AURORA_USER_ID"] - config.Key = values["AURORA_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for AuroraDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("aurora: the configuration of the DNS provider is nil") - } - - if config.UserID == "" || config.Key == "" { - return nil, errors.New("aurora: some credentials information are missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - tr, err := auroradns.NewTokenTransport(config.UserID, config.Key) - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - client, err := auroradns.NewClient(tr.Client(), auroradns.WithBaseURL(config.BaseURL)) - if err != nil { - return nil, fmt.Errorf("aurora: %v", err) - } - - return &DNSProvider{ - config: config, - client: client, - recordIDs: make(map[string]string), - }, nil -} - -// Present creates a record with a secret -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("aurora: could not determine zone for domain: '%s'. %s", domain, err) - } - - // 1. Aurora will happily create the TXT record when it is provided a fqdn, - // but it will only appear in the control panel and will not be - // propagated to DNS servers. Extract and use subdomain instead. - // 2. A trailing dot in the fqdn will cause Aurora to add a trailing dot to - // the subdomain, resulting in _acme-challenge.. rather - // than _acme-challenge. - - subdomain := fqdn[0 : len(fqdn)-len(authZone)-1] - - authZone = dns01.UnFqdn(authZone) - - zone, err := d.getZoneInformationByName(authZone) - if err != nil { - return fmt.Errorf("aurora: could not create record: %v", err) - } - - record := auroradns.Record{ - RecordType: "TXT", - Name: subdomain, - Content: value, - TTL: d.config.TTL, - } - - newRecord, _, err := d.client.CreateRecord(zone.ID, record) - if err != nil { - return fmt.Errorf("aurora: could not create record: %v", err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = newRecord.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes a given record that was generated by Present -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - - if !ok { - return fmt.Errorf("unknown recordID for %q", fqdn) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("could not determine zone for domain: %q. %v", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - - zone, err := d.getZoneInformationByName(authZone) - if err != nil { - return err - } - - _, _, err = d.client.DeleteRecord(zone.ID, recordID) - if err != nil { - return err - } - - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getZoneInformationByName(name string) (auroradns.Zone, error) { - zs, _, err := d.client.ListZones() - if err != nil { - return auroradns.Zone{}, err - } - - for _, element := range zs { - if element.Name == name { - return element, nil - } - } - - return auroradns.Zone{}, fmt.Errorf("could not find Zone record") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go b/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go deleted file mode 100644 index f10bfc90b..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/azure/azure.go +++ /dev/null @@ -1,274 +0,0 @@ -// Package azure implements a DNS provider for solving the DNS-01 challenge using azure DNS. -// Azure doesn't like trailing dots on domain names, most of the acme code does. -package azure - -import ( - "context" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strings" - "time" - - "github.com/Azure/azure-sdk-for-go/services/dns/mgmt/2017-09-01/dns" - "github.com/Azure/go-autorest/autorest" - "github.com/Azure/go-autorest/autorest/adal" - "github.com/Azure/go-autorest/autorest/azure" - "github.com/Azure/go-autorest/autorest/azure/auth" - "github.com/Azure/go-autorest/autorest/to" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultMetadataEndpoint = "http://169.254.169.254" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - // optional if using instance metadata service - ClientID string - ClientSecret string - TenantID string - - SubscriptionID string - ResourceGroup string - - MetadataEndpoint string - - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("AZURE_TTL", 60), - PropagationTimeout: env.GetOrDefaultSecond("AZURE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("AZURE_POLLING_INTERVAL", 2*time.Second), - MetadataEndpoint: env.GetOrFile("AZURE_METADATA_ENDPOINT"), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - authorizer autorest.Authorizer -} - -// NewDNSProvider returns a DNSProvider instance configured for azure. -// Credentials can be passed in the environment variables: -// AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_SUBSCRIPTION_ID, AZURE_TENANT_ID, AZURE_RESOURCE_GROUP -// If the credentials are _not_ set via the environment, -// then it will attempt to get a bearer token via the instance metadata service. -// see: https://github.com/Azure/go-autorest/blob/v10.14.0/autorest/azure/auth/auth.go#L38-L42 -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - config.SubscriptionID = env.GetOrFile("AZURE_SUBSCRIPTION_ID") - config.ResourceGroup = env.GetOrFile("AZURE_RESOURCE_GROUP") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Azure. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("azure: the configuration of the DNS provider is nil") - } - - if config.HTTPClient == nil { - config.HTTPClient = http.DefaultClient - } - - authorizer, err := getAuthorizer(config) - if err != nil { - return nil, err - } - - if config.SubscriptionID == "" { - subsID, err := getMetadata(config, "subscriptionId") - if err != nil { - return nil, fmt.Errorf("azure: %v", err) - } - - if subsID == "" { - return nil, errors.New("azure: SubscriptionID is missing") - } - config.SubscriptionID = subsID - } - - if config.ResourceGroup == "" { - resGroup, err := getMetadata(config, "resourceGroupName") - if err != nil { - return nil, fmt.Errorf("azure: %v", err) - } - - if resGroup == "" { - return nil, errors.New("azure: ResourceGroup is missing") - } - config.ResourceGroup = resGroup - } - - return &DNSProvider{config: config, authorizer: authorizer}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneID(ctx, fqdn) - if err != nil { - return fmt.Errorf("azure: %v", err) - } - - rsc := dns.NewRecordSetsClient(d.config.SubscriptionID) - rsc.Authorizer = d.authorizer - - relative := toRelativeRecord(fqdn, dns01.ToFqdn(zone)) - - // Get existing record set - rset, err := rsc.Get(ctx, d.config.ResourceGroup, zone, relative, dns.TXT) - if err != nil { - detailedError, ok := err.(autorest.DetailedError) - if !ok || detailedError.StatusCode != http.StatusNotFound { - return fmt.Errorf("azure: %v", err) - } - } - - // Construct unique TXT records using map - uniqRecords := map[string]struct{}{value: {}} - if rset.RecordSetProperties != nil && rset.TxtRecords != nil { - for _, txtRecord := range *rset.TxtRecords { - // Assume Value doesn't contain multiple strings - if txtRecord.Value != nil && len(*txtRecord.Value) > 0 { - uniqRecords[(*txtRecord.Value)[0]] = struct{}{} - } - } - } - - var txtRecords []dns.TxtRecord - for txt := range uniqRecords { - txtRecords = append(txtRecords, dns.TxtRecord{Value: &[]string{txt}}) - } - - rec := dns.RecordSet{ - Name: &relative, - RecordSetProperties: &dns.RecordSetProperties{ - TTL: to.Int64Ptr(int64(d.config.TTL)), - TxtRecords: &txtRecords, - }, - } - - _, err = rsc.CreateOrUpdate(ctx, d.config.ResourceGroup, zone, relative, dns.TXT, rec, "", "") - if err != nil { - return fmt.Errorf("azure: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneID(ctx, fqdn) - if err != nil { - return fmt.Errorf("azure: %v", err) - } - - relative := toRelativeRecord(fqdn, dns01.ToFqdn(zone)) - rsc := dns.NewRecordSetsClient(d.config.SubscriptionID) - rsc.Authorizer = d.authorizer - - _, err = rsc.Delete(ctx, d.config.ResourceGroup, zone, relative, dns.TXT, "") - if err != nil { - return fmt.Errorf("azure: %v", err) - } - return nil -} - -// Checks that azure has a zone for this domain name. -func (d *DNSProvider) getHostedZoneID(ctx context.Context, fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - dc := dns.NewZonesClient(d.config.SubscriptionID) - dc.Authorizer = d.authorizer - - zone, err := dc.Get(ctx, d.config.ResourceGroup, dns01.UnFqdn(authZone)) - if err != nil { - return "", err - } - - // zone.Name shouldn't have a trailing dot(.) - return to.String(zone.Name), nil -} - -// Returns the relative record to the domain -func toRelativeRecord(domain, zone string) string { - return dns01.UnFqdn(strings.TrimSuffix(domain, zone)) -} - -func getAuthorizer(config *Config) (autorest.Authorizer, error) { - if config.ClientID != "" && config.ClientSecret != "" && config.TenantID != "" { - oauthConfig, err := adal.NewOAuthConfig(azure.PublicCloud.ActiveDirectoryEndpoint, config.TenantID) - if err != nil { - return nil, err - } - - spt, err := adal.NewServicePrincipalToken(*oauthConfig, config.ClientID, config.ClientSecret, azure.PublicCloud.ResourceManagerEndpoint) - if err != nil { - return nil, err - } - - spt.SetSender(config.HTTPClient) - return autorest.NewBearerAuthorizer(spt), nil - } - - return auth.NewAuthorizerFromEnvironment() -} - -// Fetches metadata from environment or he instance metadata service -// borrowed from https://github.com/Microsoft/azureimds/blob/master/imdssample.go -func getMetadata(config *Config, field string) (string, error) { - metadataEndpoint := config.MetadataEndpoint - if len(metadataEndpoint) == 0 { - metadataEndpoint = defaultMetadataEndpoint - } - - resource := fmt.Sprintf("%s/metadata/instance/compute/%s", metadataEndpoint, field) - req, err := http.NewRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - req.Header.Add("Metadata", "True") - - q := req.URL.Query() - q.Add("format", "text") - q.Add("api-version", "2017-12-01") - req.URL.RawQuery = q.Encode() - - resp, err := config.HTTPClient.Do(req) - if err != nil { - return "", err - } - defer resp.Body.Close() - - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - return string(respBody), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go b/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go deleted file mode 100644 index 2079711c6..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bindman/bindman.go +++ /dev/null @@ -1,99 +0,0 @@ -// Package bindman implements a DNS provider for solving the DNS-01 challenge. -package bindman - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/labbsr0x/bindman-dns-webhook/src/client" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - PropagationTimeout time.Duration - PollingInterval time.Duration - BaseURL string - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("BINDMAN_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("BINDMAN_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("BINDMAN_HTTP_TIMEOUT", time.Minute), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Bindman's Address Manager REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *client.DNSWebhookClient -} - -// NewDNSProvider returns a DNSProvider instance configured for Bindman. -// BINDMAN_MANAGER_ADDRESS should have the scheme, hostname, and port (if required) of the authoritative Bindman Manager server. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("BINDMAN_MANAGER_ADDRESS") - if err != nil { - return nil, fmt.Errorf("bindman: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = values["BINDMAN_MANAGER_ADDRESS"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Bindman. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("bindman: the configuration of the DNS provider is nil") - } - - if config.BaseURL == "" { - return nil, fmt.Errorf("bindman: bindman manager address missing") - } - - bClient, err := client.New(config.BaseURL, config.HTTPClient) - if err != nil { - return nil, fmt.Errorf("bindman: %v", err) - } - - return &DNSProvider{config: config, client: bClient}, nil -} - -// Present creates a TXT record using the specified parameters. -// This will *not* create a subzone to contain the TXT record, -// so make sure the FQDN specified is within an extant zone. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - if err := d.client.AddRecord(fqdn, "TXT", value); err != nil { - return fmt.Errorf("bindman: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - if err := d.client.RemoveRecord(fqdn, "TXT"); err != nil { - return fmt.Errorf("bindman: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go b/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go deleted file mode 100644 index d3becf804..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/bluecat.go +++ /dev/null @@ -1,201 +0,0 @@ -// Package bluecat implements a DNS provider for solving the DNS-01 challenge using a self-hosted Bluecat Address Manager. -package bluecat - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - configType = "Configuration" - viewType = "View" - zoneType = "Zone" - txtType = "TXTRecord" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - UserName string - Password string - ConfigName string - DNSView string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("BLUECAT_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("BLUECAT_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("BLUECAT_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("BLUECAT_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Bluecat's Address Manager REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for Bluecat DNS. -// Credentials must be passed in the environment variables: BLUECAT_SERVER_URL, BLUECAT_USER_NAME and BLUECAT_PASSWORD. -// BLUECAT_SERVER_URL should have the scheme, hostname, and port (if required) of the authoritative Bluecat BAM server. -// The REST endpoint will be appended. -// In addition, the Configuration name and external DNS View Name must be passed in BLUECAT_CONFIG_NAME and BLUECAT_DNS_VIEW -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("BLUECAT_SERVER_URL", "BLUECAT_USER_NAME", "BLUECAT_PASSWORD", "BLUECAT_CONFIG_NAME", "BLUECAT_DNS_VIEW") - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = values["BLUECAT_SERVER_URL"] - config.UserName = values["BLUECAT_USER_NAME"] - config.Password = values["BLUECAT_PASSWORD"] - config.ConfigName = values["BLUECAT_CONFIG_NAME"] - config.DNSView = values["BLUECAT_DNS_VIEW"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Bluecat DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("bluecat: the configuration of the DNS provider is nil") - } - - if config.BaseURL == "" || config.UserName == "" || config.Password == "" || config.ConfigName == "" || config.DNSView == "" { - return nil, fmt.Errorf("bluecat: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -// This will *not* create a subzone to contain the TXT record, -// so make sure the FQDN specified is within an extant zone. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.login() - if err != nil { - return err - } - - viewID, err := d.lookupViewID(d.config.DNSView) - if err != nil { - return err - } - - parentZoneID, name, err := d.lookupParentZoneID(viewID, fqdn) - if err != nil { - return err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentZoneID), 10), - } - - body := bluecatEntity{ - Name: name, - Type: "TXTRecord", - Properties: fmt.Sprintf("ttl=%d|absoluteName=%s|txt=%s|", d.config.TTL, fqdn, value), - } - - resp, err := d.sendRequest(http.MethodPost, "addEntity", body, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - addTxtBytes, _ := ioutil.ReadAll(resp.Body) - addTxtResp := string(addTxtBytes) - // addEntity responds only with body text containing the ID of the created record - _, err = strconv.ParseUint(addTxtResp, 10, 64) - if err != nil { - return fmt.Errorf("bluecat: addEntity request failed: %s", addTxtResp) - } - - err = d.deploy(parentZoneID) - if err != nil { - return err - } - - return d.logout() -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - err := d.login() - if err != nil { - return err - } - - viewID, err := d.lookupViewID(d.config.DNSView) - if err != nil { - return err - } - - parentID, name, err := d.lookupParentZoneID(viewID, fqdn) - if err != nil { - return err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentID), 10), - "name": name, - "type": txtType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - var txtRec entityResponse - err = json.NewDecoder(resp.Body).Decode(&txtRec) - if err != nil { - return fmt.Errorf("bluecat: %v", err) - } - queryArgs = map[string]string{ - "objectId": strconv.FormatUint(uint64(txtRec.ID), 10), - } - - resp, err = d.sendRequest(http.MethodDelete, http.MethodDelete, nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - err = d.deploy(parentID) - if err != nil { - return err - } - - return d.logout() -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go b/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go deleted file mode 100644 index d910594ce..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/bluecat/client.go +++ /dev/null @@ -1,249 +0,0 @@ -package bluecat - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "regexp" - "strconv" - "strings" -) - -// JSON body for Bluecat entity requests and responses -type bluecatEntity struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Properties string `json:"properties"` -} - -type entityResponse struct { - ID uint `json:"id"` - Name string `json:"name"` - Type string `json:"type"` - Properties string `json:"properties"` -} - -// Starts a new Bluecat API Session. Authenticates using customerName, userName, -// password and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - queryArgs := map[string]string{ - "username": d.config.UserName, - "password": d.config.Password, - } - - resp, err := d.sendRequest(http.MethodGet, "login", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - authBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("bluecat: %v", err) - } - authResp := string(authBytes) - - if strings.Contains(authResp, "Authentication Error") { - msg := strings.Trim(authResp, "\"") - return fmt.Errorf("bluecat: request failed: %s", msg) - } - - // Upon success, API responds with "Session Token-> BAMAuthToken: dQfuRMTUxNjc3MjcyNDg1ODppcGFybXM= <- for User : username" - d.token = regexp.MustCompile("BAMAuthToken: [^ ]+").FindString(authResp) - return nil -} - -// Destroys Bluecat Session -func (d *DNSProvider) logout() error { - if len(d.token) == 0 { - // nothing to do - return nil - } - - resp, err := d.sendRequest(http.MethodGet, "logout", nil, nil) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return fmt.Errorf("bluecat: request failed to delete session with HTTP status code %d", resp.StatusCode) - } - - authBytes, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - authResp := string(authBytes) - - if !strings.Contains(authResp, "successfully") { - msg := strings.Trim(authResp, "\"") - return fmt.Errorf("bluecat: request failed to delete session: %s", msg) - } - - d.token = "" - - return nil -} - -// Lookup the entity ID of the configuration named in our properties -func (d *DNSProvider) lookupConfID() (uint, error) { - queryArgs := map[string]string{ - "parentId": strconv.Itoa(0), - "name": d.config.ConfigName, - "type": configType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var conf entityResponse - err = json.NewDecoder(resp.Body).Decode(&conf) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - return conf.ID, nil -} - -// Find the DNS view with the given name within -func (d *DNSProvider) lookupViewID(viewName string) (uint, error) { - confID, err := d.lookupConfID() - if err != nil { - return 0, err - } - - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(confID), 10), - "name": viewName, - "type": viewType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var view entityResponse - err = json.NewDecoder(resp.Body).Decode(&view) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - - return view.ID, nil -} - -// Return the entityId of the parent zone by recursing from the root view -// Also return the simple name of the host -func (d *DNSProvider) lookupParentZoneID(viewID uint, fqdn string) (uint, string, error) { - parentViewID := viewID - name := "" - - if fqdn != "" { - zones := strings.Split(strings.Trim(fqdn, "."), ".") - last := len(zones) - 1 - name = zones[0] - - for i := last; i > -1; i-- { - zoneID, err := d.getZone(parentViewID, zones[i]) - if err != nil || zoneID == 0 { - return parentViewID, name, err - } - if i > 0 { - name = strings.Join(zones[0:i], ".") - } - parentViewID = zoneID - } - } - - return parentViewID, name, nil -} - -// Get the DNS zone with the specified name under the parentId -func (d *DNSProvider) getZone(parentID uint, name string) (uint, error) { - queryArgs := map[string]string{ - "parentId": strconv.FormatUint(uint64(parentID), 10), - "name": name, - "type": zoneType, - } - - resp, err := d.sendRequest(http.MethodGet, "getEntityByName", nil, queryArgs) - - // Return an empty zone if the named zone doesn't exist - if resp != nil && resp.StatusCode == http.StatusNotFound { - return 0, fmt.Errorf("bluecat: could not find zone named %s", name) - } - if err != nil { - return 0, err - } - defer resp.Body.Close() - - var zone entityResponse - err = json.NewDecoder(resp.Body).Decode(&zone) - if err != nil { - return 0, fmt.Errorf("bluecat: %v", err) - } - - return zone.ID, nil -} - -// Deploy the DNS config for the specified entity to the authoritative servers -func (d *DNSProvider) deploy(entityID uint) error { - queryArgs := map[string]string{ - "entityId": strconv.FormatUint(uint64(entityID), 10), - } - - resp, err := d.sendRequest(http.MethodPost, "quickDeploy", nil, queryArgs) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// Send a REST request, using query parameters specified. The Authorization -// header will be set if we have an active auth token -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}, queryArgs map[string]string) (*http.Response, error) { - url := fmt.Sprintf("%s/Services/REST/v1/%s", d.config.BaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("Authorization", d.token) - } - - // Add all query parameters - q := req.URL.Query() - for argName, argVal := range queryArgs { - q.Add(argName, argVal) - } - req.URL.RawQuery = q.Encode() - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("bluecat: %v", err) - } - - if resp.StatusCode >= 400 { - errBytes, _ := ioutil.ReadAll(resp.Body) - errResp := string(errBytes) - return nil, fmt.Errorf("bluecat: request failed with HTTP status code %d\n Full message: %s", - resp.StatusCode, errResp) - } - - return resp, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go b/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go deleted file mode 100644 index 85b298a98..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudflare/cloudflare.go +++ /dev/null @@ -1,157 +0,0 @@ -// Package cloudflare implements a DNS provider for solving the DNS-01 challenge using cloudflare DNS. -package cloudflare - -import ( - "errors" - "fmt" - "net/http" - "time" - - cloudflare "github.com/cloudflare/cloudflare-go" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - minTTL = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AuthEmail string - AuthKey string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("CLOUDFLARE_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("CLOUDFLARE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("CLOUDFLARE_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDFLARE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - client *cloudflare.API - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Cloudflare. -// Credentials must be passed in the environment variables: -// CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.GetWithFallback( - []string{"CLOUDFLARE_EMAIL", "CF_API_EMAIL"}, - []string{"CLOUDFLARE_API_KEY", "CF_API_KEY"}) - if err != nil { - return nil, fmt.Errorf("cloudflare: %v", err) - } - - config := NewDefaultConfig() - config.AuthEmail = values["CLOUDFLARE_EMAIL"] - config.AuthKey = values["CLOUDFLARE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Cloudflare. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("cloudflare: the configuration of the DNS provider is nil") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("cloudflare: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client, err := cloudflare.New(config.AuthKey, config.AuthEmail, cloudflare.HTTPClient(config.HTTPClient)) - if err != nil { - return nil, err - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("cloudflare: %v", err) - } - - zoneID, err := d.client.ZoneIDByName(dns01.UnFqdn(authZone)) - if err != nil { - return fmt.Errorf("cloudflare: failed to find zone %s: %v", authZone, err) - } - - dnsRecord := cloudflare.DNSRecord{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: value, - TTL: d.config.TTL, - } - - response, err := d.client.CreateDNSRecord(zoneID, dnsRecord) - if err != nil { - return fmt.Errorf("cloudflare: failed to create TXT record: %v", err) - } - - if !response.Success { - return fmt.Errorf("cloudflare: failed to create TXT record: %+v %+v", response.Errors, response.Messages) - } - - log.Infof("cloudflare: new record for %s, ID %s", domain, response.Result.ID) - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("cloudflare: %v", err) - } - - zoneID, err := d.client.ZoneIDByName(dns01.UnFqdn(authZone)) - if err != nil { - return fmt.Errorf("cloudflare: failed to find zone %s: %v", authZone, err) - } - - dnsRecord := cloudflare.DNSRecord{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - } - - records, err := d.client.DNSRecords(zoneID, dnsRecord) - if err != nil { - return fmt.Errorf("cloudflare: failed to find TXT records: %v", err) - } - - for _, record := range records { - err = d.client.DeleteDNSRecord(zoneID, record.ID) - if err != nil { - log.Printf("cloudflare: failed to delete TXT record: %v", err) - } - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go deleted file mode 100644 index a33d3f099..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/cloudns.go +++ /dev/null @@ -1,121 +0,0 @@ -// Package cloudns implements a DNS provider for solving the DNS-01 challenge using ClouDNS DNS. -package cloudns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/cloudns/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AuthID string - AuthPassword string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("CLOUDNS_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("CLOUDNS_POLLING_INTERVAL", 4*time.Second), - TTL: env.GetOrDefaultInt("CLOUDNS_TTL", 60), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for ClouDNS. -// Credentials must be passed in the environment variables: -// CLOUDNS_AUTH_ID and CLOUDNS_AUTH_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CLOUDNS_AUTH_ID", "CLOUDNS_AUTH_PASSWORD") - if err != nil { - return nil, fmt.Errorf("ClouDNS: %v", err) - } - - config := NewDefaultConfig() - config.AuthID = values["CLOUDNS_AUTH_ID"] - config.AuthPassword = values["CLOUDNS_AUTH_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for ClouDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ClouDNS: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.AuthID, config.AuthPassword) - if err != nil { - return nil, fmt.Errorf("ClouDNS: %v", err) - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.client.GetZone(fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - err = d.client.AddTxtRecord(zone.Name, fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.client.GetZone(fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - record, err := d.client.FindTxtRecord(zone.Name, fqdn) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - - if record == nil { - return nil - } - - err = d.client.RemoveTxtRecord(record.ID, zone.Name) - if err != nil { - return fmt.Errorf("ClouDNS: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go deleted file mode 100644 index 92620e935..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudns/internal/client.go +++ /dev/null @@ -1,271 +0,0 @@ -package internal - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://api.cloudns.net/dns/" - -type apiResponse struct { - Status string `json:"status"` - StatusDescription string `json:"statusDescription"` -} - -type Zone struct { - Name string - Type string - Zone string - Status string // is an integer, but cast as string -} - -// TXTRecord a TXT record -type TXTRecord struct { - ID int `json:"id,string"` - Type string `json:"type"` - Host string `json:"host"` - Record string `json:"record"` - Failover int `json:"failover,string"` - TTL int `json:"ttl,string"` - Status int `json:"status"` -} - -type TXTRecords map[string]TXTRecord - -// NewClient creates a ClouDNS client -func NewClient(authID string, authPassword string) (*Client, error) { - if authID == "" { - return nil, fmt.Errorf("credentials missing: authID") - } - - if authPassword == "" { - return nil, fmt.Errorf("credentials missing: authPassword") - } - - baseURL, err := url.Parse(defaultBaseURL) - if err != nil { - return nil, err - } - - return &Client{ - authID: authID, - authPassword: authPassword, - HTTPClient: &http.Client{}, - BaseURL: baseURL, - }, nil -} - -// Client ClouDNS client -type Client struct { - authID string - authPassword string - HTTPClient *http.Client - BaseURL *url.URL -} - -// GetZone Get domain name information for a FQDN -func (c *Client) GetZone(authFQDN string) (*Zone, error) { - authZone, err := dns01.FindZoneByFqdn(authFQDN) - if err != nil { - return nil, err - } - - authZoneName := dns01.UnFqdn(authZone) - - reqURL := *c.BaseURL - reqURL.Path += "get-zone-info.json" - - q := reqURL.Query() - q.Add("domain-name", authZoneName) - reqURL.RawQuery = q.Encode() - - result, err := c.doRequest(http.MethodGet, &reqURL) - if err != nil { - return nil, err - } - - var zone Zone - - if len(result) > 0 { - if err = json.Unmarshal(result, &zone); err != nil { - return nil, fmt.Errorf("zone unmarshaling error: %v", err) - } - } - - if zone.Name == authZoneName { - return &zone, nil - } - - return nil, fmt.Errorf("zone %s not found for authFQDN %s", authZoneName, authFQDN) -} - -// FindTxtRecord return the TXT record a zone ID and a FQDN -func (c *Client) FindTxtRecord(zoneName, fqdn string) (*TXTRecord, error) { - host := dns01.UnFqdn(strings.TrimSuffix(dns01.UnFqdn(fqdn), zoneName)) - - reqURL := *c.BaseURL - reqURL.Path += "records.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("host", host) - q.Add("type", "TXT") - reqURL.RawQuery = q.Encode() - - result, err := c.doRequest(http.MethodGet, &reqURL) - if err != nil { - return nil, err - } - - // the API returns [] when there is no records. - if string(result) == "[]" { - return nil, nil - } - - var records TXTRecords - if err = json.Unmarshal(result, &records); err != nil { - return nil, fmt.Errorf("TXT record unmarshaling error: %v: %s", err, string(result)) - } - - for _, record := range records { - if record.Host == host && record.Type == "TXT" { - return &record, nil - } - } - - return nil, nil -} - -// AddTxtRecord add a TXT record -func (c *Client) AddTxtRecord(zoneName string, fqdn, value string, ttl int) error { - host := dns01.UnFqdn(strings.TrimSuffix(dns01.UnFqdn(fqdn), zoneName)) - - reqURL := *c.BaseURL - reqURL.Path += "add-record.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("host", host) - q.Add("record", value) - q.Add("ttl", strconv.Itoa(ttlRounder(ttl))) - q.Add("record-type", "TXT") - reqURL.RawQuery = q.Encode() - - raw, err := c.doRequest(http.MethodPost, &reqURL) - if err != nil { - return err - } - - resp := apiResponse{} - if err = json.Unmarshal(raw, &resp); err != nil { - return fmt.Errorf("apiResponse unmarshaling error: %v: %s", err, string(raw)) - } - - if resp.Status != "Success" { - return fmt.Errorf("fail to add TXT record: %s %s", resp.Status, resp.StatusDescription) - } - - return nil -} - -// RemoveTxtRecord remove a TXT record -func (c *Client) RemoveTxtRecord(recordID int, zoneName string) error { - reqURL := *c.BaseURL - reqURL.Path += "delete-record.json" - - q := reqURL.Query() - q.Add("domain-name", zoneName) - q.Add("record-id", strconv.Itoa(recordID)) - reqURL.RawQuery = q.Encode() - - raw, err := c.doRequest(http.MethodPost, &reqURL) - if err != nil { - return err - } - - resp := apiResponse{} - if err = json.Unmarshal(raw, &resp); err != nil { - return fmt.Errorf("apiResponse unmarshaling error: %v: %s", err, string(raw)) - } - - if resp.Status != "Success" { - return fmt.Errorf("fail to add TXT record: %s %s", resp.Status, resp.StatusDescription) - } - - return nil -} - -func (c *Client) doRequest(method string, url *url.URL) (json.RawMessage, error) { - req, err := c.buildRequest(method, url) - if err != nil { - return nil, err - } - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(req, content)) - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("invalid code (%v), error: %s", resp.StatusCode, content) - } - return content, nil -} - -func (c *Client) buildRequest(method string, url *url.URL) (*http.Request, error) { - q := url.Query() - q.Add("auth-id", c.authID) - q.Add("auth-password", c.authPassword) - url.RawQuery = q.Encode() - - req, err := http.NewRequest(method, url.String(), nil) - if err != nil { - return nil, fmt.Errorf("invalid request: %v", err) - } - - return req, nil -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} - -// https://www.cloudns.net/wiki/article/58/ -// Available TTL's: -// 60 = 1 minute -// 300 = 5 minutes -// 900 = 15 minutes -// 1800 = 30 minutes -// 3600 = 1 hour -// 21600 = 6 hours -// 43200 = 12 hours -// 86400 = 1 day -// 172800 = 2 days -// 259200 = 3 days -// 604800 = 1 week -// 1209600 = 2 weeks -// 2592000 = 1 month -func ttlRounder(ttl int) int { - for _, validTTL := range []int{60, 300, 900, 1800, 3600, 21600, 43200, 86400, 172800, 259200, 604800, 1209600} { - if ttl <= validTTL { - return validTTL - } - } - - return 2592000 -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go deleted file mode 100644 index ef70629bb..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/cloudxns.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package cloudxns implements a DNS provider for solving the DNS-01 challenge using CloudXNS DNS. -package cloudxns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/cloudxns/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - SecretKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("CLOUDXNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("CLOUDXNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("CLOUDXNS_TTL", dns01.DefaultTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CLOUDXNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for CloudXNS. -// Credentials must be passed in the environment variables: -// CLOUDXNS_API_KEY and CLOUDXNS_SECRET_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CLOUDXNS_API_KEY", "CLOUDXNS_SECRET_KEY") - if err != nil { - return nil, fmt.Errorf("CloudXNS: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["CLOUDXNS_API_KEY"] - config.SecretKey = values["CLOUDXNS_SECRET_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for CloudXNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("CloudXNS: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.APIKey, config.SecretKey) - if err != nil { - return nil, err - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - info, err := d.client.GetDomainInformation(fqdn) - if err != nil { - return err - } - - return d.client.AddTxtRecord(info, fqdn, value, d.config.TTL) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - info, err := d.client.GetDomainInformation(fqdn) - if err != nil { - return err - } - - record, err := d.client.FindTxtRecord(info.ID, fqdn) - if err != nil { - return err - } - - return d.client.RemoveTxtRecord(record.RecordID, info.ID) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go deleted file mode 100644 index be71c9bbe..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/cloudxns/internal/client.go +++ /dev/null @@ -1,208 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/md5" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://www.cloudxns.net/api2/" - -type apiResponse struct { - Code int `json:"code"` - Message string `json:"message"` - Data json.RawMessage `json:"data,omitempty"` -} - -// Data Domain information -type Data struct { - ID string `json:"id"` - Domain string `json:"domain"` - TTL int `json:"ttl,omitempty"` -} - -// TXTRecord a TXT record -type TXTRecord struct { - ID int `json:"domain_id,omitempty"` - RecordID string `json:"record_id,omitempty"` - - Host string `json:"host"` - Value string `json:"value"` - Type string `json:"type"` - LineID int `json:"line_id,string"` - TTL int `json:"ttl,string"` -} - -// NewClient creates a CloudXNS client -func NewClient(apiKey string, secretKey string) (*Client, error) { - if apiKey == "" { - return nil, fmt.Errorf("CloudXNS: credentials missing: apiKey") - } - - if secretKey == "" { - return nil, fmt.Errorf("CloudXNS: credentials missing: secretKey") - } - - return &Client{ - apiKey: apiKey, - secretKey: secretKey, - HTTPClient: &http.Client{}, - BaseURL: defaultBaseURL, - }, nil -} - -// Client CloudXNS client -type Client struct { - apiKey string - secretKey string - HTTPClient *http.Client - BaseURL string -} - -// GetDomainInformation Get domain name information for a FQDN -func (c *Client) GetDomainInformation(fqdn string) (*Data, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - result, err := c.doRequest(http.MethodGet, "domain", nil) - if err != nil { - return nil, err - } - - var domains []Data - if len(result) > 0 { - err = json.Unmarshal(result, &domains) - if err != nil { - return nil, fmt.Errorf("CloudXNS: domains unmarshaling error: %v", err) - } - } - - for _, data := range domains { - if data.Domain == authZone { - return &data, nil - } - } - - return nil, fmt.Errorf("CloudXNS: zone %s not found for domain %s", authZone, fqdn) -} - -// FindTxtRecord return the TXT record a zone ID and a FQDN -func (c *Client) FindTxtRecord(zoneID, fqdn string) (*TXTRecord, error) { - result, err := c.doRequest(http.MethodGet, fmt.Sprintf("record/%s?host_id=0&offset=0&row_num=2000", zoneID), nil) - if err != nil { - return nil, err - } - - var records []TXTRecord - err = json.Unmarshal(result, &records) - if err != nil { - return nil, fmt.Errorf("CloudXNS: TXT record unmarshaling error: %v", err) - } - - for _, record := range records { - if record.Host == dns01.UnFqdn(fqdn) && record.Type == "TXT" { - return &record, nil - } - } - - return nil, fmt.Errorf("CloudXNS: no existing record found for %q", fqdn) -} - -// AddTxtRecord add a TXT record -func (c *Client) AddTxtRecord(info *Data, fqdn, value string, ttl int) error { - id, err := strconv.Atoi(info.ID) - if err != nil { - return fmt.Errorf("CloudXNS: invalid zone ID: %v", err) - } - - payload := TXTRecord{ - ID: id, - Host: dns01.UnFqdn(strings.TrimSuffix(fqdn, info.Domain)), - Value: value, - Type: "TXT", - LineID: 1, - TTL: ttl, - } - - body, err := json.Marshal(payload) - if err != nil { - return fmt.Errorf("CloudXNS: record unmarshaling error: %v", err) - } - - _, err = c.doRequest(http.MethodPost, "record", body) - return err -} - -// RemoveTxtRecord remove a TXT record -func (c *Client) RemoveTxtRecord(recordID, zoneID string) error { - _, err := c.doRequest(http.MethodDelete, fmt.Sprintf("record/%s/%s", recordID, zoneID), nil) - return err -} - -func (c *Client) doRequest(method, uri string, body []byte) (json.RawMessage, error) { - req, err := c.buildRequest(method, uri, body) - if err != nil { - return nil, err - } - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("CloudXNS: %v", err) - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("CloudXNS: %s", toUnreadableBodyMessage(req, content)) - } - - var r apiResponse - err = json.Unmarshal(content, &r) - if err != nil { - return nil, fmt.Errorf("CloudXNS: response unmashaling error: %v: %s", err, toUnreadableBodyMessage(req, content)) - } - - if r.Code != 1 { - return nil, fmt.Errorf("CloudXNS: invalid code (%v), error: %s", r.Code, r.Message) - } - return r.Data, nil -} - -func (c *Client) buildRequest(method, uri string, body []byte) (*http.Request, error) { - url := c.BaseURL + uri - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, fmt.Errorf("CloudXNS: invalid request: %v", err) - } - - requestDate := time.Now().Format(time.RFC1123Z) - - req.Header.Set("API-KEY", c.apiKey) - req.Header.Set("API-REQUEST-DATE", requestDate) - req.Header.Set("API-HMAC", c.hmac(url, requestDate, string(body))) - req.Header.Set("API-FORMAT", "json") - - return req, nil -} - -func (c *Client) hmac(url, date, body string) string { - sum := md5.Sum([]byte(c.apiKey + url + body + date + c.secretKey)) - return hex.EncodeToString(sum[:]) -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go deleted file mode 100644 index 2a9621868..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/conoha.go +++ /dev/null @@ -1,148 +0,0 @@ -// Package conoha implements a DNS provider for solving the DNS-01 challenge using ConoHa DNS. -package conoha - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/conoha/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Region string - TenantID string - Username string - Password string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - Region: env.GetOrDefaultString("CONOHA_REGION", "tyo1"), - TTL: env.GetOrDefaultInt("CONOHA_TTL", 60), - PropagationTimeout: env.GetOrDefaultSecond("CONOHA_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("CONOHA_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("CONOHA_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for ConoHa DNS. -// Credentials must be passed in the environment variables: CONOHA_TENANT_ID, CONOHA_API_USERNAME, CONOHA_API_PASSWORD -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("CONOHA_TENANT_ID", "CONOHA_API_USERNAME", "CONOHA_API_PASSWORD") - if err != nil { - return nil, fmt.Errorf("conoha: %v", err) - } - - config := NewDefaultConfig() - config.TenantID = values["CONOHA_TENANT_ID"] - config.Username = values["CONOHA_API_USERNAME"] - config.Password = values["CONOHA_API_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for ConoHa DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("conoha: the configuration of the DNS provider is nil") - } - - if config.TenantID == "" || config.Username == "" || config.Password == "" { - return nil, errors.New("conoha: some credentials information are missing") - } - - auth := internal.Auth{ - TenantID: config.TenantID, - PasswordCredentials: internal.PasswordCredentials{ - Username: config.Username, - Password: config.Password, - }, - } - - client, err := internal.NewClient(config.Region, auth, config.HTTPClient) - if err != nil { - return nil, fmt.Errorf("conoha: failed to create client: %v", err) - } - - return &DNSProvider{config: config, client: client}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - id, err := d.client.GetDomainID(authZone) - if err != nil { - return fmt.Errorf("conoha: failed to get domain ID: %v", err) - } - - record := internal.Record{ - Name: fqdn, - Type: "TXT", - Data: value, - TTL: d.config.TTL, - } - - err = d.client.CreateRecord(id, record) - if err != nil { - return fmt.Errorf("conoha: failed to create record: %v", err) - } - - return nil -} - -// CleanUp clears ConoHa DNS TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domID, err := d.client.GetDomainID(authZone) - if err != nil { - return fmt.Errorf("conoha: failed to get domain ID: %v", err) - } - - recID, err := d.client.GetRecordID(domID, fqdn, "TXT", value) - if err != nil { - return fmt.Errorf("conoha: failed to get record ID: %v", err) - } - - err = d.client.DeleteRecord(domID, recID) - if err != nil { - return fmt.Errorf("conoha: failed to delete record: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go deleted file mode 100644 index 3136a24d6..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/conoha/internal/client.go +++ /dev/null @@ -1,205 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" -) - -const ( - identityBaseURL = "https://identity.%s.conoha.io" - dnsServiceBaseURL = "https://dns-service.%s.conoha.io" -) - -// IdentityRequest is an authentication request body. -type IdentityRequest struct { - Auth Auth `json:"auth"` -} - -// Auth is an authentication information. -type Auth struct { - TenantID string `json:"tenantId"` - PasswordCredentials PasswordCredentials `json:"passwordCredentials"` -} - -// PasswordCredentials is API-user's credentials. -type PasswordCredentials struct { - Username string `json:"username"` - Password string `json:"password"` -} - -// IdentityResponse is an authentication response body. -type IdentityResponse struct { - Access Access `json:"access"` -} - -// Access is an identity information. -type Access struct { - Token Token `json:"token"` -} - -// Token is an api access token. -type Token struct { - ID string `json:"id"` -} - -// DomainListResponse is a response of a domain listing request. -type DomainListResponse struct { - Domains []Domain `json:"domains"` -} - -// Domain is a hosted domain entry. -type Domain struct { - ID string `json:"id"` - Name string `json:"name"` -} - -// RecordListResponse is a response of record listing request. -type RecordListResponse struct { - Records []Record `json:"records"` -} - -// Record is a record entry. -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl"` -} - -// Client is a ConoHa API client. -type Client struct { - token string - endpoint string - httpClient *http.Client -} - -// NewClient returns a client instance logged into the ConoHa service. -func NewClient(region string, auth Auth, httpClient *http.Client) (*Client, error) { - if httpClient == nil { - httpClient = &http.Client{} - } - - c := &Client{httpClient: httpClient} - - c.endpoint = fmt.Sprintf(identityBaseURL, region) - - identity, err := c.getIdentity(auth) - if err != nil { - return nil, fmt.Errorf("failed to login: %v", err) - } - - c.token = identity.Access.Token.ID - c.endpoint = fmt.Sprintf(dnsServiceBaseURL, region) - - return c, nil -} - -func (c *Client) getIdentity(auth Auth) (*IdentityResponse, error) { - req := &IdentityRequest{Auth: auth} - - identity := &IdentityResponse{} - - err := c.do(http.MethodPost, "/v2.0/tokens", req, identity) - if err != nil { - return nil, err - } - - return identity, nil -} - -// GetDomainID returns an ID of specified domain. -func (c *Client) GetDomainID(domainName string) (string, error) { - domainList := &DomainListResponse{} - - err := c.do(http.MethodGet, "/v1/domains", nil, domainList) - if err != nil { - return "", err - } - - for _, domain := range domainList.Domains { - if domain.Name == domainName { - return domain.ID, nil - } - } - return "", fmt.Errorf("no such domain: %s", domainName) -} - -// GetRecordID returns an ID of specified record. -func (c *Client) GetRecordID(domainID, recordName, recordType, data string) (string, error) { - recordList := &RecordListResponse{} - - err := c.do(http.MethodGet, fmt.Sprintf("/v1/domains/%s/records", domainID), nil, recordList) - if err != nil { - return "", err - } - - for _, record := range recordList.Records { - if record.Name == recordName && record.Type == recordType && record.Data == data { - return record.ID, nil - } - } - return "", errors.New("no such record") -} - -// CreateRecord adds new record. -func (c *Client) CreateRecord(domainID string, record Record) error { - return c.do(http.MethodPost, fmt.Sprintf("/v1/domains/%s/records", domainID), record, nil) -} - -// DeleteRecord removes specified record. -func (c *Client) DeleteRecord(domainID, recordID string) error { - return c.do(http.MethodDelete, fmt.Sprintf("/v1/domains/%s/records/%s", domainID, recordID), nil, nil) -} - -func (c *Client) do(method, path string, payload, result interface{}) error { - body := bytes.NewReader(nil) - - if payload != nil { - bodyBytes, err := json.Marshal(payload) - if err != nil { - return err - } - body = bytes.NewReader(bodyBytes) - } - - req, err := http.NewRequest(method, c.endpoint+path, body) - if err != nil { - return err - } - - req.Header.Set("Accept", "application/json") - req.Header.Set("Content-Type", "application/json") - req.Header.Set("X-Auth-Token", c.token) - - resp, err := c.httpClient.Do(req) - if err != nil { - return err - } - - if resp.StatusCode != http.StatusOK { - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - return fmt.Errorf("HTTP request failed with status code %d: %s", resp.StatusCode, string(respBody)) - } - - if result != nil { - respBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - return json.Unmarshal(respBody, result) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go b/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go deleted file mode 100644 index 072784246..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/designate/designate.go +++ /dev/null @@ -1,249 +0,0 @@ -// Package designate implements a DNS provider for solving the DNS-01 challenge using the Designate DNSaaS for Openstack. -package designate - -import ( - "errors" - "fmt" - "log" - "os" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/gophercloud/gophercloud" - "github.com/gophercloud/gophercloud/openstack" - "github.com/gophercloud/gophercloud/openstack/dns/v2/recordsets" - "github.com/gophercloud/gophercloud/openstack/dns/v2/zones" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - opts gophercloud.AuthOptions -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DESIGNATE_TTL", 10), - PropagationTimeout: env.GetOrDefaultSecond("DESIGNATE_PROPAGATION_TIMEOUT", 10*time.Minute), - PollingInterval: env.GetOrDefaultSecond("DESIGNATE_POLLING_INTERVAL", 10*time.Second), - } -} - -// DNSProvider describes a provider for Designate -type DNSProvider struct { - config *Config - client *gophercloud.ServiceClient - dnsEntriesMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for Designate. -// Credentials must be passed in the environment variables: -// OS_AUTH_URL, OS_USERNAME, OS_PASSWORD, OS_TENANT_NAME, OS_REGION_NAME. -func NewDNSProvider() (*DNSProvider, error) { - _, err := env.Get("OS_AUTH_URL", "OS_USERNAME", "OS_PASSWORD", "OS_TENANT_NAME", "OS_REGION_NAME") - if err != nil { - return nil, fmt.Errorf("designate: %v", err) - } - - opts, err := openstack.AuthOptionsFromEnv() - if err != nil { - return nil, fmt.Errorf("designate: %v", err) - } - - config := NewDefaultConfig() - config.opts = opts - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Designate. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("designate: the configuration of the DNS provider is nil") - } - - provider, err := openstack.AuthenticatedClient(config.opts) - if err != nil { - return nil, fmt.Errorf("designate: failed to authenticate: %v", err) - } - - dnsClient, err := openstack.NewDNSV2(provider, gophercloud.EndpointOpts{ - Region: os.Getenv("OS_REGION_NAME"), - }) - if err != nil { - return nil, fmt.Errorf("designate: failed to get DNS provider: %v", err) - } - - return &DNSProvider{client: dnsClient, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("designate: couldn't get zone ID in Present: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - // use mutex to prevent race condition between creating the record and verifying it - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - existingRecord, err := d.getRecord(zoneID, fqdn) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - if existingRecord != nil { - if contains(existingRecord.Records, value) { - log.Printf("designate: the record already exists: %s", value) - return nil - } - - return d.updateRecord(existingRecord, value) - } - - err = d.createRecord(zoneID, fqdn, value) - if err != nil { - return fmt.Errorf("designate: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("designate: couldn't get zone ID in CleanUp: %v", err) - } - - // use mutex to prevent race condition between getting the record and deleting it - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - record, err := d.getRecord(zoneID, fqdn) - if err != nil { - return fmt.Errorf("designate: couldn't get Record ID in CleanUp: %v", err) - } - - if record == nil { - // Record is already deleted - return nil - } - - err = recordsets.Delete(d.client, zoneID, record.ID).ExtractErr() - if err != nil { - return fmt.Errorf("designate: error for %s in CleanUp: %v", fqdn, err) - } - return nil -} - -func contains(values []string, value string) bool { - for _, v := range values { - if v == value { - return true - } - } - return false -} - -func (d *DNSProvider) createRecord(zoneID, fqdn, value string) error { - createOpts := recordsets.CreateOpts{ - Name: fqdn, - Type: "TXT", - TTL: d.config.TTL, - Description: "ACME verification record", - Records: []string{value}, - } - - actual, err := recordsets.Create(d.client, zoneID, createOpts).Extract() - if err != nil { - return fmt.Errorf("error for %s in Present while creating record: %v", fqdn, err) - } - - if actual.Name != fqdn || actual.TTL != d.config.TTL { - return fmt.Errorf("the created record doesn't match what we wanted to create") - } - - return nil -} - -func (d *DNSProvider) updateRecord(record *recordsets.RecordSet, value string) error { - if contains(record.Records, value) { - log.Printf("skip: the record already exists: %s", value) - return nil - } - - values := append([]string{value}, record.Records...) - - updateOpts := recordsets.UpdateOpts{ - Description: &record.Description, - TTL: record.TTL, - Records: values, - } - - result := recordsets.Update(d.client, record.ZoneID, record.ID, updateOpts) - return result.Err -} - -func (d *DNSProvider) getZoneID(wanted string) (string, error) { - allPages, err := zones.List(d.client, nil).AllPages() - if err != nil { - return "", err - } - allZones, err := zones.ExtractZones(allPages) - if err != nil { - return "", err - } - - for _, zone := range allZones { - if zone.Name == wanted { - return zone.ID, nil - } - } - return "", fmt.Errorf("zone id not found for %s", wanted) -} - -func (d *DNSProvider) getRecord(zoneID string, wanted string) (*recordsets.RecordSet, error) { - allPages, err := recordsets.ListByZone(d.client, zoneID, nil).AllPages() - if err != nil { - return nil, err - } - allRecords, err := recordsets.ExtractRecordSets(allPages) - if err != nil { - return nil, err - } - - for _, record := range allRecords { - if record.Name == wanted { - return &record, nil - } - } - - return nil, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go deleted file mode 100644 index 48e335ae6..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/client.go +++ /dev/null @@ -1,132 +0,0 @@ -package digitalocean - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/challenge/dns01" -) - -const defaultBaseURL = "https://api.digitalocean.com" - -// txtRecordResponse represents a response from DO's API after making a TXT record -type txtRecordResponse struct { - DomainRecord record `json:"domain_record"` -} - -type record struct { - ID int `json:"id,omitempty"` - Type string `json:"type,omitempty"` - Name string `json:"name,omitempty"` - Data string `json:"data,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -type apiError struct { - ID string `json:"id"` - Message string `json:"message"` -} - -func (d *DNSProvider) removeTxtRecord(domain string, recordID int) error { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("could not determine zone for domain: '%s'. %s", domain, err) - } - - reqURL := fmt.Sprintf("%s/v2/domains/%s/records/%d", d.config.BaseURL, dns01.UnFqdn(authZone), recordID) - req, err := d.newRequest(http.MethodDelete, reqURL, nil) - if err != nil { - return err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return readError(req, resp) - } - - return nil -} - -func (d *DNSProvider) addTxtRecord(fqdn, value string) (*txtRecordResponse, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(fqdn)) - if err != nil { - return nil, fmt.Errorf("could not determine zone for domain: '%s'. %s", fqdn, err) - } - - reqData := record{Type: "TXT", Name: fqdn, Data: value, TTL: d.config.TTL} - body, err := json.Marshal(reqData) - if err != nil { - return nil, err - } - - reqURL := fmt.Sprintf("%s/v2/domains/%s/records", d.config.BaseURL, dns01.UnFqdn(authZone)) - req, err := d.newRequest(http.MethodPost, reqURL, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, readError(req, resp) - } - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(req, content)) - } - - // Everything looks good; but we'll need the ID later to delete the record - respData := &txtRecordResponse{} - err = json.Unmarshal(content, respData) - if err != nil { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(req, content)) - } - - return respData, nil -} - -func (d *DNSProvider) newRequest(method, reqURL string, body io.Reader) (*http.Request, error) { - req, err := http.NewRequest(method, reqURL, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.config.AuthToken)) - - return req, nil -} - -func readError(req *http.Request, resp *http.Response) error { - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return errors.New(toUnreadableBodyMessage(req, content)) - } - - var errInfo apiError - err = json.Unmarshal(content, &errInfo) - if err != nil { - return fmt.Errorf("apiError unmarshaling error: %v: %s", err, toUnreadableBodyMessage(req, content)) - } - - return fmt.Errorf("HTTP %d: %s: %s", resp.StatusCode, errInfo.ID, errInfo.Message) -} - -func toUnreadableBodyMessage(req *http.Request, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", req.URL, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go b/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go deleted file mode 100644 index 0492a596e..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/digitalocean/digitalocean.go +++ /dev/null @@ -1,131 +0,0 @@ -// Package digitalocean implements a DNS provider for solving the DNS-01 challenge using digitalocean DNS. -package digitalocean - -import ( - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - AuthToken string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - TTL: env.GetOrDefaultInt("DO_TTL", 30), - PropagationTimeout: env.GetOrDefaultSecond("DO_PROPAGATION_TIMEOUT", 60*time.Second), - PollingInterval: env.GetOrDefaultSecond("DO_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DO_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// that uses DigitalOcean's REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - recordIDs map[string]int - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for Digital -// Ocean. Credentials must be passed in the environment variable: -// DO_AUTH_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DO_AUTH_TOKEN") - if err != nil { - return nil, fmt.Errorf("digitalocean: %v", err) - } - - config := NewDefaultConfig() - config.AuthToken = values["DO_AUTH_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Digital Ocean. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("digitalocean: the configuration of the DNS provider is nil") - } - - if config.AuthToken == "" { - return nil, fmt.Errorf("digitalocean: credentials missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{ - config: config, - recordIDs: make(map[string]int), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - respData, err := d.addTxtRecord(fqdn, value) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = respData.DomainRecord.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - // get the record's unique ID from when we created it - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - if !ok { - return fmt.Errorf("digitalocean: unknown record ID for '%s'", fqdn) - } - - err = d.removeTxtRecord(authZone, recordID) - if err != nil { - return fmt.Errorf("digitalocean: %v", err) - } - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go b/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go deleted file mode 100644 index 194db1d30..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dns_providers.go +++ /dev/null @@ -1,189 +0,0 @@ -package dns - -import ( - "fmt" - - "github.com/go-acme/lego/challenge" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/providers/dns/acmedns" - "github.com/go-acme/lego/providers/dns/alidns" - "github.com/go-acme/lego/providers/dns/auroradns" - "github.com/go-acme/lego/providers/dns/azure" - "github.com/go-acme/lego/providers/dns/bindman" - "github.com/go-acme/lego/providers/dns/bluecat" - "github.com/go-acme/lego/providers/dns/cloudflare" - "github.com/go-acme/lego/providers/dns/cloudns" - "github.com/go-acme/lego/providers/dns/cloudxns" - "github.com/go-acme/lego/providers/dns/conoha" - "github.com/go-acme/lego/providers/dns/designate" - "github.com/go-acme/lego/providers/dns/digitalocean" - "github.com/go-acme/lego/providers/dns/dnsimple" - "github.com/go-acme/lego/providers/dns/dnsmadeeasy" - "github.com/go-acme/lego/providers/dns/dnspod" - "github.com/go-acme/lego/providers/dns/dode" - "github.com/go-acme/lego/providers/dns/dreamhost" - "github.com/go-acme/lego/providers/dns/duckdns" - "github.com/go-acme/lego/providers/dns/dyn" - "github.com/go-acme/lego/providers/dns/easydns" - "github.com/go-acme/lego/providers/dns/exec" - "github.com/go-acme/lego/providers/dns/exoscale" - "github.com/go-acme/lego/providers/dns/fastdns" - "github.com/go-acme/lego/providers/dns/gandi" - "github.com/go-acme/lego/providers/dns/gandiv5" - "github.com/go-acme/lego/providers/dns/gcloud" - "github.com/go-acme/lego/providers/dns/glesys" - "github.com/go-acme/lego/providers/dns/godaddy" - "github.com/go-acme/lego/providers/dns/hostingde" - "github.com/go-acme/lego/providers/dns/httpreq" - "github.com/go-acme/lego/providers/dns/iij" - "github.com/go-acme/lego/providers/dns/inwx" - "github.com/go-acme/lego/providers/dns/joker" - "github.com/go-acme/lego/providers/dns/lightsail" - "github.com/go-acme/lego/providers/dns/linode" - "github.com/go-acme/lego/providers/dns/linodev4" - "github.com/go-acme/lego/providers/dns/mydnsjp" - "github.com/go-acme/lego/providers/dns/namecheap" - "github.com/go-acme/lego/providers/dns/namedotcom" - "github.com/go-acme/lego/providers/dns/netcup" - "github.com/go-acme/lego/providers/dns/nifcloud" - "github.com/go-acme/lego/providers/dns/ns1" - "github.com/go-acme/lego/providers/dns/oraclecloud" - "github.com/go-acme/lego/providers/dns/otc" - "github.com/go-acme/lego/providers/dns/ovh" - "github.com/go-acme/lego/providers/dns/pdns" - "github.com/go-acme/lego/providers/dns/rackspace" - "github.com/go-acme/lego/providers/dns/rfc2136" - "github.com/go-acme/lego/providers/dns/route53" - "github.com/go-acme/lego/providers/dns/sakuracloud" - "github.com/go-acme/lego/providers/dns/selectel" - "github.com/go-acme/lego/providers/dns/stackpath" - "github.com/go-acme/lego/providers/dns/transip" - "github.com/go-acme/lego/providers/dns/vegadns" - "github.com/go-acme/lego/providers/dns/vscale" - "github.com/go-acme/lego/providers/dns/vultr" - "github.com/go-acme/lego/providers/dns/zoneee" -) - -// NewDNSChallengeProviderByName Factory for DNS providers -func NewDNSChallengeProviderByName(name string) (challenge.Provider, error) { - switch name { - case "acme-dns": - return acmedns.NewDNSProvider() - case "alidns": - return alidns.NewDNSProvider() - case "azure": - return azure.NewDNSProvider() - case "auroradns": - return auroradns.NewDNSProvider() - case "bindman": - return bindman.NewDNSProvider() - case "bluecat": - return bluecat.NewDNSProvider() - case "cloudflare": - return cloudflare.NewDNSProvider() - case "cloudns": - return cloudns.NewDNSProvider() - case "cloudxns": - return cloudxns.NewDNSProvider() - case "conoha": - return conoha.NewDNSProvider() - case "designate": - return designate.NewDNSProvider() - case "digitalocean": - return digitalocean.NewDNSProvider() - case "dnsimple": - return dnsimple.NewDNSProvider() - case "dnsmadeeasy": - return dnsmadeeasy.NewDNSProvider() - case "dnspod": - return dnspod.NewDNSProvider() - case "dode": - return dode.NewDNSProvider() - case "dreamhost": - return dreamhost.NewDNSProvider() - case "duckdns": - return duckdns.NewDNSProvider() - case "dyn": - return dyn.NewDNSProvider() - case "fastdns": - return fastdns.NewDNSProvider() - case "easydns": - return easydns.NewDNSProvider() - case "exec": - return exec.NewDNSProvider() - case "exoscale": - return exoscale.NewDNSProvider() - case "gandi": - return gandi.NewDNSProvider() - case "gandiv5": - return gandiv5.NewDNSProvider() - case "glesys": - return glesys.NewDNSProvider() - case "gcloud": - return gcloud.NewDNSProvider() - case "godaddy": - return godaddy.NewDNSProvider() - case "hostingde": - return hostingde.NewDNSProvider() - case "httpreq": - return httpreq.NewDNSProvider() - case "iij": - return iij.NewDNSProvider() - case "inwx": - return inwx.NewDNSProvider() - case "joker": - return joker.NewDNSProvider() - case "lightsail": - return lightsail.NewDNSProvider() - case "linode": - return linode.NewDNSProvider() - case "linodev4": - return linodev4.NewDNSProvider() - case "manual": - return dns01.NewDNSProviderManual() - case "mydnsjp": - return mydnsjp.NewDNSProvider() - case "namecheap": - return namecheap.NewDNSProvider() - case "namedotcom": - return namedotcom.NewDNSProvider() - case "netcup": - return netcup.NewDNSProvider() - case "nifcloud": - return nifcloud.NewDNSProvider() - case "ns1": - return ns1.NewDNSProvider() - case "oraclecloud": - return oraclecloud.NewDNSProvider() - case "otc": - return otc.NewDNSProvider() - case "ovh": - return ovh.NewDNSProvider() - case "pdns": - return pdns.NewDNSProvider() - case "rackspace": - return rackspace.NewDNSProvider() - case "route53": - return route53.NewDNSProvider() - case "rfc2136": - return rfc2136.NewDNSProvider() - case "sakuracloud": - return sakuracloud.NewDNSProvider() - case "stackpath": - return stackpath.NewDNSProvider() - case "selectel": - return selectel.NewDNSProvider() - case "transip": - return transip.NewDNSProvider() - case "vegadns": - return vegadns.NewDNSProvider() - case "vultr": - return vultr.NewDNSProvider() - case "vscale": - return vscale.NewDNSProvider() - case "zoneee": - return zoneee.NewDNSProvider() - default: - return nil, fmt.Errorf("unrecognised DNS provider: %s", name) - } -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go b/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go deleted file mode 100644 index ac26e30a7..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsimple/dnsimple.go +++ /dev/null @@ -1,211 +0,0 @@ -// Package dnsimple implements a DNS provider for solving the DNS-01 challenge using dnsimple DNS. -package dnsimple - -import ( - "context" - "errors" - "fmt" - "strconv" - "strings" - "time" - - "github.com/dnsimple/dnsimple-go/dnsimple" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "golang.org/x/oauth2" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccessToken string - BaseURL string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSIMPLE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DNSIMPLE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSIMPLE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dnsimple.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for dnsimple. -// Credentials must be passed in the environment variables: DNSIMPLE_OAUTH_TOKEN. -// -// See: https://developer.dnsimple.com/v2/#authentication -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - config.AccessToken = env.GetOrFile("DNSIMPLE_OAUTH_TOKEN") - config.BaseURL = env.GetOrFile("DNSIMPLE_BASE_URL") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DNSimple. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnsimple: the configuration of the DNS provider is nil") - } - - if config.AccessToken == "" { - return nil, fmt.Errorf("dnsimple: OAuth token is missing") - } - - ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: config.AccessToken}) - client := dnsimple.NewClient(oauth2.NewClient(context.Background(), ts)) - - if config.BaseURL != "" { - client.BaseURL = config.BaseURL - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneName, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - accountID, err := d.getAccountID() - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - recordAttributes := newTxtRecord(zoneName, fqdn, value, d.config.TTL) - _, err = d.client.Zones.CreateRecord(accountID, zoneName, recordAttributes) - if err != nil { - return fmt.Errorf("dnsimple: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - accountID, err := d.getAccountID() - if err != nil { - return fmt.Errorf("dnsimple: %v", err) - } - - var lastErr error - for _, rec := range records { - _, err := d.client.Zones.DeleteRecord(accountID, rec.ZoneID, rec.ID) - if err != nil { - lastErr = fmt.Errorf("dnsimple: %v", err) - } - } - - return lastErr -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", err - } - - accountID, err := d.getAccountID() - if err != nil { - return "", err - } - - zoneName := dns01.UnFqdn(authZone) - - zones, err := d.client.Zones.ListZones(accountID, &dnsimple.ZoneListOptions{NameLike: zoneName}) - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - var hostedZone dnsimple.Zone - for _, zone := range zones.Data { - if zone.Name == zoneName { - hostedZone = zone - } - } - - if hostedZone.ID == 0 { - return "", fmt.Errorf("zone %s not found in DNSimple for domain %s", authZone, domain) - } - - return hostedZone.Name, nil -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnsimple.ZoneRecord, error) { - zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - accountID, err := d.getAccountID() - if err != nil { - return nil, err - } - - recordName := extractRecordName(fqdn, zoneName) - - result, err := d.client.Zones.ListRecords(accountID, zoneName, &dnsimple.ZoneRecordListOptions{Name: recordName, Type: "TXT", ListOptions: dnsimple.ListOptions{}}) - if err != nil { - return nil, fmt.Errorf("API call has failed: %v", err) - } - - return result.Data, nil -} - -func newTxtRecord(zoneName, fqdn, value string, ttl int) dnsimple.ZoneRecord { - name := extractRecordName(fqdn, zoneName) - - return dnsimple.ZoneRecord{ - Type: "TXT", - Name: name, - Content: value, - TTL: ttl, - } -} - -func extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} - -func (d *DNSProvider) getAccountID() (string, error) { - whoamiResponse, err := d.client.Identity.Whoami() - if err != nil { - return "", err - } - - if whoamiResponse.Data.Account == nil { - return "", fmt.Errorf("user tokens are not supported, please use an account token") - } - - return strconv.FormatInt(whoamiResponse.Data.Account.ID, 10), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go deleted file mode 100644 index 0d38ef173..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/dnsmadeeasy.go +++ /dev/null @@ -1,163 +0,0 @@ -// Package dnsmadeeasy implements a DNS provider for solving the DNS-01 challenge using DNS Made Easy. -package dnsmadeeasy - -import ( - "crypto/tls" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - APISecret string - Sandbox bool - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSMADEEASY_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DNSMADEEASY_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSMADEEASY_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DNSMADEEASY_HTTP_TIMEOUT", 10*time.Second), - Transport: &http.Transport{ - TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// DNSMadeEasy's DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for DNSMadeEasy DNS. -// Credentials must be passed in the environment variables: -// DNSMADEEASY_API_KEY and DNSMADEEASY_API_SECRET. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DNSMADEEASY_API_KEY", "DNSMADEEASY_API_SECRET") - if err != nil { - return nil, fmt.Errorf("dnsmadeeasy: %v", err) - } - - config := NewDefaultConfig() - config.Sandbox = env.GetOrDefaultBool("DNSMADEEASY_SANDBOX", false) - config.APIKey = values["DNSMADEEASY_API_KEY"] - config.APISecret = values["DNSMADEEASY_API_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DNS Made Easy. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnsmadeeasy: the configuration of the DNS provider is nil") - } - - var baseURL string - if config.Sandbox { - baseURL = "https://api.sandbox.dnsmadeeasy.com/V2.0" - } else { - if len(config.BaseURL) > 0 { - baseURL = config.BaseURL - } else { - baseURL = "https://api.dnsmadeeasy.com/V2.0" - } - } - - client, err := internal.NewClient(config.APIKey, config.APISecret) - if err != nil { - return nil, fmt.Errorf("dnsmadeeasy: %v", err) - } - - client.HTTPClient = config.HTTPClient - client.BaseURL = baseURL - - return &DNSProvider{ - client: client, - config: config, - }, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err) - } - - // fetch the domain details - domain, err := d.client.GetDomain(authZone) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err) - } - - // create the TXT record - name := strings.Replace(fqdn, "."+authZone, "", 1) - record := &internal.Record{Type: "TXT", Name: name, Value: value, TTL: d.config.TTL} - - err = d.client.CreateRecord(domain, record) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to create record for %s: %v", name, err) - } - return nil -} - -// CleanUp removes the TXT records matching the specified parameters -func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domainName, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to find zone for %s: %v", fqdn, err) - } - - // fetch the domain details - domain, err := d.client.GetDomain(authZone) - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get domain for zone %s: %v", authZone, err) - } - - // find matching records - name := strings.Replace(fqdn, "."+authZone, "", 1) - records, err := d.client.GetRecords(domain, name, "TXT") - if err != nil { - return fmt.Errorf("dnsmadeeasy: unable to get records for domain %s: %v", domain.Name, err) - } - - // delete records - var lastError error - for _, record := range *records { - err = d.client.DeleteRecord(record) - if err != nil { - lastError = fmt.Errorf("dnsmadeeasy: unable to delete record [id=%d, name=%s]: %v", record.ID, record.Name, err) - } - } - - return lastError -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go deleted file mode 100644 index 748d385d8..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnsmadeeasy/internal/client.go +++ /dev/null @@ -1,173 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/hmac" - "crypto/sha1" - "encoding/hex" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "time" -) - -// Domain holds the DNSMadeEasy API representation of a Domain -type Domain struct { - ID int `json:"id"` - Name string `json:"name"` -} - -// Record holds the DNSMadeEasy API representation of a Domain Record -type Record struct { - ID int `json:"id"` - Type string `json:"type"` - Name string `json:"name"` - Value string `json:"value"` - TTL int `json:"ttl"` - SourceID int `json:"sourceId"` -} - -type recordsResponse struct { - Records *[]Record `json:"data"` -} - -// Client DNSMadeEasy client -type Client struct { - apiKey string - apiSecret string - BaseURL string - HTTPClient *http.Client -} - -// NewClient creates a DNSMadeEasy client -func NewClient(apiKey string, apiSecret string) (*Client, error) { - if apiKey == "" { - return nil, fmt.Errorf("credentials missing: API key") - } - - if apiSecret == "" { - return nil, fmt.Errorf("credentials missing: API secret") - } - - return &Client{ - apiKey: apiKey, - apiSecret: apiSecret, - HTTPClient: &http.Client{}, - }, nil -} - -// GetDomain gets a domain -func (c *Client) GetDomain(authZone string) (*Domain, error) { - domainName := authZone[0 : len(authZone)-1] - resource := fmt.Sprintf("%s%s", "/dns/managed/name?domainname=", domainName) - - resp, err := c.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - domain := &Domain{} - err = json.NewDecoder(resp.Body).Decode(&domain) - if err != nil { - return nil, err - } - - return domain, nil -} - -// GetRecords gets all TXT records -func (c *Client) GetRecords(domain *Domain, recordName, recordType string) (*[]Record, error) { - resource := fmt.Sprintf("%s/%d/%s%s%s%s", "/dns/managed", domain.ID, "records?recordName=", recordName, "&type=", recordType) - - resp, err := c.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - records := &recordsResponse{} - err = json.NewDecoder(resp.Body).Decode(&records) - if err != nil { - return nil, err - } - - return records.Records, nil -} - -// CreateRecord creates a TXT records -func (c *Client) CreateRecord(domain *Domain, record *Record) error { - url := fmt.Sprintf("%s/%d/%s", "/dns/managed", domain.ID, "records") - - resp, err := c.sendRequest(http.MethodPost, url, record) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -// DeleteRecord deletes a TXT records -func (c *Client) DeleteRecord(record Record) error { - resource := fmt.Sprintf("%s/%d/%s/%d", "/dns/managed", record.SourceID, "records", record.ID) - - resp, err := c.sendRequest(http.MethodDelete, resource, nil) - if err != nil { - return err - } - defer resp.Body.Close() - - return nil -} - -func (c *Client) sendRequest(method, resource string, payload interface{}) (*http.Response, error) { - url := fmt.Sprintf("%s%s", c.BaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - timestamp := time.Now().UTC().Format(time.RFC1123) - signature, err := computeHMAC(timestamp, c.apiSecret) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("x-dnsme-apiKey", c.apiKey) - req.Header.Set("x-dnsme-requestDate", timestamp) - req.Header.Set("x-dnsme-hmac", signature) - req.Header.Set("accept", "application/json") - req.Header.Set("content-type", "application/json") - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - - if resp.StatusCode > 299 { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - return nil, fmt.Errorf("request failed with HTTP status code %d: %s", resp.StatusCode, string(body)) - } - - return resp, nil -} - -func computeHMAC(message string, secret string) (string, error) { - key := []byte(secret) - h := hmac.New(sha1.New, key) - _, err := h.Write([]byte(message)) - if err != nil { - return "", err - } - return hex.EncodeToString(h.Sum(nil)), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go b/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go deleted file mode 100644 index 506836dc7..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dnspod/dnspod.go +++ /dev/null @@ -1,189 +0,0 @@ -// Package dnspod implements a DNS provider for solving the DNS-01 challenge using dnspod DNS. -package dnspod - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "strings" - "time" - - dnspod "github.com/decker502/dnspod-go" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - LoginToken string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DNSPOD_TTL", 600), - PropagationTimeout: env.GetOrDefaultSecond("DNSPOD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DNSPOD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DNSPOD_HTTP_TIMEOUT", 0), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dnspod.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for dnspod. -// Credentials must be passed in the environment variables: DNSPOD_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DNSPOD_API_KEY") - if err != nil { - return nil, fmt.Errorf("dnspod: %v", err) - } - - config := NewDefaultConfig() - config.LoginToken = values["DNSPOD_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for dnspod. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dnspod: the configuration of the DNS provider is nil") - } - - if config.LoginToken == "" { - return nil, fmt.Errorf("dnspod: credentials missing") - } - - params := dnspod.CommonParams{LoginToken: config.LoginToken, Format: "json"} - - client := dnspod.NewClient(params) - client.HttpClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zoneID, zoneName, err := d.getHostedZone(domain) - if err != nil { - return err - } - - recordAttributes := d.newTxtRecord(zoneName, fqdn, value, d.config.TTL) - _, _, err = d.client.Domains.CreateRecord(zoneID, *recordAttributes) - if err != nil { - return fmt.Errorf("API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return err - } - - zoneID, _, err := d.getHostedZone(domain) - if err != nil { - return err - } - - for _, rec := range records { - _, err := d.client.Domains.DeleteRecord(zoneID, rec.ID) - if err != nil { - return err - } - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, string, error) { - zones, _, err := d.client.Domains.List() - if err != nil { - return "", "", fmt.Errorf("API call failed: %v", err) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - - var hostedZone dnspod.Domain - for _, zone := range zones { - if zone.Name == dns01.UnFqdn(authZone) { - hostedZone = zone - } - } - - if hostedZone.ID == 0 { - return "", "", fmt.Errorf("zone %s not found in dnspod for domain %s", authZone, domain) - - } - - return fmt.Sprintf("%v", hostedZone.ID), hostedZone.Name, nil -} - -func (d *DNSProvider) newTxtRecord(zone, fqdn, value string, ttl int) *dnspod.Record { - name := d.extractRecordName(fqdn, zone) - - return &dnspod.Record{ - Type: "TXT", - Name: name, - Value: value, - Line: "默认", - TTL: strconv.Itoa(ttl), - } -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) ([]dnspod.Record, error) { - zoneID, zoneName, err := d.getHostedZone(domain) - if err != nil { - return nil, err - } - - var records []dnspod.Record - result, _, err := d.client.Domains.ListRecords(zoneID, "") - if err != nil { - return records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneName) - - for _, record := range result { - if record.Name == recordName { - records = append(records, record) - } - } - - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/client.go b/vendor/github.com/go-acme/lego/providers/dns/dode/client.go deleted file mode 100644 index 193b5160d..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/client.go +++ /dev/null @@ -1,57 +0,0 @@ -package dode - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - - "github.com/go-acme/lego/challenge/dns01" -) - -type apiResponse struct { - Domain string - Success bool -} - -// updateTxtRecord Update the domains TXT record -// To update the TXT record we just need to make one simple get request. -func (d *DNSProvider) updateTxtRecord(fqdn, token, txt string, clear bool) error { - u, _ := url.Parse("https://www.do.de/api/letsencrypt") - - query := u.Query() - query.Set("token", token) - query.Set("domain", dns01.UnFqdn(fqdn)) - - // api call differs per set/delete - if clear { - query.Set("action", "delete") - } else { - query.Set("value", txt) - } - - u.RawQuery = query.Encode() - - response, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer response.Body.Close() - - bodyBytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - var r apiResponse - err = json.Unmarshal(bodyBytes, &r) - if err != nil { - return fmt.Errorf("request to change TXT record for do.de returned the following invalid json (%s); used url [%s]", string(bodyBytes), u) - } - - body := string(bodyBytes) - if !r.Success { - return fmt.Errorf("request to change TXT record for do.de returned the following error result (%s); used url [%s]", body, u) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go b/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go deleted file mode 100644 index 693543a77..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dode/dode.go +++ /dev/null @@ -1,89 +0,0 @@ -// Package dode implements a DNS provider for solving the DNS-01 challenge using do.de. -package dode - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("DODE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DODE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - SequenceInterval: env.GetOrDefaultSecond("DODE_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DODE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DODE_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DODE_TOKEN") - if err != nil { - return nil, fmt.Errorf("do.de: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["DODE_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for do.de. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("do.de: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("do.de: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, txtRecord := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(fqdn, d.config.Token, txtRecord, false) -} - -// CleanUp clears TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(fqdn, d.config.Token, "", true) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go deleted file mode 100644 index 9734d55c0..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/client.go +++ /dev/null @@ -1,73 +0,0 @@ -package dreamhost - -import ( - "encoding/json" - "fmt" - "io/ioutil" - "net/url" - - "github.com/go-acme/lego/log" -) - -const ( - defaultBaseURL = "https://api.dreamhost.com" - - cmdAddRecord = "dns-add_record" - cmdRemoveRecord = "dns-remove_record" -) - -type apiResponse struct { - Data string `json:"data"` - Result string `json:"result"` -} - -func (d *DNSProvider) buildQuery(action, domain, txt string) (*url.URL, error) { - u, err := url.Parse(d.config.BaseURL) - if err != nil { - return nil, err - } - - query := u.Query() - query.Set("key", d.config.APIKey) - query.Set("cmd", action) - query.Set("format", "json") - query.Set("record", domain) - query.Set("type", "TXT") - query.Set("value", txt) - query.Set("comment", url.QueryEscape("Managed By lego")) - u.RawQuery = query.Encode() - - return u, nil -} - -// updateTxtRecord will either add or remove a TXT record. -// action is either cmdAddRecord or cmdRemoveRecord -func (d *DNSProvider) updateTxtRecord(u fmt.Stringer) error { - resp, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode != 200 { - return fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - var response apiResponse - err = json.Unmarshal(raw, &response) - if err != nil { - return fmt.Errorf("unable to decode API server response: %v: %s", err, string(raw)) - } - - if response.Result == "error" { - return fmt.Errorf("add TXT record failed: %s", response.Data) - } - - log.Infof("dreamhost: %s", response.Data) - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go b/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go deleted file mode 100644 index c7816036c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dreamhost/dreamhost.go +++ /dev/null @@ -1,111 +0,0 @@ -// Package dreamhost implements a DNS provider for solving the DNS-01 challenge using DreamHost. -// See https://help.dreamhost.com/hc/en-us/articles/217560167-API_overview -// and https://help.dreamhost.com/hc/en-us/articles/217555707-DNS-API-commands for the API spec. -package dreamhost - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - PropagationTimeout: env.GetOrDefaultSecond("DREAMHOST_PROPAGATION_TIMEOUT", 60*time.Minute), - PollingInterval: env.GetOrDefaultSecond("DREAMHOST_POLLING_INTERVAL", 1*time.Minute), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DREAMHOST_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DREAMHOST_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DREAMHOST_API_KEY") - if err != nil { - return nil, fmt.Errorf("dreamhost: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["DREAMHOST_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DreamHost. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dreamhost: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, errors.New("dreamhost: credentials missing") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - record := dns01.UnFqdn(fqdn) - - u, err := d.buildQuery(cmdAddRecord, record, value) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - - err = d.updateTxtRecord(u) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - return nil -} - -// CleanUp clears DreamHost TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - record := dns01.UnFqdn(fqdn) - - u, err := d.buildQuery(cmdRemoveRecord, record, value) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - - err = d.updateTxtRecord(u) - if err != nil { - return fmt.Errorf("dreamhost: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go b/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go deleted file mode 100644 index 4c0f35f4a..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/client.go +++ /dev/null @@ -1,68 +0,0 @@ -package duckdns - -import ( - "fmt" - "io/ioutil" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/miekg/dns" -) - -// updateTxtRecord Update the domains TXT record -// To update the TXT record we just need to make one simple get request. -// In DuckDNS you only have one TXT record shared with the domain and all sub domains. -func (d *DNSProvider) updateTxtRecord(domain, token, txt string, clear bool) error { - u, _ := url.Parse("https://www.duckdns.org/update") - - mainDomain := getMainDomain(domain) - if len(mainDomain) == 0 { - return fmt.Errorf("unable to find the main domain for: %s", domain) - } - - query := u.Query() - query.Set("domains", mainDomain) - query.Set("token", token) - query.Set("clear", strconv.FormatBool(clear)) - query.Set("txt", txt) - u.RawQuery = query.Encode() - - response, err := d.config.HTTPClient.Get(u.String()) - if err != nil { - return err - } - defer response.Body.Close() - - bodyBytes, err := ioutil.ReadAll(response.Body) - if err != nil { - return err - } - - body := string(bodyBytes) - if body != "OK" { - return fmt.Errorf("request to change TXT record for DuckDNS returned the following result (%s) this does not match expectation (OK) used url [%s]", body, u) - } - return nil -} - -// DuckDNS only lets you write to your subdomain -// so it must be in format subdomain.duckdns.org -// not in format subsubdomain.subdomain.duckdns.org -// so strip off everything that is not top 3 levels -func getMainDomain(domain string) string { - domain = dns01.UnFqdn(domain) - - split := dns.Split(domain) - if strings.HasSuffix(strings.ToLower(domain), "duckdns.org") { - if len(split) < 3 { - return "" - } - - firstSubDomainIndex := split[len(split)-3] - return domain[firstSubDomainIndex:] - } - - return domain[split[len(split)-1]:] -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go b/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go deleted file mode 100644 index 8d2d78330..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/duckdns/duckdns.go +++ /dev/null @@ -1,89 +0,0 @@ -// Package duckdns implements a DNS provider for solving the DNS-01 challenge using DuckDNS. -// See http://www.duckdns.org/spec.jsp for more info on updating TXT records. -package duckdns - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("DUCKDNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DUCKDNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - SequenceInterval: env.GetOrDefaultSecond("DUCKDNS_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DUCKDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider adds and removes the record for the DNS challenge -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider using -// environment variable DUCKDNS_TOKEN for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DUCKDNS_TOKEN") - if err != nil { - return nil, fmt.Errorf("duckdns: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["DUCKDNS_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for DuckDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("duckdns: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("duckdns: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, txtRecord := dns01.GetRecord(domain, keyAuth) - return d.updateTxtRecord(domain, d.config.Token, txtRecord, false) -} - -// CleanUp clears DuckDNS TXT record -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - return d.updateTxtRecord(domain, d.config.Token, "", true) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go b/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go deleted file mode 100644 index f7e6cee84..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/client.go +++ /dev/null @@ -1,146 +0,0 @@ -package dyn - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" -) - -const defaultBaseURL = "https://api.dynect.net/REST" - -type dynResponse struct { - // One of 'success', 'failure', or 'incomplete' - Status string `json:"status"` - - // The structure containing the actual results of the request - Data json.RawMessage `json:"data"` - - // The ID of the job that was created in response to a request. - JobID int `json:"job_id"` - - // A list of zero or more messages - Messages json.RawMessage `json:"msgs"` -} - -type credentials struct { - Customer string `json:"customer_name"` - User string `json:"user_name"` - Pass string `json:"password"` -} - -type session struct { - Token string `json:"token"` - Version string `json:"version"` -} - -type publish struct { - Publish bool `json:"publish"` - Notes string `json:"notes"` -} - -// Starts a new Dyn API Session. Authenticates using customerName, userName, -// password and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - payload := &credentials{Customer: d.config.CustomerName, User: d.config.UserName, Pass: d.config.Password} - dynRes, err := d.sendRequest(http.MethodPost, "Session", payload) - if err != nil { - return err - } - - var s session - err = json.Unmarshal(dynRes.Data, &s) - if err != nil { - return err - } - - d.token = s.Token - - return nil -} - -// Destroys Dyn Session -func (d *DNSProvider) logout() error { - if len(d.token) == 0 { - // nothing to do - return nil - } - - url := fmt.Sprintf("%s/Session", defaultBaseURL) - req, err := http.NewRequest(http.MethodDelete, url, nil) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Auth-Token", d.token) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("API request failed to delete session with HTTP status code %d", resp.StatusCode) - } - - d.token = "" - - return nil -} - -func (d *DNSProvider) publish(zone, notes string) error { - pub := &publish{Publish: true, Notes: notes} - resource := fmt.Sprintf("Zone/%s/", zone) - - _, err := d.sendRequest(http.MethodPut, resource, pub) - return err -} - -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) (*dynResponse, error) { - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("Auth-Token", d.token) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 500 { - return nil, fmt.Errorf("API request failed with HTTP status code %d", resp.StatusCode) - } - - var dynRes dynResponse - err = json.NewDecoder(resp.Body).Decode(&dynRes) - if err != nil { - return nil, err - } - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("API request failed with HTTP status code %d: %s", resp.StatusCode, dynRes.Messages) - } else if resp.StatusCode == 307 { - // TODO add support for HTTP 307 response and long running jobs - return nil, fmt.Errorf("API request returned HTTP 307. This is currently unsupported") - } - - if dynRes.Status == "failure" { - // TODO add better error handling - return nil, fmt.Errorf("API request failed: %s", dynRes.Messages) - } - - return &dynRes, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go b/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go deleted file mode 100644 index 37cc7ec76..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/dyn/dyn.go +++ /dev/null @@ -1,157 +0,0 @@ -// Package dyn implements a DNS provider for solving the DNS-01 challenge using Dyn Managed DNS. -package dyn - -import ( - "errors" - "fmt" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - CustomerName string - UserName string - Password string - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("DYN_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("DYN_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("DYN_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("DYN_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// Dyn's Managed DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for Dyn DNS. -// Credentials must be passed in the environment variables: -// DYN_CUSTOMER_NAME, DYN_USER_NAME and DYN_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("DYN_CUSTOMER_NAME", "DYN_USER_NAME", "DYN_PASSWORD") - if err != nil { - return nil, fmt.Errorf("dyn: %v", err) - } - - config := NewDefaultConfig() - config.CustomerName = values["DYN_CUSTOMER_NAME"] - config.UserName = values["DYN_USER_NAME"] - config.Password = values["DYN_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Dyn DNS -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("dyn: the configuration of the DNS provider is nil") - } - - if config.CustomerName == "" || config.UserName == "" || config.Password == "" { - return nil, fmt.Errorf("dyn: credentials missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - data := map[string]interface{}{ - "rdata": map[string]string{ - "txtdata": value, - }, - "ttl": strconv.Itoa(d.config.TTL), - } - - resource := fmt.Sprintf("TXTRecord/%s/%s/", authZone, fqdn) - _, err = d.sendRequest(http.MethodPost, resource, data) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.publish(authZone, "Added TXT record for ACME dns-01 challenge using lego client") - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - return d.logout() -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - resource := fmt.Sprintf("TXTRecord/%s/%s/", authZone, fqdn) - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - req, err := http.NewRequest(http.MethodDelete, url, nil) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Auth-Token", d.token) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return fmt.Errorf("dyn: API request failed to delete TXT record HTTP status code %d", resp.StatusCode) - } - - err = d.publish(authZone, "Removed TXT record for ACME dns-01 challenge using lego client") - if err != nil { - return fmt.Errorf("dyn: %v", err) - } - - return d.logout() -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go b/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go deleted file mode 100644 index 3d2c565b2..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/client.go +++ /dev/null @@ -1,97 +0,0 @@ -package easydns - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path" -) - -const defaultEndpoint = "https://rest.easydns.net" - -type zoneRecord struct { - ID string `json:"id,omitempty"` - Domain string `json:"domain"` - Host string `json:"host"` - TTL string `json:"ttl"` - Prio string `json:"prio"` - Type string `json:"type"` - Rdata string `json:"rdata"` - LastMod string `json:"last_mod,omitempty"` - Revoked int `json:"revoked,omitempty"` - NewHost string `json:"new_host,omitempty"` -} - -type addRecordResponse struct { - Msg string `json:"msg"` - Tm int `json:"tm"` - Data zoneRecord `json:"data"` - Status int `json:"status"` -} - -func (d *DNSProvider) addRecord(domain string, record interface{}) (string, error) { - pathAdd := path.Join("/zones/records/add", domain, "TXT") - - response := &addRecordResponse{} - err := d.doRequest(http.MethodPut, pathAdd, record, response) - if err != nil { - return "", err - } - - recordID := response.Data.ID - - return recordID, nil -} - -func (d *DNSProvider) deleteRecord(domain, recordID string) error { - pathDelete := path.Join("/zones/records", domain, recordID) - - return d.doRequest(http.MethodDelete, pathDelete, nil, nil) -} - -func (d *DNSProvider) doRequest(method, path string, requestMsg, responseMsg interface{}) error { - reqBody := &bytes.Buffer{} - if requestMsg != nil { - err := json.NewEncoder(reqBody).Encode(requestMsg) - if err != nil { - return err - } - } - - endpoint, err := d.config.Endpoint.Parse(path + "?format=json") - if err != nil { - return err - } - - request, err := http.NewRequest(method, endpoint.String(), reqBody) - if err != nil { - return err - } - - request.Header.Set("Content-Type", "application/json") - request.Header.Set("Accept", "application/json") - request.SetBasicAuth(d.config.Token, d.config.Key) - - response, err := d.config.HTTPClient.Do(request) - if err != nil { - return err - } - defer response.Body.Close() - - if response.StatusCode >= http.StatusBadRequest { - body, err := ioutil.ReadAll(response.Body) - if err != nil { - return fmt.Errorf("%d: failed to read response body: %v", response.StatusCode, err) - } - - return fmt.Errorf("%d: request failed: %v", response.StatusCode, string(body)) - } - - if responseMsg != nil { - return json.NewDecoder(response.Body).Decode(responseMsg) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go b/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go deleted file mode 100644 index 2ef5c2853..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/easydns/easydns.go +++ /dev/null @@ -1,165 +0,0 @@ -// Package easydns implements a DNS provider for solving the DNS-01 challenge using EasyDNS API. -package easydns - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "strconv" - "strings" - "sync" - "time" - - "github.com/miekg/dns" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Token string - Key string - TTL int - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("EASYDNS_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - SequenceInterval: env.GetOrDefaultSecond("EASYDNS_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EASYDNS_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("EASYDNS_TTL", dns01.DefaultTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("EASYDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config - recordIDs map[string]string - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - config := NewDefaultConfig() - - endpoint, err := url.Parse(env.GetOrDefaultString("EASYDNS_ENDPOINT", defaultEndpoint)) - if err != nil { - return nil, fmt.Errorf("easydns: %v", err) - } - config.Endpoint = endpoint - - values, err := env.Get("EASYDNS_TOKEN", "EASYDNS_KEY") - if err != nil { - return nil, fmt.Errorf("easydns: %v", err) - } - - config.Token = values["EASYDNS_TOKEN"] - config.Key = values["EASYDNS_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("easydns: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("easydns: the API token is missing") - } - - if config.Key == "" { - return nil, errors.New("easydns: the API key is missing") - } - - return &DNSProvider{config: config, recordIDs: map[string]string{}}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - apiHost, apiDomain := splitFqdn(fqdn) - record := &zoneRecord{ - Domain: apiDomain, - Host: apiHost, - Type: "TXT", - Rdata: value, - TTL: strconv.Itoa(d.config.TTL), - Prio: "0", - } - - recordID, err := d.addRecord(apiDomain, record) - if err != nil { - return fmt.Errorf("easydns: error adding zone record: %v", err) - } - - key := getMapKey(fqdn, value) - - d.recordIDsMu.Lock() - d.recordIDs[key] = recordID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, challenge := dns01.GetRecord(domain, keyAuth) - - key := getMapKey(fqdn, challenge) - recordID, exists := d.recordIDs[key] - if !exists { - return nil - } - - _, apiDomain := splitFqdn(fqdn) - err := d.deleteRecord(apiDomain, recordID) - - d.recordIDsMu.Lock() - defer delete(d.recordIDs, key) - d.recordIDsMu.Unlock() - - if err != nil { - return fmt.Errorf("easydns: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -func splitFqdn(fqdn string) (host, domain string) { - parts := dns.SplitDomainName(fqdn) - length := len(parts) - - host = strings.Join(parts[0:length-2], ".") - domain = strings.Join(parts[length-2:length], ".") - return -} - -func getMapKey(fqdn, value string) string { - return fqdn + "|" + value -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go b/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go deleted file mode 100644 index 903bcca78..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exec/exec.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package exec implements a DNS provider which runs a program for adding/removing the DNS record. -package exec - -import ( - "errors" - "fmt" - "os" - "os/exec" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config Provider configuration. -type Config struct { - Program string - Mode string - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("EXEC_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EXEC_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider adds and removes the record for the DNS challenge by calling a -// program with command-line parameters. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a new DNS provider which runs the program in the -// environment variable EXEC_PATH for adding and removing the DNS record. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("EXEC_PATH") - if err != nil { - return nil, fmt.Errorf("exec: %v", err) - } - - config := NewDefaultConfig() - config.Program = values["EXEC_PATH"] - config.Mode = os.Getenv("EXEC_MODE") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig returns a new DNS provider which runs the given configuration -// for adding and removing the DNS record. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("the configuration is nil") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - var args []string - if d.config.Mode == "RAW" { - args = []string{"present", "--", domain, token, keyAuth} - } else { - fqdn, value := dns01.GetRecord(domain, keyAuth) - args = []string{"present", fqdn, value} - } - - cmd := exec.Command(d.config.Program, args...) - - output, err := cmd.CombinedOutput() - if len(output) > 0 { - log.Println(string(output)) - } - - return err -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - var args []string - if d.config.Mode == "RAW" { - args = []string{"cleanup", "--", domain, token, keyAuth} - } else { - fqdn, value := dns01.GetRecord(domain, keyAuth) - args = []string{"cleanup", fqdn, value} - } - - cmd := exec.Command(d.config.Program, args...) - - output, err := cmd.CombinedOutput() - if len(output) > 0 { - log.Println(string(output)) - } - - return err -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.PropagationTimeout -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go b/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go deleted file mode 100644 index 02ec21470..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/exoscale/exoscale.go +++ /dev/null @@ -1,184 +0,0 @@ -// Package exoscale implements a DNS provider for solving the DNS-01 challenge using exoscale DNS. -package exoscale - -import ( - "context" - "errors" - "fmt" - "net/http" - "time" - - "github.com/exoscale/egoscale" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultBaseURL = "https://api.exoscale.com/dns" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - APISecret string - Endpoint string - HTTPClient *http.Client - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("EXOSCALE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("EXOSCALE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("EXOSCALE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("EXOSCALE_HTTP_TIMEOUT", 0), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *egoscale.Client -} - -// NewDNSProvider Credentials must be passed in the environment variables: -// EXOSCALE_API_KEY, EXOSCALE_API_SECRET, EXOSCALE_ENDPOINT. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("EXOSCALE_API_KEY", "EXOSCALE_API_SECRET") - if err != nil { - return nil, fmt.Errorf("exoscale: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["EXOSCALE_API_KEY"] - config.APISecret = values["EXOSCALE_API_SECRET"] - config.Endpoint = env.GetOrFile("EXOSCALE_ENDPOINT") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Exoscale. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.APISecret == "" { - return nil, fmt.Errorf("exoscale: credentials missing") - } - - if config.Endpoint == "" { - config.Endpoint = defaultBaseURL - } - - client := egoscale.NewClient(config.Endpoint, config.APIKey, config.APISecret) - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, recordName, err := d.FindZoneAndRecordName(fqdn, domain) - if err != nil { - return err - } - - recordID, err := d.FindExistingRecordID(zone, recordName) - if err != nil { - return err - } - - if recordID == 0 { - record := egoscale.DNSRecord{ - Name: recordName, - TTL: d.config.TTL, - Content: value, - RecordType: "TXT", - } - - _, err := d.client.CreateRecord(ctx, zone, record) - if err != nil { - return errors.New("Error while creating DNS record: " + err.Error()) - } - } else { - record := egoscale.UpdateDNSRecord{ - ID: recordID, - Name: recordName, - TTL: d.config.TTL, - Content: value, - RecordType: "TXT", - } - - _, err := d.client.UpdateRecord(ctx, zone, record) - if err != nil { - return errors.New("Error while updating DNS record: " + err.Error()) - } - } - - return nil -} - -// CleanUp removes the record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - ctx := context.Background() - fqdn, _ := dns01.GetRecord(domain, keyAuth) - zone, recordName, err := d.FindZoneAndRecordName(fqdn, domain) - if err != nil { - return err - } - - recordID, err := d.FindExistingRecordID(zone, recordName) - if err != nil { - return err - } - - if recordID != 0 { - err = d.client.DeleteRecord(ctx, zone, recordID) - if err != nil { - return errors.New("Error while deleting DNS record: " + err.Error()) - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// FindExistingRecordID Query Exoscale to find an existing record for this name. -// Returns nil if no record could be found -func (d *DNSProvider) FindExistingRecordID(zone, recordName string) (int64, error) { - ctx := context.Background() - records, err := d.client.GetRecords(ctx, zone) - if err != nil { - return -1, errors.New("Error while retrievening DNS records: " + err.Error()) - } - for _, record := range records { - if record.Name == recordName { - return record.ID, nil - } - } - return 0, nil -} - -// FindZoneAndRecordName Extract DNS zone and DNS entry name -func (d *DNSProvider) FindZoneAndRecordName(fqdn, domain string) (string, string, error) { - zone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - zone = dns01.UnFqdn(zone) - name := dns01.UnFqdn(fqdn) - name = name[:len(name)-len("."+zone)] - - return zone, name, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go b/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go deleted file mode 100644 index 214e4a944..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/fastdns/fastdns.go +++ /dev/null @@ -1,158 +0,0 @@ -// Package fastdns implements a DNS provider for solving the DNS-01 challenge using FastDNS. -package fastdns - -import ( - "errors" - "fmt" - "reflect" - "time" - - configdns "github.com/akamai/AkamaiOPEN-edgegrid-golang/configdns-v1" - "github.com/akamai/AkamaiOPEN-edgegrid-golang/edgegrid" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - edgegrid.Config - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("AKAMAI_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("AKAMAI_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("AKAMAI_TTL", dns01.DefaultTTL), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider uses the supplied environment variables to return a DNSProvider instance: -// AKAMAI_HOST, AKAMAI_CLIENT_TOKEN, AKAMAI_CLIENT_SECRET, AKAMAI_ACCESS_TOKEN -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("AKAMAI_HOST", "AKAMAI_CLIENT_TOKEN", "AKAMAI_CLIENT_SECRET", "AKAMAI_ACCESS_TOKEN") - if err != nil { - return nil, fmt.Errorf("fastdns: %v", err) - } - - config := NewDefaultConfig() - config.Config = edgegrid.Config{ - Host: values["AKAMAI_HOST"], - ClientToken: values["AKAMAI_CLIENT_TOKEN"], - ClientSecret: values["AKAMAI_CLIENT_SECRET"], - AccessToken: values["AKAMAI_ACCESS_TOKEN"], - MaxBody: 131072, - } - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for FastDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("fastdns: the configuration of the DNS provider is nil") - } - - if config.ClientToken == "" || config.ClientSecret == "" || config.AccessToken == "" || config.Host == "" { - return nil, fmt.Errorf("fastdns: credentials are missing") - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record to fullfil the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zoneName, recordName, err := d.findZoneAndRecordName(fqdn, domain) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - configdns.Init(d.config.Config) - - zone, err := configdns.GetZone(zoneName) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - record := configdns.NewTxtRecord() - _ = record.SetField("name", recordName) - _ = record.SetField("ttl", d.config.TTL) - _ = record.SetField("target", value) - _ = record.SetField("active", true) - - for _, r := range zone.Zone.Txt { - if r != nil && reflect.DeepEqual(r.ToMap(), record.ToMap()) { - return nil - } - } - - return d.createRecord(zone, record) -} - -// CleanUp removes the record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - zoneName, recordName, err := d.findZoneAndRecordName(fqdn, domain) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - configdns.Init(d.config.Config) - - zone, err := configdns.GetZone(zoneName) - if err != nil { - return fmt.Errorf("fastdns: %v", err) - } - - var removed bool - for _, r := range zone.Zone.Txt { - if r != nil && r.Name == recordName { - if zone.RemoveRecord(r) != nil { - return fmt.Errorf("fastdns: %v", err) - } - removed = true - } - } - - if removed { - return zone.Save() - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) findZoneAndRecordName(fqdn, domain string) (string, string, error) { - zone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", "", err - } - zone = dns01.UnFqdn(zone) - name := dns01.UnFqdn(fqdn) - name = name[:len(name)-len("."+zone)] - - return zone, name, nil -} - -func (d *DNSProvider) createRecord(zone *configdns.Zone, record *configdns.TxtRecord) error { - err := zone.AddRecord(record) - if err != nil { - return err - } - - return zone.Save() -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go deleted file mode 100644 index 901a78947..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/client.go +++ /dev/null @@ -1,316 +0,0 @@ -package gandi - -import ( - "bytes" - "encoding/xml" - "fmt" - "io" - "io/ioutil" -) - -// types for XML-RPC method calls and parameters - -type param interface { - param() -} - -type paramString struct { - XMLName xml.Name `xml:"param"` - Value string `xml:"value>string"` -} - -type paramInt struct { - XMLName xml.Name `xml:"param"` - Value int `xml:"value>int"` -} - -type structMember interface { - structMember() -} -type structMemberString struct { - Name string `xml:"name"` - Value string `xml:"value>string"` -} -type structMemberInt struct { - Name string `xml:"name"` - Value int `xml:"value>int"` -} -type paramStruct struct { - XMLName xml.Name `xml:"param"` - StructMembers []structMember `xml:"value>struct>member"` -} - -func (p paramString) param() {} -func (p paramInt) param() {} -func (m structMemberString) structMember() {} -func (m structMemberInt) structMember() {} -func (p paramStruct) param() {} - -type methodCall struct { - XMLName xml.Name `xml:"methodCall"` - MethodName string `xml:"methodName"` - Params []param `xml:"params"` -} - -// types for XML-RPC responses - -type response interface { - faultCode() int - faultString() string -} - -type responseFault struct { - FaultCode int `xml:"fault>value>struct>member>value>int"` - FaultString string `xml:"fault>value>struct>member>value>string"` -} - -func (r responseFault) faultCode() int { return r.FaultCode } -func (r responseFault) faultString() string { return r.FaultString } - -type responseStruct struct { - responseFault - StructMembers []struct { - Name string `xml:"name"` - ValueInt int `xml:"value>int"` - } `xml:"params>param>value>struct>member"` -} - -type responseInt struct { - responseFault - Value int `xml:"params>param>value>int"` -} - -type responseBool struct { - responseFault - Value bool `xml:"params>param>value>boolean"` -} - -type rpcError struct { - faultCode int - faultString string -} - -func (e rpcError) Error() string { - return fmt.Sprintf("Gandi DNS: RPC Error: (%d) %s", e.faultCode, e.faultString) -} - -// rpcCall makes an XML-RPC call to Gandi's RPC endpoint by -// marshaling the data given in the call argument to XML and sending -// that via HTTP Post to Gandi. -// The response is then unmarshalled into the resp argument. -func (d *DNSProvider) rpcCall(call *methodCall, resp response) error { - // marshal - b, err := xml.MarshalIndent(call, "", " ") - if err != nil { - return fmt.Errorf("marshal error: %v", err) - } - - // post - b = append([]byte(``+"\n"), b...) - respBody, err := d.httpPost(d.config.BaseURL, "text/xml", bytes.NewReader(b)) - if err != nil { - return err - } - - // unmarshal - err = xml.Unmarshal(respBody, resp) - if err != nil { - return fmt.Errorf("unmarshal error: %v", err) - } - if resp.faultCode() != 0 { - return rpcError{ - faultCode: resp.faultCode(), faultString: resp.faultString()} - } - return nil -} - -// functions to perform API actions - -func (d *DNSProvider) getZoneID(domain string) (int, error) { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.info", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramString{Value: domain}, - }, - }, resp) - if err != nil { - return 0, err - } - - var zoneID int - for _, member := range resp.StructMembers { - if member.Name == "zone_id" { - zoneID = member.ValueInt - } - } - - if zoneID == 0 { - return 0, fmt.Errorf("could not determine zone_id for %s", domain) - } - return zoneID, nil -} - -func (d *DNSProvider) cloneZone(zoneID int, name string) (int, error) { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.clone", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: 0}, - paramStruct{ - StructMembers: []structMember{ - structMemberString{ - Name: "name", - Value: name, - }}, - }, - }, - }, resp) - if err != nil { - return 0, err - } - - var newZoneID int - for _, member := range resp.StructMembers { - if member.Name == "id" { - newZoneID = member.ValueInt - } - } - - if newZoneID == 0 { - return 0, fmt.Errorf("could not determine cloned zone_id") - } - return newZoneID, nil -} - -func (d *DNSProvider) newZoneVersion(zoneID int) (int, error) { - resp := &responseInt{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.version.new", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return 0, err - } - - if resp.Value == 0 { - return 0, fmt.Errorf("could not create new zone version") - } - return resp.Value, nil -} - -func (d *DNSProvider) addTXTRecord(zoneID int, version int, name string, value string, ttl int) error { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.record.add", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: version}, - paramStruct{ - StructMembers: []structMember{ - structMemberString{ - Name: "type", - Value: "TXT", - }, structMemberString{ - Name: "name", - Value: name, - }, structMemberString{ - Name: "value", - Value: value, - }, structMemberInt{ - Name: "ttl", - Value: ttl, - }}, - }, - }, - }, resp) - return err -} - -func (d *DNSProvider) setZoneVersion(zoneID int, version int) error { - resp := &responseBool{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.version.set", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - paramInt{Value: version}, - }, - }, resp) - if err != nil { - return err - } - - if !resp.Value { - return fmt.Errorf("could not set zone version") - } - return nil -} - -func (d *DNSProvider) setZone(domain string, zoneID int) error { - resp := &responseStruct{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.set", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramString{Value: domain}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return err - } - - var respZoneID int - for _, member := range resp.StructMembers { - if member.Name == "zone_id" { - respZoneID = member.ValueInt - } - } - - if respZoneID != zoneID { - return fmt.Errorf("could not set new zone_id for %s", domain) - } - return nil -} - -func (d *DNSProvider) deleteZone(zoneID int) error { - resp := &responseBool{} - err := d.rpcCall(&methodCall{ - MethodName: "domain.zone.delete", - Params: []param{ - paramString{Value: d.config.APIKey}, - paramInt{Value: zoneID}, - }, - }, resp) - if err != nil { - return err - } - - if !resp.Value { - return fmt.Errorf("could not delete zone_id") - } - return nil -} - -func (d *DNSProvider) httpPost(url string, bodyType string, body io.Reader) ([]byte, error) { - resp, err := d.config.HTTPClient.Post(url, bodyType, body) - if err != nil { - return nil, fmt.Errorf("HTTP Post Error: %v", err) - } - defer resp.Body.Close() - - b, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("HTTP Post Error: %v", err) - } - - return b, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go b/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go deleted file mode 100644 index ffde8f461..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandi/gandi.go +++ /dev/null @@ -1,214 +0,0 @@ -// Package gandi implements a DNS provider for solving the DNS-01 challenge using Gandi DNS. -package gandi - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Gandi API reference: http://doc.rpc.gandi.net/index.html -// Gandi API domain examples: http://doc.rpc.gandi.net/domain/faq.html - -const ( - // defaultBaseURL Gandi XML-RPC endpoint used by Present and CleanUp - defaultBaseURL = "https://rpc.gandi.net/xmlrpc/" - minTTL = 300 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GANDI_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GANDI_PROPAGATION_TIMEOUT", 40*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GANDI_POLLING_INTERVAL", 60*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GANDI_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// inProgressInfo contains information about an in-progress challenge -type inProgressInfo struct { - zoneID int // zoneID of gandi zone to restore in CleanUp - newZoneID int // zoneID of temporary gandi zone containing TXT record - authZone string // the domain name registered at gandi with trailing "." -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses Gandi's XML-RPC -// API to manage TXT records for a domain. -type DNSProvider struct { - inProgressFQDNs map[string]inProgressInfo - inProgressAuthZones map[string]struct{} - inProgressMu sync.Mutex - config *Config - // findZoneByFqdn determines the DNS zone of an fqdn. It is overridden during tests. - findZoneByFqdn func(fqdn string) (string, error) -} - -// NewDNSProvider returns a DNSProvider instance configured for Gandi. -// Credentials must be passed in the environment variable: GANDI_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GANDI_API_KEY") - if err != nil { - return nil, fmt.Errorf("gandi: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GANDI_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Gandi. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("gandi: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("gandi: no API Key given") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - return &DNSProvider{ - config: config, - inProgressFQDNs: make(map[string]inProgressInfo), - inProgressAuthZones: make(map[string]struct{}), - findZoneByFqdn: dns01.FindZoneByFqdn, - }, nil -} - -// Present creates a TXT record using the specified parameters. It -// does this by creating and activating a new temporary Gandi DNS -// zone. This new zone contains the TXT record. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - if d.config.TTL < minTTL { - d.config.TTL = minTTL // 300 is gandi minimum value for ttl - } - - // find authZone and Gandi zone_id for fqdn - authZone, err := d.findZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("gandi: findZoneByFqdn failure: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("gandi: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - if _, ok := d.inProgressAuthZones[authZone]; ok { - return fmt.Errorf("gandi: challenge already in progress for authZone %s", authZone) - } - - // perform API actions to create and activate new gandi zone - // containing the required TXT record - newZoneName := fmt.Sprintf("%s [ACME Challenge %s]", dns01.UnFqdn(authZone), time.Now().Format(time.RFC822Z)) - - newZoneID, err := d.cloneZone(zoneID, newZoneName) - if err != nil { - return err - } - - newZoneVersion, err := d.newZoneVersion(newZoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.addTXTRecord(newZoneID, newZoneVersion, name, value, d.config.TTL) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.setZoneVersion(newZoneID, newZoneVersion) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - err = d.setZone(authZone, newZoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - // save data necessary for CleanUp - d.inProgressFQDNs[fqdn] = inProgressInfo{ - zoneID: zoneID, - newZoneID: newZoneID, - authZone: authZone, - } - d.inProgressAuthZones[authZone] = struct{}{} - - return nil -} - -// CleanUp removes the TXT record matching the specified -// parameters. It does this by restoring the old Gandi DNS zone and -// removing the temporary one created by Present. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve zoneID, newZoneID and authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - if _, ok := d.inProgressFQDNs[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - zoneID := d.inProgressFQDNs[fqdn].zoneID - newZoneID := d.inProgressFQDNs[fqdn].newZoneID - authZone := d.inProgressFQDNs[fqdn].authZone - delete(d.inProgressFQDNs, fqdn) - delete(d.inProgressAuthZones, authZone) - - // perform API actions to restore old gandi zone for authZone - err := d.setZone(authZone, zoneID) - if err != nil { - return fmt.Errorf("gandi: %v", err) - } - - return d.deleteZone(newZoneID) -} - -// Timeout returns the values (40*time.Minute, 60*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with Gandi. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go deleted file mode 100644 index 5c2c2485e..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/client.go +++ /dev/null @@ -1,199 +0,0 @@ -package gandiv5 - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - - "github.com/go-acme/lego/log" -) - -const apiKeyHeader = "X-Api-Key" - -// types for JSON responses with only a message -type apiResponse struct { - Message string `json:"message"` - UUID string `json:"uuid,omitempty"` -} - -// Record TXT record representation -type Record struct { - RRSetTTL int `json:"rrset_ttl"` - RRSetValues []string `json:"rrset_values"` - RRSetName string `json:"rrset_name,omitempty"` - RRSetType string `json:"rrset_type,omitempty"` -} - -func (d *DNSProvider) addTXTRecord(domain string, name string, value string, ttl int) error { - // Get exiting values for the TXT records - // Needed to create challenges for both wildcard and base name domains - txtRecord, err := d.getTXTRecord(domain, name) - if err != nil { - return err - } - - values := []string{value} - if len(txtRecord.RRSetValues) > 0 { - values = append(values, txtRecord.RRSetValues...) - } - - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - newRecord := &Record{RRSetTTL: ttl, RRSetValues: values} - req, err := d.newRequest(http.MethodPut, target, newRecord) - if err != nil { - return err - } - - message := apiResponse{} - err = d.do(req, &message) - if err != nil { - return fmt.Errorf("unable to create TXT record for domain %s and name %s: %v", domain, name, err) - } - - if len(message.Message) > 0 { - log.Infof("API response: %s", message.Message) - } - - return nil -} - -func (d *DNSProvider) getTXTRecord(domain, name string) (*Record, error) { - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - // Get exiting values for the TXT records - // Needed to create challenges for both wildcard and base name domains - req, err := d.newRequest(http.MethodGet, target, nil) - if err != nil { - return nil, err - } - - txtRecord := &Record{} - err = d.do(req, txtRecord) - if err != nil { - return nil, fmt.Errorf("unable to get TXT records for domain %s and name %s: %v", domain, name, err) - } - - return txtRecord, nil -} - -func (d *DNSProvider) deleteTXTRecord(domain string, name string) error { - target := fmt.Sprintf("domains/%s/records/%s/TXT", domain, name) - - req, err := d.newRequest(http.MethodDelete, target, nil) - if err != nil { - return err - } - - message := apiResponse{} - err = d.do(req, &message) - if err != nil { - return fmt.Errorf("unable to delete TXT record for domain %s and name %s: %v", domain, name, err) - } - - if len(message.Message) > 0 { - log.Infof("API response: %s", message.Message) - } - - return nil -} - -func (d *DNSProvider) newRequest(method, resource string, body interface{}) (*http.Request, error) { - u := fmt.Sprintf("%s/%s", d.config.BaseURL, resource) - - if body == nil { - req, err := http.NewRequest(method, u, nil) - if err != nil { - return nil, err - } - - return req, nil - } - - reqBody, err := json.Marshal(body) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, u, bytes.NewBuffer(reqBody)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - return req, nil -} - -func (d *DNSProvider) do(req *http.Request, v interface{}) error { - if len(d.config.APIKey) > 0 { - req.Header.Set(apiKeyHeader, d.config.APIKey) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - err = checkResponse(resp) - if err != nil { - return err - } - - if v == nil { - return nil - } - - raw, err := readBody(resp) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - if len(raw) > 0 { - err = json.Unmarshal(raw, v) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(raw)) - } - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode == 404 && resp.Request.Method == http.MethodGet { - return nil - } - - if resp.StatusCode >= 400 { - data, err := readBody(resp) - if err != nil { - return fmt.Errorf("%d [%s] request failed: %v", resp.StatusCode, http.StatusText(resp.StatusCode), err) - } - - message := &apiResponse{} - err = json.Unmarshal(data, message) - if err != nil { - return fmt.Errorf("%d [%s] request failed: %v: %s", resp.StatusCode, http.StatusText(resp.StatusCode), err, data) - } - return fmt.Errorf("%d [%s] request failed: %s", resp.StatusCode, http.StatusText(resp.StatusCode), message.Message) - } - - return nil -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go b/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go deleted file mode 100644 index e7d326b6c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gandiv5/gandiv5.go +++ /dev/null @@ -1,167 +0,0 @@ -// Package gandiv5 implements a DNS provider for solving the DNS-01 challenge using Gandi LiveDNS api. -package gandiv5 - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Gandi API reference: http://doc.livedns.gandi.net/ - -const ( - // defaultBaseURL endpoint is the Gandi API endpoint used by Present and CleanUp. - defaultBaseURL = "https://dns.api.gandi.net/api/v5" - minTTL = 300 -) - -// inProgressInfo contains information about an in-progress challenge -type inProgressInfo struct { - fieldName string - authZone string -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GANDIV5_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GANDIV5_PROPAGATION_TIMEOUT", 20*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GANDIV5_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GANDIV5_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses Gandi's LiveDNS -// API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - inProgressFQDNs map[string]inProgressInfo - inProgressMu sync.Mutex - // findZoneByFqdn determines the DNS zone of an fqdn. It is overridden during tests. - findZoneByFqdn func(fqdn string) (string, error) -} - -// NewDNSProvider returns a DNSProvider instance configured for Gandi. -// Credentials must be passed in the environment variable: GANDIV5_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GANDIV5_API_KEY") - if err != nil { - return nil, fmt.Errorf("gandi: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GANDIV5_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Gandi. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("gandiv5: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("gandiv5: no API Key given") - } - - if config.BaseURL == "" { - config.BaseURL = defaultBaseURL - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("gandiv5: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - inProgressFQDNs: make(map[string]inProgressInfo), - findZoneByFqdn: dns01.FindZoneByFqdn, - }, nil -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // find authZone - authZone, err := d.findZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("gandiv5: findZoneByFqdn failure: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("gandiv5: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - // add TXT record into authZone - err = d.addTXTRecord(dns01.UnFqdn(authZone), name, value, d.config.TTL) - if err != nil { - return err - } - - // save data necessary for CleanUp - d.inProgressFQDNs[fqdn] = inProgressInfo{ - authZone: authZone, - fieldName: name, - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - if _, ok := d.inProgressFQDNs[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - fieldName := d.inProgressFQDNs[fqdn].fieldName - authZone := d.inProgressFQDNs[fqdn].authZone - delete(d.inProgressFQDNs, fqdn) - - // delete TXT record from authZone - err := d.deleteTXTRecord(dns01.UnFqdn(authZone), fieldName) - if err != nil { - return fmt.Errorf("gandiv5: %v", err) - } - return nil -} - -// Timeout returns the values (20*time.Minute, 20*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with Gandi. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go b/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go deleted file mode 100644 index 331a5c04c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/gcloud/googlecloud.go +++ /dev/null @@ -1,337 +0,0 @@ -// Package gcloud implements a DNS provider for solving the DNS-01 challenge using Google Cloud DNS. -package gcloud - -import ( - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" - "golang.org/x/net/context" - "golang.org/x/oauth2/google" - "google.golang.org/api/dns/v1" - "google.golang.org/api/googleapi" - "google.golang.org/api/option" -) - -const ( - changeStatusDone = "done" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Debug bool - Project string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - Debug: env.GetOrDefaultBool("GCE_DEBUG", false), - TTL: env.GetOrDefaultInt("GCE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("GCE_PROPAGATION_TIMEOUT", 180*time.Second), - PollingInterval: env.GetOrDefaultSecond("GCE_POLLING_INTERVAL", 5*time.Second), - } -} - -// DNSProvider is an implementation of the DNSProvider interface. -type DNSProvider struct { - config *Config - client *dns.Service -} - -// NewDNSProvider returns a DNSProvider instance configured for Google Cloud DNS. -// Project name must be passed in the environment variable: GCE_PROJECT. -// A Service Account can be passed in the environment variable: GCE_SERVICE_ACCOUNT -// or by specifying the keyfile location: GCE_SERVICE_ACCOUNT_FILE -func NewDNSProvider() (*DNSProvider, error) { - // Use a service account file if specified via environment variable. - if saKey := env.GetOrFile("GCE_SERVICE_ACCOUNT"); len(saKey) > 0 { - return NewDNSProviderServiceAccountKey([]byte(saKey)) - } - - // Use default credentials. - project := env.GetOrDefaultString("GCE_PROJECT", "") - return NewDNSProviderCredentials(project) -} - -// NewDNSProviderCredentials uses the supplied credentials -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderCredentials(project string) (*DNSProvider, error) { - if project == "" { - return nil, fmt.Errorf("googlecloud: project name missing") - } - - client, err := google.DefaultClient(context.Background(), dns.NdevClouddnsReadwriteScope) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to get Google Cloud client: %v", err) - } - - config := NewDefaultConfig() - config.Project = project - config.HTTPClient = client - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderServiceAccountKey uses the supplied service account JSON -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderServiceAccountKey(saKey []byte) (*DNSProvider, error) { - if len(saKey) == 0 { - return nil, fmt.Errorf("googlecloud: Service Account is missing") - } - - // If GCE_PROJECT is non-empty it overrides the project in the service - // account file. - project := env.GetOrDefaultString("GCE_PROJECT", "") - if project == "" { - // read project id from service account file - var datJSON struct { - ProjectID string `json:"project_id"` - } - err := json.Unmarshal(saKey, &datJSON) - if err != nil || datJSON.ProjectID == "" { - return nil, fmt.Errorf("googlecloud: project ID not found in Google Cloud Service Account file") - } - project = datJSON.ProjectID - } - - conf, err := google.JWTConfigFromJSON(saKey, dns.NdevClouddnsReadwriteScope) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to acquire config: %v", err) - } - client := conf.Client(context.Background()) - - config := NewDefaultConfig() - config.Project = project - config.HTTPClient = client - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderServiceAccount uses the supplied service account JSON file -// to return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderServiceAccount(saFile string) (*DNSProvider, error) { - if saFile == "" { - return nil, fmt.Errorf("googlecloud: Service Account file missing") - } - - saKey, err := ioutil.ReadFile(saFile) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to read Service Account file: %v", err) - } - - return NewDNSProviderServiceAccountKey(saKey) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Google Cloud DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("googlecloud: the configuration of the DNS provider is nil") - } - if config.HTTPClient == nil { - return nil, fmt.Errorf("googlecloud: unable to create Google Cloud DNS service: client is nil") - } - - svc, err := dns.NewService(context.Background(), option.WithHTTPClient(config.HTTPClient)) - if err != nil { - return nil, fmt.Errorf("googlecloud: unable to create Google Cloud DNS service: %v", err) - } - - return &DNSProvider{config: config, client: svc}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - // Look for existing records. - existingRrSet, err := d.findTxtRecords(zone, fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - for _, rrSet := range existingRrSet { - var rrd []string - for _, rr := range rrSet.Rrdatas { - data := mustUnquote(rr) - rrd = append(rrd, data) - - if data == value { - log.Printf("skip: the record already exists: %s", value) - return nil - } - } - rrSet.Rrdatas = rrd - } - - // Attempt to delete the existing records before adding the new one. - if len(existingRrSet) > 0 { - if err = d.applyChanges(zone, &dns.Change{Deletions: existingRrSet}); err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - } - - rec := &dns.ResourceRecordSet{ - Name: fqdn, - Rrdatas: []string{value}, - Ttl: int64(d.config.TTL), - Type: "TXT", - } - - // Append existing TXT record data to the new TXT record data - for _, rrSet := range existingRrSet { - for _, rr := range rrSet.Rrdatas { - if rr != value { - rec.Rrdatas = append(rec.Rrdatas, rr) - } - } - } - - change := &dns.Change{ - Additions: []*dns.ResourceRecordSet{rec}, - } - - if err = d.applyChanges(zone, change); err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - return nil -} - -func (d *DNSProvider) applyChanges(zone string, change *dns.Change) error { - if d.config.Debug { - data, _ := json.Marshal(change) - log.Printf("change (Create): %s", string(data)) - } - - chg, err := d.client.Changes.Create(d.config.Project, zone, change).Do() - if err != nil { - if v, ok := err.(*googleapi.Error); ok { - if v.Code == http.StatusNotFound { - return nil - } - } - - data, _ := json.Marshal(change) - return fmt.Errorf("failed to perform changes [zone %s, change %s]: %v", zone, string(data), err) - } - - if chg.Status == changeStatusDone { - return nil - } - - chgID := chg.Id - - // wait for change to be acknowledged - return wait.For("apply change", 30*time.Second, 3*time.Second, func() (bool, error) { - if d.config.Debug { - data, _ := json.Marshal(change) - log.Printf("change (Get): %s", string(data)) - } - - chg, err = d.client.Changes.Get(d.config.Project, zone, chgID).Do() - if err != nil { - data, _ := json.Marshal(change) - return false, fmt.Errorf("failed to get changes [zone %s, change %s]: %v", zone, string(data), err) - } - - if chg.Status == changeStatusDone { - return true, nil - } - - return false, fmt.Errorf("status: %s", chg.Status) - }) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - records, err := d.findTxtRecords(zone, fqdn) - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - - if len(records) == 0 { - return nil - } - - _, err = d.client.Changes.Create(d.config.Project, zone, &dns.Change{Deletions: records}).Do() - if err != nil { - return fmt.Errorf("googlecloud: %v", err) - } - return nil -} - -// Timeout customizes the timeout values used by the ACME package for checking -// DNS record validity. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// getHostedZone returns the managed-zone -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return "", err - } - - zones, err := d.client.ManagedZones. - List(d.config.Project). - DnsName(authZone). - Do() - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - if len(zones.ManagedZones) == 0 { - return "", fmt.Errorf("no matching domain found for domain %s", authZone) - } - - for _, z := range zones.ManagedZones { - if z.Visibility == "public" || z.Visibility == "" { - return z.Name, nil - } - } - - return "", fmt.Errorf("no public zone found for domain %s", authZone) -} - -func (d *DNSProvider) findTxtRecords(zone, fqdn string) ([]*dns.ResourceRecordSet, error) { - recs, err := d.client.ResourceRecordSets.List(d.config.Project, zone).Name(fqdn).Type("TXT").Do() - if err != nil { - return nil, err - } - - return recs.Rrsets, nil -} - -func mustUnquote(raw string) string { - clean, err := strconv.Unquote(raw) - if err != nil { - return raw - } - return clean -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go b/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go deleted file mode 100644 index ea64f6b01..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/client.go +++ /dev/null @@ -1,91 +0,0 @@ -package glesys - -import ( - "bytes" - "encoding/json" - "fmt" - "net/http" - - "github.com/go-acme/lego/log" -) - -// types for JSON method calls, parameters, and responses - -type addRecordRequest struct { - DomainName string `json:"domainname"` - Host string `json:"host"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl,omitempty"` -} - -type deleteRecordRequest struct { - RecordID int `json:"recordid"` -} - -type responseStruct struct { - Response struct { - Status struct { - Code int `json:"code"` - } `json:"status"` - Record deleteRecordRequest `json:"record"` - } `json:"response"` -} - -func (d *DNSProvider) addTXTRecord(fqdn string, domain string, name string, value string, ttl int) (int, error) { - response, err := d.sendRequest(http.MethodPost, "addrecord", addRecordRequest{ - DomainName: domain, - Host: name, - Type: "TXT", - Data: value, - TTL: ttl, - }) - - if response != nil && response.Response.Status.Code == http.StatusOK { - log.Infof("[%s]: Successfully created record id %d", fqdn, response.Response.Record.RecordID) - return response.Response.Record.RecordID, nil - } - return 0, err -} - -func (d *DNSProvider) deleteTXTRecord(fqdn string, recordid int) error { - response, err := d.sendRequest(http.MethodPost, "deleterecord", deleteRecordRequest{ - RecordID: recordid, - }) - if response != nil && response.Response.Status.Code == 200 { - log.Infof("[%s]: Successfully deleted record id %d", fqdn, recordid) - } - return err -} - -func (d *DNSProvider) sendRequest(method string, resource string, payload interface{}) (*responseStruct, error) { - url := fmt.Sprintf("%s/%s", defaultBaseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.SetBasicAuth(d.config.APIUser, d.config.APIKey) - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("request failed with HTTP status code %d", resp.StatusCode) - } - - var response responseStruct - err = json.NewDecoder(resp.Body).Decode(&response) - - return &response, err -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go b/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go deleted file mode 100644 index 6b481cfaa..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/glesys/glesys.go +++ /dev/null @@ -1,146 +0,0 @@ -// Package glesys implements a DNS provider for solving the DNS-01 challenge using GleSYS api. -package glesys - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // defaultBaseURL is the GleSYS API endpoint used by Present and CleanUp. - defaultBaseURL = "https://api.glesys.com/domain" - minTTL = 60 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIUser string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GLESYS_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GLESYS_PROPAGATION_TIMEOUT", 20*time.Minute), - PollingInterval: env.GetOrDefaultSecond("GLESYS_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GLESYS_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the -// acme.ChallengeProviderTimeout interface that uses GleSYS -// API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - activeRecords map[string]int - inProgressMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for GleSYS. -// Credentials must be passed in the environment variables: -// GLESYS_API_USER and GLESYS_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GLESYS_API_USER", "GLESYS_API_KEY") - if err != nil { - return nil, fmt.Errorf("glesys: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["GLESYS_API_USER"] - config.APIKey = values["GLESYS_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for GleSYS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("glesys: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("glesys: incomplete credentials provided") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("glesys: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - activeRecords: make(map[string]int), - }, nil -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // find authZone - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("glesys: findZoneByFqdn failure: %v", err) - } - - // determine name of TXT record - if !strings.HasSuffix( - strings.ToLower(fqdn), strings.ToLower("."+authZone)) { - return fmt.Errorf("glesys: unexpected authZone %s for fqdn %s", authZone, fqdn) - } - name := fqdn[:len(fqdn)-len("."+authZone)] - - // acquire lock and check there is not a challenge already in - // progress for this value of authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - - // add TXT record into authZone - recordID, err := d.addTXTRecord(domain, dns01.UnFqdn(authZone), name, value, d.config.TTL) - if err != nil { - return err - } - - // save data necessary for CleanUp - d.activeRecords[fqdn] = recordID - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // acquire lock and retrieve authZone - d.inProgressMu.Lock() - defer d.inProgressMu.Unlock() - if _, ok := d.activeRecords[fqdn]; !ok { - // if there is no cleanup information then just return - return nil - } - - recordID := d.activeRecords[fqdn] - delete(d.activeRecords, fqdn) - - // delete TXT record from authZone - return d.deleteTXTRecord(domain, recordID) -} - -// Timeout returns the values (20*time.Minute, 20*time.Second) which -// are used by the acme package as timeout and check interval values -// when checking for DNS record propagation with GleSYS. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go b/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go deleted file mode 100644 index 212b8e69c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/client.go +++ /dev/null @@ -1,53 +0,0 @@ -package godaddy - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" -) - -// DNSRecord a DNS record -type DNSRecord struct { - Type string `json:"type"` - Name string `json:"name"` - Data string `json:"data"` - Priority int `json:"priority,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -func (d *DNSProvider) updateRecords(records []DNSRecord, domainZone string, recordName string) error { - body, err := json.Marshal(records) - if err != nil { - return err - } - - var resp *http.Response - resp, err = d.makeRequest(http.MethodPut, fmt.Sprintf("/v1/domains/%s/records/TXT/%s", domainZone, recordName), bytes.NewReader(body)) - if err != nil { - return err - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - bodyBytes, _ := ioutil.ReadAll(resp.Body) - return fmt.Errorf("could not create record %v; Status: %v; Body: %s", string(body), resp.StatusCode, string(bodyBytes)) - } - return nil -} - -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (*http.Response, error) { - req, err := http.NewRequest(method, fmt.Sprintf("%s%s", defaultBaseURL, uri), body) - if err != nil { - return nil, err - } - - req.Header.Set("Accept", "application/json") - req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("sso-key %s:%s", d.config.APIKey, d.config.APISecret)) - - return d.config.HTTPClient.Do(req) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go b/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go deleted file mode 100644 index 7e803ca92..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/godaddy/godaddy.go +++ /dev/null @@ -1,151 +0,0 @@ -// Package godaddy implements a DNS provider for solving the DNS-01 challenge using godaddy DNS. -package godaddy - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - // defaultBaseURL represents the API endpoint to call. - defaultBaseURL = "https://api.godaddy.com" - minTTL = 600 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - APISecret string - PropagationTimeout time.Duration - PollingInterval time.Duration - SequenceInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("GODADDY_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("GODADDY_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("GODADDY_POLLING_INTERVAL", 2*time.Second), - SequenceInterval: env.GetOrDefaultSecond("GODADDY_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("GODADDY_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for godaddy. -// Credentials must be passed in the environment variables: -// GODADDY_API_KEY and GODADDY_API_SECRET. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("GODADDY_API_KEY", "GODADDY_API_SECRET") - if err != nil { - return nil, fmt.Errorf("godaddy: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["GODADDY_API_KEY"] - config.APISecret = values["GODADDY_API_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for godaddy. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("godaddy: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" || config.APISecret == "" { - return nil, fmt.Errorf("godaddy: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("godaddy: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - domainZone, err := d.getZone(fqdn) - if err != nil { - return err - } - - recordName := d.extractRecordName(fqdn, domainZone) - rec := []DNSRecord{ - { - Type: "TXT", - Name: recordName, - Data: value, - TTL: d.config.TTL, - }, - } - - return d.updateRecords(rec, domainZone, recordName) -} - -// CleanUp sets null value in the TXT DNS record as GoDaddy has no proper DELETE record method -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - domainZone, err := d.getZone(fqdn) - if err != nil { - return err - } - - recordName := d.extractRecordName(fqdn, domainZone) - rec := []DNSRecord{ - { - Type: "TXT", - Name: recordName, - Data: "null", - }, - } - - return d.updateRecords(rec, domainZone, recordName) -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} - -func (d *DNSProvider) getZone(fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - return dns01.UnFqdn(authZone), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go deleted file mode 100644 index b1a23a368..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/client.go +++ /dev/null @@ -1,127 +0,0 @@ -package hostingde - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "time" - - "github.com/cenkalti/backoff" -) - -const defaultBaseURL = "https://secure.hosting.de/api/dns/v1/json" - -// https://www.hosting.de/api/?json#list-zoneconfigs -func (d *DNSProvider) listZoneConfigs(findRequest ZoneConfigsFindRequest) (*ZoneConfigsFindResponse, error) { - uri := defaultBaseURL + "/zoneConfigsFind" - - findResponse := &ZoneConfigsFindResponse{} - - rawResp, err := d.post(uri, findRequest, findResponse) - if err != nil { - return nil, err - } - - if len(findResponse.Response.Data) == 0 { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(uri, rawResp)) - } - - if findResponse.Status != "success" && findResponse.Status != "pending" { - return findResponse, errors.New(toUnreadableBodyMessage(uri, rawResp)) - } - - return findResponse, nil -} - -// https://www.hosting.de/api/?json#updating-zones -func (d *DNSProvider) updateZone(updateRequest ZoneUpdateRequest) (*ZoneUpdateResponse, error) { - uri := defaultBaseURL + "/zoneUpdate" - - // but we'll need the ID later to delete the record - updateResponse := &ZoneUpdateResponse{} - - rawResp, err := d.post(uri, updateRequest, updateResponse) - if err != nil { - return nil, err - } - - if updateResponse.Status != "success" && updateResponse.Status != "pending" { - return nil, errors.New(toUnreadableBodyMessage(uri, rawResp)) - } - - return updateResponse, nil -} - -func (d *DNSProvider) getZone(findRequest ZoneConfigsFindRequest) (*ZoneConfig, error) { - ctx, cancel := context.WithCancel(context.Background()) - - var zoneConfig *ZoneConfig - - operation := func() error { - findResponse, err := d.listZoneConfigs(findRequest) - if err != nil { - cancel() - return err - } - - if findResponse.Response.Data[0].Status != "active" { - return fmt.Errorf("unexpected status: %q", findResponse.Response.Data[0].Status) - } - - zoneConfig = &findResponse.Response.Data[0] - - return nil - } - - bo := backoff.NewExponentialBackOff() - bo.InitialInterval = 3 * time.Second - bo.MaxInterval = 10 * bo.InitialInterval - bo.MaxElapsedTime = 100 * bo.InitialInterval - - // retry in case the zone was edited recently and is not yet active - err := backoff.Retry(operation, backoff.WithContext(bo, ctx)) - if err != nil { - return nil, err - } - - return zoneConfig, nil -} - -func (d *DNSProvider) post(uri string, request interface{}, response interface{}) ([]byte, error) { - body, err := json.Marshal(request) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, uri, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying API: %v", err) - } - - defer resp.Body.Close() - - content, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, errors.New(toUnreadableBodyMessage(uri, content)) - } - - err = json.Unmarshal(content, response) - if err != nil { - return nil, fmt.Errorf("%v: %s", err, toUnreadableBodyMessage(uri, content)) - } - - return content, nil -} - -func toUnreadableBodyMessage(uri string, rawBody []byte) string { - return fmt.Sprintf("the request %s sent a response with a body which is an invalid format: %q", uri, string(rawBody)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go deleted file mode 100644 index 4a00f0451..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/hostingde.go +++ /dev/null @@ -1,183 +0,0 @@ -// Package hostingde implements a DNS provider for solving the DNS-01 challenge using hosting.de. -package hostingde - -import ( - "errors" - "fmt" - "net/http" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - ZoneName string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("HOSTINGDE_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("HOSTINGDE_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("HOSTINGDE_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("HOSTINGDE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - recordIDs map[string]string - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for hosting.de. -// Credentials must be passed in the environment variables: -// HOSTINGDE_ZONE_NAME and HOSTINGDE_API_KEY -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("HOSTINGDE_API_KEY", "HOSTINGDE_ZONE_NAME") - if err != nil { - return nil, fmt.Errorf("hostingde: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["HOSTINGDE_API_KEY"] - config.ZoneName = values["HOSTINGDE_ZONE_NAME"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for hosting.de. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("hostingde: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, errors.New("hostingde: API key missing") - } - - if config.ZoneName == "" { - return nil, errors.New("hostingde: Zone Name missing") - } - - return &DNSProvider{ - config: config, - recordIDs: make(map[string]string), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // get the ZoneConfig for that domain - zonesFind := ZoneConfigsFindRequest{ - Filter: Filter{ - Field: "zoneName", - Value: d.config.ZoneName, - }, - Limit: 1, - Page: 1, - } - zonesFind.AuthToken = d.config.APIKey - - zoneConfig, err := d.getZone(zonesFind) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - zoneConfig.Name = d.config.ZoneName - - rec := []DNSRecord{{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: value, - TTL: d.config.TTL, - }} - - req := ZoneUpdateRequest{ - ZoneConfig: *zoneConfig, - RecordsToAdd: rec, - } - req.AuthToken = d.config.APIKey - - resp, err := d.updateZone(req) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - - for _, record := range resp.Response.Records { - if record.Name == dns01.UnFqdn(fqdn) && record.Content == fmt.Sprintf(`"%s"`, value) { - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = record.ID - d.recordIDsMu.Unlock() - } - } - - if d.recordIDs[fqdn] == "" { - return fmt.Errorf("hostingde: error getting ID of just created record, for domain %s", domain) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - rec := []DNSRecord{{ - Type: "TXT", - Name: dns01.UnFqdn(fqdn), - Content: `"` + value + `"`, - }} - - // get the ZoneConfig for that domain - zonesFind := ZoneConfigsFindRequest{ - Filter: Filter{ - Field: "zoneName", - Value: d.config.ZoneName, - }, - Limit: 1, - Page: 1, - } - zonesFind.AuthToken = d.config.APIKey - - zoneConfig, err := d.getZone(zonesFind) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - zoneConfig.Name = d.config.ZoneName - - req := ZoneUpdateRequest{ - ZoneConfig: *zoneConfig, - RecordsToDelete: rec, - } - req.AuthToken = d.config.APIKey - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - _, err = d.updateZone(req) - if err != nil { - return fmt.Errorf("hostingde: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go b/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go deleted file mode 100644 index 9c67784b6..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/hostingde/model.go +++ /dev/null @@ -1,139 +0,0 @@ -package hostingde - -import "encoding/json" - -// APIError represents an error in an API response. -// https://www.hosting.de/api/?json#warnings-and-errors -type APIError struct { - Code int `json:"code"` - ContextObject string `json:"contextObject"` - ContextPath string `json:"contextPath"` - Details []string `json:"details"` - Text string `json:"text"` - Value string `json:"value"` -} - -// Filter is used to filter FindRequests to the API. -// https://www.hosting.de/api/?json#filter-object -type Filter struct { - Field string `json:"field"` - Value string `json:"value"` -} - -// Sort is used to sort FindRequests from the API. -// https://www.hosting.de/api/?json#filtering-and-sorting -type Sort struct { - Field string `json:"zoneName"` - Order string `json:"order"` -} - -// Metadata represents the metadata in an API response. -// https://www.hosting.de/api/?json#metadata-object -type Metadata struct { - ClientTransactionID string `json:"clientTransactionId"` - ServerTransactionID string `json:"serverTransactionId"` -} - -// ZoneConfig The ZoneConfig object defines a zone. -// https://www.hosting.de/api/?json#the-zoneconfig-object -type ZoneConfig struct { - ID string `json:"id"` - AccountID string `json:"accountId"` - Status string `json:"status"` - Name string `json:"name"` - NameUnicode string `json:"nameUnicode"` - MasterIP string `json:"masterIp"` - Type string `json:"type"` - EMailAddress string `json:"emailAddress"` - ZoneTransferWhitelist []string `json:"zoneTransferWhitelist"` - LastChangeDate string `json:"lastChangeDate"` - DNSServerGroupID string `json:"dnsServerGroupId"` - DNSSecMode string `json:"dnsSecMode"` - SOAValues *SOAValues `json:"soaValues,omitempty"` - TemplateValues json.RawMessage `json:"templateValues,omitempty"` -} - -// SOAValues The SOA values object contains the time (seconds) used in a zone’s SOA record. -// https://www.hosting.de/api/?json#the-soa-values-object -type SOAValues struct { - Refresh int `json:"refresh"` - Retry int `json:"retry"` - Expire int `json:"expire"` - TTL int `json:"ttl"` - NegativeTTL int `json:"negativeTtl"` -} - -// DNSRecord The DNS Record object is part of a zone. It is used to manage DNS resource records. -// https://www.hosting.de/api/?json#the-record-object -type DNSRecord struct { - ID string `json:"id,omitempty"` - ZoneID string `json:"zoneId,omitempty"` - RecordTemplateID string `json:"recordTemplateId,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` - Content string `json:"content,omitempty"` - TTL int `json:"ttl,omitempty"` - Priority int `json:"priority,omitempty"` - LastChangeDate string `json:"lastChangeDate,omitempty"` -} - -// Zone The Zone Object. -// https://www.hosting.de/api/?json#the-zone-object -type Zone struct { - Records []DNSRecord `json:"records"` - ZoneConfig ZoneConfig `json:"zoneConfig"` -} - -// ZoneUpdateRequest represents a API ZoneUpdate request. -// https://www.hosting.de/api/?json#updating-zones -type ZoneUpdateRequest struct { - BaseRequest - ZoneConfig `json:"zoneConfig"` - RecordsToAdd []DNSRecord `json:"recordsToAdd"` - RecordsToDelete []DNSRecord `json:"recordsToDelete"` -} - -// ZoneUpdateResponse represents a response from the API. -// https://www.hosting.de/api/?json#updating-zones -type ZoneUpdateResponse struct { - BaseResponse - Response Zone `json:"response"` -} - -// ZoneConfigsFindRequest represents a API ZonesFind request. -// https://www.hosting.de/api/?json#list-zoneconfigs -type ZoneConfigsFindRequest struct { - BaseRequest - Filter Filter `json:"filter"` - Limit int `json:"limit"` - Page int `json:"page"` - Sort *Sort `json:"sort,omitempty"` -} - -// ZoneConfigsFindResponse represents the API response for ZoneConfigsFind. -// https://www.hosting.de/api/?json#list-zoneconfigs -type ZoneConfigsFindResponse struct { - BaseResponse - Response struct { - Limit int `json:"limit"` - Page int `json:"page"` - TotalEntries int `json:"totalEntries"` - TotalPages int `json:"totalPages"` - Type string `json:"type"` - Data []ZoneConfig `json:"data"` - } `json:"response"` -} - -// BaseResponse Common response struct. -// https://www.hosting.de/api/?json#responses -type BaseResponse struct { - Errors []APIError `json:"errors"` - Metadata Metadata `json:"metadata"` - Warnings []string `json:"warnings"` - Status string `json:"status"` -} - -// BaseRequest Common request struct. -type BaseRequest struct { - AuthToken string `json:"authToken"` -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go b/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go deleted file mode 100644 index e626f2a65..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/httpreq/httpreq.go +++ /dev/null @@ -1,195 +0,0 @@ -// Package httpreq implements a DNS provider for solving the DNS-01 challenge through a HTTP server. -package httpreq - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "os" - "path" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -type message struct { - FQDN string `json:"fqdn"` - Value string `json:"value"` -} - -type messageRaw struct { - Domain string `json:"domain"` - Token string `json:"token"` - KeyAuth string `json:"keyAuth"` -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Mode string - Username string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("HTTPREQ_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("HTTPREQ_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("HTTPREQ_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("HTTPREQ_ENDPOINT") - if err != nil { - return nil, fmt.Errorf("httpreq: %v", err) - } - - endpoint, err := url.Parse(values["HTTPREQ_ENDPOINT"]) - if err != nil { - return nil, fmt.Errorf("httpreq: %v", err) - } - - config := NewDefaultConfig() - config.Mode = os.Getenv("HTTPREQ_MODE") - config.Username = os.Getenv("HTTPREQ_USERNAME") - config.Password = os.Getenv("HTTPREQ_PASSWORD") - config.Endpoint = endpoint - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("httpreq: the configuration of the DNS provider is nil") - } - - if config.Endpoint == nil { - return nil, errors.New("httpreq: the endpoint is missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - if d.config.Mode == "RAW" { - msg := &messageRaw{ - Domain: domain, - Token: token, - KeyAuth: keyAuth, - } - - err := d.doPost("/present", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - msg := &message{ - FQDN: fqdn, - Value: value, - } - - err := d.doPost("/present", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - if d.config.Mode == "RAW" { - msg := &messageRaw{ - Domain: domain, - Token: token, - KeyAuth: keyAuth, - } - - err := d.doPost("/cleanup", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - msg := &message{ - FQDN: fqdn, - Value: value, - } - - err := d.doPost("/cleanup", msg) - if err != nil { - return fmt.Errorf("httpreq: %v", err) - } - return nil -} - -func (d *DNSProvider) doPost(uri string, msg interface{}) error { - reqBody := &bytes.Buffer{} - err := json.NewEncoder(reqBody).Encode(msg) - if err != nil { - return err - } - - newURI := path.Join(d.config.Endpoint.EscapedPath(), uri) - endpoint, err := d.config.Endpoint.Parse(newURI) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, endpoint.String(), reqBody) - if err != nil { - return err - } - - req.Header.Set("Content-Type", "application/json") - - if len(d.config.Username) > 0 && len(d.config.Password) > 0 { - req.SetBasicAuth(d.config.Username, d.config.Password) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= http.StatusBadRequest { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("%d: failed to read response body: %v", resp.StatusCode, err) - } - - return fmt.Errorf("%d: request failed: %v", resp.StatusCode, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go b/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go deleted file mode 100644 index cceae690d..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/iij/iij.go +++ /dev/null @@ -1,239 +0,0 @@ -// Package iij implements a DNS provider for solving the DNS-01 challenge using IIJ DNS. -package iij - -import ( - "fmt" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/iij/doapi" - "github.com/iij/doapi/protocol" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccessKey string - SecretKey string - DoServiceCode string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("IIJ_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("IIJ_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("IIJ_POLLING_INTERVAL", 4*time.Second), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - api *doapi.API - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for IIJ DO -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("IIJ_API_ACCESS_KEY", "IIJ_API_SECRET_KEY", "IIJ_DO_SERVICE_CODE") - if err != nil { - return nil, fmt.Errorf("iij: %v", err) - } - - config := NewDefaultConfig() - config.AccessKey = values["IIJ_API_ACCESS_KEY"] - config.SecretKey = values["IIJ_API_SECRET_KEY"] - config.DoServiceCode = values["IIJ_DO_SERVICE_CODE"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig takes a given config -// and returns a custom configured DNSProvider instance -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config.SecretKey == "" || config.AccessKey == "" || config.DoServiceCode == "" { - return nil, fmt.Errorf("iij: credentials missing") - } - - return &DNSProvider{ - api: doapi.NewAPI(config.AccessKey, config.SecretKey), - config: config, - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - err := d.addTxtRecord(domain, value) - if err != nil { - return fmt.Errorf("iij: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - err := d.deleteTxtRecord(domain, value) - if err != nil { - return fmt.Errorf("iij: %v", err) - } - return nil -} - -func (d *DNSProvider) addTxtRecord(domain, value string) error { - zones, err := d.listZones() - if err != nil { - return err - } - - owner, zone, err := splitDomain(domain, zones) - if err != nil { - return err - } - - request := protocol.RecordAdd{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - Owner: owner, - TTL: strconv.Itoa(d.config.TTL), - RecordType: "TXT", - RData: value, - } - - response := &protocol.RecordAddResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return err - } - - return d.commit() -} - -func (d *DNSProvider) deleteTxtRecord(domain, value string) error { - zones, err := d.listZones() - if err != nil { - return err - } - - owner, zone, err := splitDomain(domain, zones) - if err != nil { - return err - } - - id, err := d.findTxtRecord(owner, zone, value) - if err != nil { - return err - } - - request := protocol.RecordDelete{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - RecordID: id, - } - - response := &protocol.RecordDeleteResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return err - } - - return d.commit() -} - -func (d *DNSProvider) commit() error { - request := protocol.Commit{ - DoServiceCode: d.config.DoServiceCode, - } - - response := &protocol.CommitResponse{} - - return doapi.Call(*d.api, request, response) -} - -func (d *DNSProvider) findTxtRecord(owner, zone, value string) (string, error) { - request := protocol.RecordListGet{ - DoServiceCode: d.config.DoServiceCode, - ZoneName: zone, - } - - response := &protocol.RecordListGetResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return "", err - } - - var id string - - for _, record := range response.RecordList { - if record.Owner == owner && record.RecordType == "TXT" && record.RData == "\""+value+"\"" { - id = record.Id - } - } - - if id == "" { - return "", fmt.Errorf("%s record in %s not found", owner, zone) - } - - return id, nil -} - -func (d *DNSProvider) listZones() ([]string, error) { - request := protocol.ZoneListGet{ - DoServiceCode: d.config.DoServiceCode, - } - - response := &protocol.ZoneListGetResponse{} - - if err := doapi.Call(*d.api, request, response); err != nil { - return nil, err - } - - return response.ZoneList, nil -} - -func splitDomain(domain string, zones []string) (string, string, error) { - parts := strings.Split(strings.Trim(domain, "."), ".") - - var owner string - var zone string - - for i := 0; i < len(parts)-1; i++ { - zone = strings.Join(parts[i:], ".") - if zoneContains(zone, zones) { - baseOwner := strings.Join(parts[0:i], ".") - if len(baseOwner) > 0 { - baseOwner = "." + baseOwner - } - owner = "_acme-challenge" + baseOwner - break - } - } - - if len(owner) == 0 { - return "", "", fmt.Errorf("%s not found", domain) - } - - return owner, zone, nil -} - -func zoneContains(zone string, zones []string) bool { - for _, z := range zones { - if zone == z { - return true - } - } - return false -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go b/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go deleted file mode 100644 index 8b2e34c9f..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/inwx/inwx.go +++ /dev/null @@ -1,166 +0,0 @@ -// Package inwx implements a DNS provider for solving the DNS-01 challenge using inwx dom robot -package inwx - -import ( - "errors" - "fmt" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "github.com/nrdcg/goinwx" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Username string - Password string - Sandbox bool - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("INWX_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("INWX_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("INWX_TTL", 300), - Sandbox: env.GetOrDefaultBool("INWX_SANDBOX", false), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config - client *goinwx.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Dyn DNS. -// Credentials must be passed in the environment variables: -// INWX_USERNAME and INWX_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("INWX_USERNAME", "INWX_PASSWORD") - if err != nil { - return nil, fmt.Errorf("inwx: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["INWX_USERNAME"] - config.Password = values["INWX_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Dyn DNS -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("inwx: the configuration of the DNS provider is nil") - } - - if config.Username == "" || config.Password == "" { - return nil, fmt.Errorf("inwx: credentials missing") - } - - if config.Sandbox { - log.Infof("inwx: sandbox mode is enabled") - } - - client := goinwx.NewClient(config.Username, config.Password, &goinwx.ClientOptions{Sandbox: config.Sandbox}) - - return &DNSProvider{config: config, client: client}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - err = d.client.Account.Login() - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - defer func() { - errL := d.client.Account.Logout() - if errL != nil { - log.Infof("inwx: failed to logout: %v", errL) - } - }() - - var request = &goinwx.NameserverRecordRequest{ - Domain: dns01.UnFqdn(authZone), - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - Content: value, - TTL: d.config.TTL, - } - - _, err = d.client.Nameservers.CreateRecord(request) - if err != nil { - switch er := err.(type) { - case *goinwx.ErrorResponse: - if er.Message == "Object exists" { - return nil - } - return fmt.Errorf("inwx: %v", err) - default: - return fmt.Errorf("inwx: %v", err) - } - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - err = d.client.Account.Login() - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - defer func() { - errL := d.client.Account.Logout() - if errL != nil { - log.Infof("inwx: failed to logout: %v", errL) - } - }() - - response, err := d.client.Nameservers.Info(&goinwx.NameserverInfoRequest{ - Domain: dns01.UnFqdn(authZone), - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - }) - if err != nil { - return fmt.Errorf("inwx: %v", err) - } - - var lastErr error - for _, record := range response.Records { - err = d.client.Nameservers.DeleteRecord(record.ID) - if err != nil { - lastErr = fmt.Errorf("inwx: %v", err) - } - } - - return lastErr -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/client.go b/vendor/github.com/go-acme/lego/providers/dns/joker/client.go deleted file mode 100644 index 18265a85e..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/client.go +++ /dev/null @@ -1,197 +0,0 @@ -package joker - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" -) - -const defaultBaseURL = "https://dmapi.joker.com/request/" - -// Joker DMAPI Response -type response struct { - Headers url.Values - Body string - StatusCode int - StatusText string - AuthSid string -} - -// parseResponse parses HTTP response body -func parseResponse(message string) *response { - r := &response{Headers: url.Values{}, StatusCode: -1} - - parts := strings.SplitN(message, "\n\n", 2) - - for _, line := range strings.Split(parts[0], "\n") { - if strings.TrimSpace(line) == "" { - continue - } - - kv := strings.SplitN(line, ":", 2) - - val := "" - if len(kv) == 2 { - val = strings.TrimSpace(kv[1]) - } - - r.Headers.Add(kv[0], val) - - switch kv[0] { - case "Status-Code": - i, err := strconv.Atoi(val) - if err == nil { - r.StatusCode = i - } - case "Status-Text": - r.StatusText = val - case "Auth-Sid": - r.AuthSid = val - } - } - - if len(parts) > 1 { - r.Body = parts[1] - } - - return r -} - -// login performs a login to Joker's DMAPI -func (d *DNSProvider) login() (*response, error) { - if d.config.AuthSid != "" { - // already logged in - return nil, nil - } - - response, err := d.postRequest("login", url.Values{"api-key": {d.config.APIKey}}) - if err != nil { - return response, err - } - - if response == nil { - return nil, fmt.Errorf("login returned nil response") - } - - if response.AuthSid == "" { - return response, fmt.Errorf("login did not return valid Auth-Sid") - } - - d.config.AuthSid = response.AuthSid - - return response, nil -} - -// logout closes authenticated session with Joker's DMAPI -func (d *DNSProvider) logout() (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("already logged out") - } - - response, err := d.postRequest("logout", url.Values{}) - if err == nil { - d.config.AuthSid = "" - } - return response, err -} - -// getZone returns content of DNS zone for domain -func (d *DNSProvider) getZone(domain string) (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("must be logged in to get zone") - } - - return d.postRequest("dns-zone-get", url.Values{"domain": {dns01.UnFqdn(domain)}}) -} - -// putZone uploads DNS zone to Joker DMAPI -func (d *DNSProvider) putZone(domain, zone string) (*response, error) { - if d.config.AuthSid == "" { - return nil, fmt.Errorf("must be logged in to put zone") - } - - return d.postRequest("dns-zone-put", url.Values{"domain": {dns01.UnFqdn(domain)}, "zone": {strings.TrimSpace(zone)}}) -} - -// postRequest performs actual HTTP request -func (d *DNSProvider) postRequest(cmd string, data url.Values) (*response, error) { - uri := d.config.BaseURL + cmd - - if d.config.AuthSid != "" { - data.Set("auth-sid", d.config.AuthSid) - } - - if d.config.Debug { - log.Infof("postRequest:\n\tURL: %q\n\tData: %v", uri, data) - } - - resp, err := d.config.HTTPClient.PostForm(uri, data) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - if resp.StatusCode != 200 { - return nil, fmt.Errorf("HTTP error %d [%s]: %v", resp.StatusCode, http.StatusText(resp.StatusCode), string(body)) - } - - return parseResponse(string(body)), nil -} - -// Temporary workaround, until it get fixed on API side -func fixTxtLines(line string) string { - fields := strings.Fields(line) - - if len(fields) < 6 || fields[1] != "TXT" { - return line - } - - if fields[3][0] == '"' && fields[4] == `"` { - fields[3] = strings.TrimSpace(fields[3]) + `"` - fields = append(fields[:4], fields[5:]...) - } - - return strings.Join(fields, " ") -} - -// removeTxtEntryFromZone clean-ups all TXT records with given name -func removeTxtEntryFromZone(zone, relative string) (string, bool) { - prefix := fmt.Sprintf("%s TXT 0 ", relative) - - modified := false - var zoneEntries []string - for _, line := range strings.Split(zone, "\n") { - if strings.HasPrefix(line, prefix) { - modified = true - continue - } - zoneEntries = append(zoneEntries, line) - } - - return strings.TrimSpace(strings.Join(zoneEntries, "\n")), modified -} - -// addTxtEntryToZone returns DNS zone with added TXT record -func addTxtEntryToZone(zone, relative, value string, ttl int) string { - var zoneEntries []string - - for _, line := range strings.Split(zone, "\n") { - zoneEntries = append(zoneEntries, fixTxtLines(line)) - } - - newZoneEntry := fmt.Sprintf("%s TXT 0 %q %d", relative, value, ttl) - zoneEntries = append(zoneEntries, newZoneEntry) - - return strings.TrimSpace(strings.Join(zoneEntries, "\n")) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go b/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go deleted file mode 100644 index d2dc1cac2..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/joker/joker.go +++ /dev/null @@ -1,174 +0,0 @@ -// Package joker implements a DNS provider for solving the DNS-01 challenge using joker.com DMAPI. -package joker - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - Debug bool - BaseURL string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client - AuthSid string -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - Debug: env.GetOrDefaultBool("JOKER_DEBUG", false), - TTL: env.GetOrDefaultInt("JOKER_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("JOKER_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("JOKER_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("JOKER_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the ChallengeProviderTimeout interface -// that uses Joker's DMAPI to manage TXT records for a domain. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Joker DMAPI. -// Credentials must be passed in the environment variable JOKER_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("JOKER_API_KEY") - if err != nil { - return nil, fmt.Errorf("joker: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["JOKER_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Joker DMAPI. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("joker: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("joker: credentials missing") - } - - if !strings.HasSuffix(config.BaseURL, "/") { - config.BaseURL += "/" - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present installs a TXT record for the DNS challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("joker: %v", err) - } - - relative := getRelative(fqdn, zone) - - if d.config.Debug { - log.Infof("[%s] joker: adding TXT record %q to zone %q with value %q", domain, relative, zone, value) - } - - response, err := d.login() - if err != nil { - return formatResponseError(response, err) - } - - response, err = d.getZone(zone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - dnsZone := addTxtEntryToZone(response.Body, relative, value, d.config.TTL) - - response, err = d.putZone(zone, dnsZone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - return nil -} - -// CleanUp removes a TXT record used for a previous DNS challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("joker: %v", err) - } - - relative := getRelative(fqdn, zone) - - if d.config.Debug { - log.Infof("[%s] joker: removing entry %q from zone %q", domain, relative, zone) - } - - response, err := d.login() - if err != nil { - return formatResponseError(response, err) - } - - defer func() { - // Try to logout in case of errors - _, _ = d.logout() - }() - - response, err = d.getZone(zone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - - dnsZone, modified := removeTxtEntryFromZone(response.Body, relative) - if modified { - response, err = d.putZone(zone, dnsZone) - if err != nil || response.StatusCode != 0 { - return formatResponseError(response, err) - } - } - - response, err = d.logout() - if err != nil { - return formatResponseError(response, err) - } - return nil -} - -func getRelative(fqdn, zone string) string { - return dns01.UnFqdn(strings.TrimSuffix(fqdn, dns01.ToFqdn(zone))) -} - -// formatResponseError formats error with optional details from DMAPI response -func formatResponseError(response *response, err error) error { - if response != nil { - return fmt.Errorf("joker: DMAPI error: %v Response: %v", err, response.Headers) - } - return fmt.Errorf("joker: DMAPI error: %v", err) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go b/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go deleted file mode 100644 index eb3f8338c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/lightsail/lightsail.go +++ /dev/null @@ -1,153 +0,0 @@ -// Package lightsail implements a DNS provider for solving the DNS-01 challenge using AWS Lightsail DNS. -package lightsail - -import ( - "errors" - "fmt" - "math/rand" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/lightsail" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const ( - maxRetries = 5 -) - -// customRetryer implements the client.Retryer interface by composing the DefaultRetryer. -// It controls the logic for retrying recoverable request errors (e.g. when rate limits are exceeded). -type customRetryer struct { - client.DefaultRetryer -} - -// RetryRules overwrites the DefaultRetryer's method. -// It uses a basic exponential backoff algorithm that returns an initial -// delay of ~400ms with an upper limit of ~30 seconds which should prevent -// causing a high number of consecutive throttling errors. -// For reference: Route 53 enforces an account-wide(!) 5req/s query limit. -func (c customRetryer) RetryRules(r *request.Request) time.Duration { - retryCount := r.RetryCount - if retryCount > 7 { - retryCount = 7 - } - - delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200) - return time.Duration(delay) * time.Millisecond -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - DNSZone string - Region string - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - DNSZone: env.GetOrFile("DNS_ZONE"), - PropagationTimeout: env.GetOrDefaultSecond("LIGHTSAIL_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("LIGHTSAIL_POLLING_INTERVAL", dns01.DefaultPollingInterval), - Region: env.GetOrDefaultString("LIGHTSAIL_REGION", "us-east-1"), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *lightsail.Lightsail - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for the AWS Lightsail service. -// -// AWS Credentials are automatically detected in the following locations -// and prioritized in the following order: -// 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, -// [AWS_SESSION_TOKEN], [DNS_ZONE], [LIGHTSAIL_REGION] -// 2. Shared credentials file (defaults to ~/.aws/credentials) -// 3. Amazon EC2 IAM role -// -// public hosted zone via the FQDN. -// -// See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk -func NewDNSProvider() (*DNSProvider, error) { - return NewDNSProviderConfig(NewDefaultConfig()) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for AWS Lightsail. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("lightsail: the configuration of the DNS provider is nil") - } - - retryer := customRetryer{} - retryer.NumMaxRetries = maxRetries - - conf := aws.NewConfig().WithRegion(config.Region) - sess, err := session.NewSession(request.WithRetryer(conf, retryer)) - if err != nil { - return nil, err - } - - return &DNSProvider{ - config: config, - client: lightsail.New(sess), - }, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.newTxtRecord(fqdn, `"`+value+`"`) - if err != nil { - return fmt.Errorf("lightsail: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - params := &lightsail.DeleteDomainEntryInput{ - DomainName: aws.String(d.config.DNSZone), - DomainEntry: &lightsail.DomainEntry{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - Target: aws.String(`"` + value + `"`), - }, - } - - _, err := d.client.DeleteDomainEntry(params) - if err != nil { - return fmt.Errorf("lightsail: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) newTxtRecord(fqdn string, value string) error { - params := &lightsail.CreateDomainEntryInput{ - DomainName: aws.String(d.config.DNSZone), - DomainEntry: &lightsail.DomainEntry{ - Name: aws.String(fqdn), - Target: aws.String(value), - Type: aws.String("TXT"), - }, - } - _, err := d.client.CreateDomainEntry(params) - return err -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go b/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go deleted file mode 100644 index 9ac8f85fd..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linode/linode.go +++ /dev/null @@ -1,164 +0,0 @@ -// Package linode implements a DNS provider for solving the DNS-01 challenge using Linode DNS. -package linode - -import ( - "errors" - "fmt" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/timewasted/linode/dns" -) - -const ( - minTTL = 300 - dnsUpdateFreqMins = 15 - dnsUpdateFudgeSecs = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PollingInterval: env.GetOrDefaultSecond("LINODE_POLLING_INTERVAL", 15*time.Second), - TTL: env.GetOrDefaultInt("LINODE_TTL", minTTL), - } -} - -type hostedZoneInfo struct { - domainID int - resourceName string -} - -// DNSProvider implements the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *dns.DNS -} - -// NewDNSProvider returns a DNSProvider instance configured for Linode. -// Credentials must be passed in the environment variable: LINODE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("LINODE_API_KEY") - if err != nil { - return nil, fmt.Errorf("linode: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["LINODE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Linode. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("linode: the configuration of the DNS provider is nil") - } - - if len(config.APIKey) == 0 { - return nil, errors.New("linode: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("linode: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - return &DNSProvider{ - config: config, - client: dns.New(config.APIKey), - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - // Since Linode only updates their zone files every X minutes, we need - // to figure out how many minutes we have to wait until we hit the next - // interval of X. We then wait another couple of minutes, just to be - // safe. Hopefully at some point during all of this, the record will - // have propagated throughout Linode's network. - minsRemaining := dnsUpdateFreqMins - (time.Now().Minute() % dnsUpdateFreqMins) - - timeout = (time.Duration(minsRemaining) * time.Minute) + - (minTTL * time.Second) + - (dnsUpdateFudgeSecs * time.Second) - interval = d.config.PollingInterval - return -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - if _, err = d.client.CreateDomainResourceTXT(zone.domainID, dns01.UnFqdn(fqdn), value, d.config.TTL); err != nil { - return err - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - // Get all TXT records for the specified domain. - resources, err := d.client.GetResourcesByType(zone.domainID, "TXT") - if err != nil { - return err - } - - // Remove the specified resource, if it exists. - for _, resource := range resources { - if resource.Name == zone.resourceName && resource.Target == value { - resp, err := d.client.DeleteDomainResource(resource.DomainID, resource.ResourceID) - if err != nil { - return err - } - - if resp.ResourceID != resource.ResourceID { - return errors.New("error deleting resource: resource IDs do not match") - } - break - } - } - - return nil -} - -func (d *DNSProvider) getHostedZoneInfo(fqdn string) (*hostedZoneInfo, error) { - // Lookup the zone that handles the specified FQDN. - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - resourceName := strings.TrimSuffix(fqdn, "."+authZone) - - // Query the authority zone. - domain, err := d.client.GetDomain(dns01.UnFqdn(authZone)) - if err != nil { - return nil, err - } - - return &hostedZoneInfo{ - domainID: domain.DomainID, - resourceName: resourceName, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go b/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go deleted file mode 100644 index 5d5a9fcea..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/linodev4/linodev4.go +++ /dev/null @@ -1,190 +0,0 @@ -// Package linodev4 implements a DNS provider for solving the DNS-01 challenge using Linode DNS and Linode's APIv4 -package linodev4 - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/linode/linodego" - "golang.org/x/oauth2" -) - -const ( - minTTL = 300 - dnsUpdateFreqMins = 15 - dnsUpdateFudgeSecs = 120 -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - PollingInterval time.Duration - TTL int - HTTPTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PollingInterval: env.GetOrDefaultSecond("LINODE_POLLING_INTERVAL", 15*time.Second), - TTL: env.GetOrDefaultInt("LINODE_TTL", minTTL), - HTTPTimeout: env.GetOrDefaultSecond("LINODE_HTTP_TIMEOUT", 0), - } -} - -type hostedZoneInfo struct { - domainID int - resourceName string -} - -// DNSProvider implements the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *linodego.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Linode. -// Credentials must be passed in the environment variable: LINODE_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("LINODE_TOKEN") - if err != nil { - return nil, fmt.Errorf("linodev4: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["LINODE_TOKEN"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Linode. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("linodev4: the configuration of the DNS provider is nil") - } - - if len(config.Token) == 0 { - return nil, errors.New("linodev4: Linode Access Token missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("linodev4: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: config.Token}) - oauth2Client := &http.Client{ - Timeout: config.HTTPTimeout, - Transport: &oauth2.Transport{ - Source: tokenSource, - }, - } - - client := linodego.NewClient(oauth2Client) - client.SetUserAgent(fmt.Sprintf("lego-dns linodego/%s", linodego.Version)) - - return &DNSProvider{ - config: config, - client: &client, - }, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - // Since Linode only updates their zone files every X minutes, we need - // to figure out how many minutes we have to wait until we hit the next - // interval of X. We then wait another couple of minutes, just to be - // safe. Hopefully at some point during all of this, the record will - // have propagated throughout Linode's network. - minsRemaining := dnsUpdateFreqMins - (time.Now().Minute() % dnsUpdateFreqMins) - - timeout = (time.Duration(minsRemaining) * time.Minute) + - (minTTL * time.Second) + - (dnsUpdateFudgeSecs * time.Second) - interval = d.config.PollingInterval - return -} - -// Present creates a TXT record using the specified parameters. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - createOpts := linodego.DomainRecordCreateOptions{ - Name: dns01.UnFqdn(fqdn), - Target: value, - TTLSec: d.config.TTL, - Type: linodego.RecordTypeTXT, - } - - _, err = d.client.CreateDomainRecord(context.Background(), zone.domainID, createOpts) - return err -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZoneInfo(fqdn) - if err != nil { - return err - } - - // Get all TXT records for the specified domain. - listOpts := linodego.NewListOptions(0, "{\"type\":\"TXT\"}") - resources, err := d.client.ListDomainRecords(context.Background(), zone.domainID, listOpts) - if err != nil { - return err - } - - // Remove the specified resource, if it exists. - for _, resource := range resources { - if (resource.Name == strings.TrimSuffix(fqdn, ".") || resource.Name == zone.resourceName) && - resource.Target == value { - if err := d.client.DeleteDomainRecord(context.Background(), zone.domainID, resource.ID); err != nil { - return err - } - } - } - - return nil -} - -func (d *DNSProvider) getHostedZoneInfo(fqdn string) (*hostedZoneInfo, error) { - // Lookup the zone that handles the specified FQDN. - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - // Query the authority zone. - data, err := json.Marshal(map[string]string{"domain": dns01.UnFqdn(authZone)}) - if err != nil { - return nil, err - } - - listOpts := linodego.NewListOptions(0, string(data)) - domains, err := d.client.ListDomains(context.Background(), listOpts) - if err != nil { - return nil, err - } - - if len(domains) == 0 { - return nil, fmt.Errorf("domain not found") - } - - return &hostedZoneInfo{ - domainID: domains[0].ID, - resourceName: strings.TrimSuffix(fqdn, "."+authZone), - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go deleted file mode 100644 index d8fc5841e..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/client.go +++ /dev/null @@ -1,52 +0,0 @@ -package mydnsjp - -import ( - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -func (d *DNSProvider) doRequest(domain, value string, cmd string) error { - req, err := d.buildRequest(domain, value, cmd) - if err != nil { - return err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return fmt.Errorf("error querying API: %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - var content []byte - content, err = ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - return fmt.Errorf("request %s failed [status code %d]: %s", req.URL, resp.StatusCode, string(content)) - } - - return nil -} - -func (d *DNSProvider) buildRequest(domain, value string, cmd string) (*http.Request, error) { - params := url.Values{} - params.Set("CERTBOT_DOMAIN", domain) - params.Set("CERTBOT_VALIDATION", value) - params.Set("EDIT_CMD", cmd) - - req, err := http.NewRequest(http.MethodPost, defaultBaseURL, strings.NewReader(params.Encode())) - if err != nil { - return nil, fmt.Errorf("invalid request: %v", err) - } - - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - req.SetBasicAuth(d.config.MasterID, d.config.Password) - - return req, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go b/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go deleted file mode 100644 index 0a4bc51e2..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/mydnsjp/mydnsjp.go +++ /dev/null @@ -1,93 +0,0 @@ -// Package mydnsjp implements a DNS provider for solving the DNS-01 challenge using MyDNS.jp. -package mydnsjp - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultBaseURL = "https://www.mydns.jp/directedit.html" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - MasterID string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - PropagationTimeout: env.GetOrDefaultSecond("MYDNSJP_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("MYDNSJP_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("MYDNSJP_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for MyDNS.jp. -// Credentials must be passed in the environment variables: MYDNSJP_MASTER_ID and MYDNSJP_PASSWORD. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("MYDNSJP_MASTER_ID", "MYDNSJP_PASSWORD") - if err != nil { - return nil, fmt.Errorf("mydnsjp: %v", err) - } - - config := NewDefaultConfig() - config.MasterID = values["MYDNSJP_MASTER_ID"] - config.Password = values["MYDNSJP_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for MyDNS.jp. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("mydnsjp: the configuration of the DNS provider is nil") - } - - if config.MasterID == "" || config.Password == "" { - return nil, errors.New("mydnsjp: some credentials information are missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - err := d.doRequest(domain, value, "REGIST") - if err != nil { - return fmt.Errorf("mydnsjp: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - err := d.doRequest(domain, value, "DELETE") - if err != nil { - return fmt.Errorf("mydnsjp: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go b/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go deleted file mode 100644 index 85bec85f8..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/client.go +++ /dev/null @@ -1,225 +0,0 @@ -package namecheap - -import ( - "encoding/xml" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" -) - -// Record describes a DNS record returned by the Namecheap DNS gethosts API. -// Namecheap uses the term "host" to refer to all DNS records that include -// a host field (A, AAAA, CNAME, NS, TXT, URL). -type Record struct { - Type string `xml:",attr"` - Name string `xml:",attr"` - Address string `xml:",attr"` - MXPref string `xml:",attr"` - TTL string `xml:",attr"` -} - -// apiError describes an error record in a namecheap API response. -type apiError struct { - Number int `xml:",attr"` - Description string `xml:",innerxml"` -} - -type setHostsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Status string `xml:"Status,attr"` - Errors []apiError `xml:"Errors>Error"` - Result struct { - IsSuccess string `xml:",attr"` - } `xml:"CommandResponse>DomainDNSSetHostsResult"` -} - -type getHostsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Status string `xml:"Status,attr"` - Errors []apiError `xml:"Errors>Error"` - Hosts []Record `xml:"CommandResponse>DomainDNSGetHostsResult>host"` -} - -type getTldsResponse struct { - XMLName xml.Name `xml:"ApiResponse"` - Errors []apiError `xml:"Errors>Error"` - Result []struct { - Name string `xml:",attr"` - } `xml:"CommandResponse>Tlds>Tld"` -} - -// getTLDs requests the list of available TLDs. -// https://www.namecheap.com/support/api/methods/domains/get-tld-list.aspx -func (d *DNSProvider) getTLDs() (map[string]string, error) { - request, err := d.newRequestGet("namecheap.domains.getTldList") - if err != nil { - return nil, err - } - - var gtr getTldsResponse - err = d.do(request, >r) - if err != nil { - return nil, err - } - - if len(gtr.Errors) > 0 { - return nil, fmt.Errorf("%s [%d]", gtr.Errors[0].Description, gtr.Errors[0].Number) - } - - tlds := make(map[string]string) - for _, t := range gtr.Result { - tlds[t.Name] = t.Name - } - return tlds, nil -} - -// getHosts reads the full list of DNS host records. -// https://www.namecheap.com/support/api/methods/domains-dns/get-hosts.aspx -func (d *DNSProvider) getHosts(sld, tld string) ([]Record, error) { - request, err := d.newRequestGet("namecheap.domains.dns.getHosts", - addParam("SLD", sld), - addParam("TLD", tld), - ) - if err != nil { - return nil, err - } - - var ghr getHostsResponse - err = d.do(request, &ghr) - if err != nil { - return nil, err - } - - if len(ghr.Errors) > 0 { - return nil, fmt.Errorf("%s [%d]", ghr.Errors[0].Description, ghr.Errors[0].Number) - } - - return ghr.Hosts, nil -} - -// setHosts writes the full list of DNS host records . -// https://www.namecheap.com/support/api/methods/domains-dns/set-hosts.aspx -func (d *DNSProvider) setHosts(sld, tld string, hosts []Record) error { - req, err := d.newRequestPost("namecheap.domains.dns.setHosts", - addParam("SLD", sld), - addParam("TLD", tld), - func(values url.Values) { - for i, h := range hosts { - ind := fmt.Sprintf("%d", i+1) - values.Add("HostName"+ind, h.Name) - values.Add("RecordType"+ind, h.Type) - values.Add("Address"+ind, h.Address) - values.Add("MXPref"+ind, h.MXPref) - values.Add("TTL"+ind, h.TTL) - } - }, - ) - if err != nil { - return err - } - - var shr setHostsResponse - err = d.do(req, &shr) - if err != nil { - return err - } - - if len(shr.Errors) > 0 { - return fmt.Errorf("%s [%d]", shr.Errors[0].Description, shr.Errors[0].Number) - } - if shr.Result.IsSuccess != "true" { - return fmt.Errorf("setHosts failed") - } - - return nil -} - -func (d *DNSProvider) do(req *http.Request, out interface{}) error { - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - if resp.StatusCode >= 400 { - var body []byte - body, err = readBody(resp) - if err != nil { - return fmt.Errorf("HTTP error %d [%s]: %v", resp.StatusCode, http.StatusText(resp.StatusCode), err) - } - return fmt.Errorf("HTTP error %d [%s]: %s", resp.StatusCode, http.StatusText(resp.StatusCode), string(body)) - } - - body, err := readBody(resp) - if err != nil { - return err - } - - if err := xml.Unmarshal(body, out); err != nil { - return err - } - - return nil -} - -func (d *DNSProvider) newRequestGet(cmd string, params ...func(url.Values)) (*http.Request, error) { - query := d.makeQuery(cmd, params...) - - reqURL, err := url.Parse(d.config.BaseURL) - if err != nil { - return nil, err - } - - reqURL.RawQuery = query.Encode() - - return http.NewRequest(http.MethodGet, reqURL.String(), nil) -} - -func (d *DNSProvider) newRequestPost(cmd string, params ...func(url.Values)) (*http.Request, error) { - query := d.makeQuery(cmd, params...) - - req, err := http.NewRequest(http.MethodPost, d.config.BaseURL, strings.NewReader(query.Encode())) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/x-www-form-urlencoded") - - return req, nil -} - -func (d *DNSProvider) makeQuery(cmd string, params ...func(url.Values)) url.Values { - queryParams := make(url.Values) - queryParams.Set("ApiUser", d.config.APIUser) - queryParams.Set("ApiKey", d.config.APIKey) - queryParams.Set("UserName", d.config.APIUser) - queryParams.Set("Command", cmd) - queryParams.Set("ClientIp", d.config.ClientIP) - - for _, param := range params { - param(queryParams) - } - - return queryParams -} - -func addParam(key, value string) func(url.Values) { - return func(values url.Values) { - values.Set(key, value) - } -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go b/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go deleted file mode 100644 index 2f1290f42..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namecheap/namecheap.go +++ /dev/null @@ -1,260 +0,0 @@ -// Package namecheap implements a DNS provider for solving the DNS-01 challenge using namecheap DNS. -package namecheap - -import ( - "errors" - "fmt" - "io/ioutil" - "net/http" - "strconv" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Notes about namecheap's tool API: -// 1. Using the API requires registration. Once registered, use your account -// name and API key to access the API. -// 2. There is no API to add or modify a single DNS record. Instead you must -// read the entire list of records, make modifications, and then write the -// entire updated list of records. (Yuck.) -// 3. Namecheap's DNS updates can be slow to propagate. I've seen them take -// as long as an hour. -// 4. Namecheap requires you to whitelist the IP address from which you call -// its APIs. It also requires all API calls to include the whitelisted IP -// address as a form or query string value. This code uses a namecheap -// service to query the client's IP address. - -const ( - defaultBaseURL = "https://api.namecheap.com/xml.response" - getIPURL = "https://dynamicdns.park-your-domain.com/getip" -) - -// A challenge represents all the data needed to specify a dns-01 challenge -// to lets-encrypt. -type challenge struct { - domain string - key string - keyFqdn string - keyValue string - tld string - sld string - host string -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Debug bool - BaseURL string - APIUser string - APIKey string - ClientIP string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - Debug: env.GetOrDefaultBool("NAMECHEAP_DEBUG", false), - TTL: env.GetOrDefaultInt("NAMECHEAP_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NAMECHEAP_PROPAGATION_TIMEOUT", 60*time.Minute), - PollingInterval: env.GetOrDefaultSecond("NAMECHEAP_POLLING_INTERVAL", 15*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NAMECHEAP_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the ChallengeProviderTimeout interface -// that uses Namecheap's tool API to manage TXT records for a domain. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for namecheap. -// Credentials must be passed in the environment variables: -// NAMECHEAP_API_USER and NAMECHEAP_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NAMECHEAP_API_USER", "NAMECHEAP_API_KEY") - if err != nil { - return nil, fmt.Errorf("namecheap: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["NAMECHEAP_API_USER"] - config.APIKey = values["NAMECHEAP_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for namecheap. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("namecheap: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("namecheap: credentials missing") - } - - if len(config.ClientIP) == 0 { - clientIP, err := getClientIP(config.HTTPClient, config.Debug) - if err != nil { - return nil, fmt.Errorf("namecheap: %v", err) - } - config.ClientIP = clientIP - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Namecheap can sometimes take a long time to complete an update, so wait up to 60 minutes for the update to propagate. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present installs a TXT record for the DNS challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - tlds, err := d.getTLDs() - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - ch, err := newChallenge(domain, keyAuth, tlds) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - records, err := d.getHosts(ch.sld, ch.tld) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - record := Record{ - Name: ch.key, - Type: "TXT", - Address: ch.keyValue, - MXPref: "10", - TTL: strconv.Itoa(d.config.TTL), - } - - records = append(records, record) - - if d.config.Debug { - for _, h := range records { - log.Printf("%-5.5s %-30.30s %-6s %-70.70s", h.Type, h.Name, h.TTL, h.Address) - } - } - - err = d.setHosts(ch.sld, ch.tld, records) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - return nil -} - -// CleanUp removes a TXT record used for a previous DNS challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - tlds, err := d.getTLDs() - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - ch, err := newChallenge(domain, keyAuth, tlds) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - records, err := d.getHosts(ch.sld, ch.tld) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - - // Find the challenge TXT record and remove it if found. - var found bool - var newRecords []Record - for _, h := range records { - if h.Name == ch.key && h.Type == "TXT" { - found = true - } else { - newRecords = append(newRecords, h) - } - } - - if !found { - return nil - } - - err = d.setHosts(ch.sld, ch.tld, newRecords) - if err != nil { - return fmt.Errorf("namecheap: %v", err) - } - return nil -} - -// getClientIP returns the client's public IP address. -// It uses namecheap's IP discovery service to perform the lookup. -func getClientIP(client *http.Client, debug bool) (addr string, err error) { - resp, err := client.Get(getIPURL) - if err != nil { - return "", err - } - defer resp.Body.Close() - - clientIP, err := ioutil.ReadAll(resp.Body) - if err != nil { - return "", err - } - - if debug { - log.Println("Client IP:", string(clientIP)) - } - return string(clientIP), nil -} - -// newChallenge builds a challenge record from a domain name, a challenge -// authentication key, and a map of available TLDs. -func newChallenge(domain, keyAuth string, tlds map[string]string) (*challenge, error) { - domain = dns01.UnFqdn(domain) - parts := strings.Split(domain, ".") - - // Find the longest matching TLD. - longest := -1 - for i := len(parts); i > 0; i-- { - t := strings.Join(parts[i-1:], ".") - if _, found := tlds[t]; found { - longest = i - 1 - } - } - if longest < 1 { - return nil, fmt.Errorf("invalid domain name %q", domain) - } - - tld := strings.Join(parts[longest:], ".") - sld := parts[longest-1] - - var host string - if longest >= 1 { - host = strings.Join(parts[:longest-1], ".") - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - - return &challenge{ - domain: domain, - key: "_acme-challenge." + host, - keyFqdn: fqdn, - keyValue: value, - tld: tld, - sld: sld, - host: host, - }, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go b/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go deleted file mode 100644 index 6cacbd85a..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/namedotcom/namedotcom.go +++ /dev/null @@ -1,170 +0,0 @@ -// Package namedotcom implements a DNS provider for solving the DNS-01 challenge using Name.com's DNS service. -package namedotcom - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/namedotcom/go/namecom" -) - -// according to https://www.name.com/api-docs/DNS#CreateRecord -const minTTL = 300 - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Username string - APIToken string - Server string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NAMECOM_TTL", minTTL), - PropagationTimeout: env.GetOrDefaultSecond("NAMECOM_PROPAGATION_TIMEOUT", 15*time.Minute), - PollingInterval: env.GetOrDefaultSecond("NAMECOM_POLLING_INTERVAL", 20*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NAMECOM_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *namecom.NameCom - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for namedotcom. -// Credentials must be passed in the environment variables: -// NAMECOM_USERNAME and NAMECOM_API_TOKEN -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NAMECOM_USERNAME", "NAMECOM_API_TOKEN") - if err != nil { - return nil, fmt.Errorf("namedotcom: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["NAMECOM_USERNAME"] - config.APIToken = values["NAMECOM_API_TOKEN"] - config.Server = env.GetOrFile("NAMECOM_SERVER") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for namedotcom. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("namedotcom: the configuration of the DNS provider is nil") - } - - if config.Username == "" { - return nil, fmt.Errorf("namedotcom: username is required") - } - - if config.APIToken == "" { - return nil, fmt.Errorf("namedotcom: API token is required") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("namedotcom: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := namecom.New(config.Username, config.APIToken) - client.Client = config.HTTPClient - - if config.Server != "" { - client.Server = config.Server - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - request := &namecom.Record{ - DomainName: domain, - Host: d.extractRecordName(fqdn, domain), - Type: "TXT", - TTL: uint32(d.config.TTL), - Answer: value, - } - - _, err := d.client.CreateRecord(request) - if err != nil { - return fmt.Errorf("namedotcom: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - records, err := d.getRecords(domain) - if err != nil { - return fmt.Errorf("namedotcom: %v", err) - } - - for _, rec := range records { - if rec.Fqdn == fqdn && rec.Type == "TXT" { - request := &namecom.DeleteRecordRequest{ - DomainName: domain, - ID: rec.ID, - } - _, err := d.client.DeleteRecord(request) - if err != nil { - return fmt.Errorf("namedotcom: %v", err) - } - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getRecords(domain string) ([]*namecom.Record, error) { - request := &namecom.ListRecordsRequest{ - DomainName: domain, - Page: 1, - } - - var records []*namecom.Record - for request.Page > 0 { - response, err := d.client.ListRecords(request) - if err != nil { - return nil, err - } - - records = append(records, response.Records...) - request.Page = response.NextPage - } - - return records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go deleted file mode 100644 index 733bfd0be..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/internal/client.go +++ /dev/null @@ -1,327 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "time" -) - -// defaultBaseURL for reaching the jSON-based API-Endpoint of netcup -const defaultBaseURL = "https://ccp.netcup.net/run/webservice/servers/endpoint.php?JSON" - -// success response status -const success = "success" - -// Request wrapper as specified in netcup wiki -// needed for every request to netcup API around *Msg -// https://www.netcup-wiki.de/wiki/CCP_API#Anmerkungen_zu_JSON-Requests -type Request struct { - Action string `json:"action"` - Param interface{} `json:"param"` -} - -// LoginRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#login -type LoginRequest struct { - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APIPassword string `json:"apipassword"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// LogoutRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#logout -type LogoutRequest struct { - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// UpdateDNSRecordsRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#updateDnsRecords -type UpdateDNSRecordsRequest struct { - DomainName string `json:"domainname"` - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` - DNSRecordSet DNSRecordSet `json:"dnsrecordset"` -} - -// DNSRecordSet as specified in netcup WSDL -// needed in UpdateDNSRecordsRequest -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Dnsrecordset -type DNSRecordSet struct { - DNSRecords []DNSRecord `json:"dnsrecords"` -} - -// InfoDNSRecordsRequest as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#infoDnsRecords -type InfoDNSRecordsRequest struct { - DomainName string `json:"domainname"` - CustomerNumber string `json:"customernumber"` - APIKey string `json:"apikey"` - APISessionID string `json:"apisessionid"` - ClientRequestID string `json:"clientrequestid,omitempty"` -} - -// DNSRecord as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Dnsrecord -type DNSRecord struct { - ID int `json:"id,string,omitempty"` - Hostname string `json:"hostname"` - RecordType string `json:"type"` - Priority string `json:"priority,omitempty"` - Destination string `json:"destination"` - DeleteRecord bool `json:"deleterecord,omitempty"` - State string `json:"state,omitempty"` - TTL int `json:"ttl,omitempty"` -} - -// ResponseMsg as specified in netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php#Responsemessage -type ResponseMsg struct { - ServerRequestID string `json:"serverrequestid"` - ClientRequestID string `json:"clientrequestid,omitempty"` - Action string `json:"action"` - Status string `json:"status"` - StatusCode int `json:"statuscode"` - ShortMessage string `json:"shortmessage"` - LongMessage string `json:"longmessage"` - ResponseData json.RawMessage `json:"responsedata,omitempty"` -} - -func (r *ResponseMsg) Error() string { - return fmt.Sprintf("an error occurred during the action %s: [Status=%s, StatusCode=%d, ShortMessage=%s, LongMessage=%s]", - r.Action, r.Status, r.StatusCode, r.ShortMessage, r.LongMessage) -} - -// LoginResponse response to login action. -type LoginResponse struct { - APISessionID string `json:"apisessionid"` -} - -// InfoDNSRecordsResponse response to infoDnsRecords action. -type InfoDNSRecordsResponse struct { - APISessionID string `json:"apisessionid"` - DNSRecords []DNSRecord `json:"dnsrecords,omitempty"` -} - -// Client netcup DNS client -type Client struct { - customerNumber string - apiKey string - apiPassword string - HTTPClient *http.Client - BaseURL string -} - -// NewClient creates a netcup DNS client -func NewClient(customerNumber string, apiKey string, apiPassword string) (*Client, error) { - if customerNumber == "" || apiKey == "" || apiPassword == "" { - return nil, fmt.Errorf("credentials missing") - } - - return &Client{ - customerNumber: customerNumber, - apiKey: apiKey, - apiPassword: apiPassword, - BaseURL: defaultBaseURL, - HTTPClient: &http.Client{ - Timeout: 10 * time.Second, - }, - }, nil -} - -// Login performs the login as specified by the netcup WSDL -// returns sessionID needed to perform remaining actions -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) Login() (string, error) { - payload := &Request{ - Action: "login", - Param: &LoginRequest{ - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APIPassword: c.apiPassword, - ClientRequestID: "", - }, - } - - var responseData LoginResponse - err := c.doRequest(payload, &responseData) - if err != nil { - return "", fmt.Errorf("loging error: %v", err) - } - - return responseData.APISessionID, nil -} - -// Logout performs the logout with the supplied sessionID as specified by the netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) Logout(sessionID string) error { - payload := &Request{ - Action: "logout", - Param: &LogoutRequest{ - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: sessionID, - ClientRequestID: "", - }, - } - - err := c.doRequest(payload, nil) - if err != nil { - return fmt.Errorf("logout error: %v", err) - } - - return nil -} - -// UpdateDNSRecord performs an update of the DNSRecords as specified by the netcup WSDL -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) UpdateDNSRecord(sessionID, domainName string, records []DNSRecord) error { - payload := &Request{ - Action: "updateDnsRecords", - Param: UpdateDNSRecordsRequest{ - DomainName: domainName, - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: sessionID, - ClientRequestID: "", - DNSRecordSet: DNSRecordSet{DNSRecords: records}, - }, - } - - err := c.doRequest(payload, nil) - if err != nil { - return fmt.Errorf("error when sending the request: %v", err) - } - - return nil -} - -// GetDNSRecords retrieves all dns records of an DNS-Zone as specified by the netcup WSDL -// returns an array of DNSRecords -// https://ccp.netcup.net/run/webservice/servers/endpoint.php -func (c *Client) GetDNSRecords(hostname, apiSessionID string) ([]DNSRecord, error) { - payload := &Request{ - Action: "infoDnsRecords", - Param: InfoDNSRecordsRequest{ - DomainName: hostname, - CustomerNumber: c.customerNumber, - APIKey: c.apiKey, - APISessionID: apiSessionID, - ClientRequestID: "", - }, - } - - var responseData InfoDNSRecordsResponse - err := c.doRequest(payload, &responseData) - if err != nil { - return nil, fmt.Errorf("error when sending the request: %v", err) - } - - return responseData.DNSRecords, nil - -} - -// doRequest marshals given body to JSON, send the request to netcup API -// and returns body of response -func (c *Client) doRequest(payload interface{}, responseData interface{}) error { - body, err := json.Marshal(payload) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, c.BaseURL, bytes.NewReader(body)) - if err != nil { - return err - } - - req.Close = true - req.Header.Set("content-type", "application/json") - - resp, err := c.HTTPClient.Do(req) - if err != nil { - return err - } - - if err = checkResponse(resp); err != nil { - return err - } - - respMsg, err := decodeResponseMsg(resp) - if err != nil { - return err - } - - if respMsg.Status != success { - return respMsg - } - - if responseData != nil { - err = json.Unmarshal(respMsg.ResponseData, responseData) - if err != nil { - return fmt.Errorf("%v: unmarshaling %T error: %v: %s", - respMsg, responseData, err, string(respMsg.ResponseData)) - } - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode > 299 { - if resp.Body == nil { - return fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - return fmt.Errorf("status code=%d: %s", resp.StatusCode, string(raw)) - } - - return nil -} - -func decodeResponseMsg(resp *http.Response) (*ResponseMsg, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - var respMsg ResponseMsg - err = json.Unmarshal(raw, &respMsg) - if err != nil { - return nil, fmt.Errorf("unmarshaling %T error [status code=%d]: %v: %s", respMsg, resp.StatusCode, err, string(raw)) - } - - return &respMsg, nil -} - -// GetDNSRecordIdx searches a given array of DNSRecords for a given DNSRecord -// equivalence is determined by Destination and RecortType attributes -// returns index of given DNSRecord in given array of DNSRecords -func GetDNSRecordIdx(records []DNSRecord, record DNSRecord) (int, error) { - for index, element := range records { - if record.Destination == element.Destination && record.RecordType == element.RecordType { - return index, nil - } - } - return -1, fmt.Errorf("no DNS Record found") -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go b/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go deleted file mode 100644 index 003dcbb15..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/netcup/netcup.go +++ /dev/null @@ -1,182 +0,0 @@ -// Package netcup implements a DNS Provider for solving the DNS-01 challenge using the netcup DNS API. -package netcup - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/providers/dns/netcup/internal" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Key string - Password string - Customer string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NETCUP_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NETCUP_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("NETCUP_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NETCUP_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - client *internal.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for netcup. -// Credentials must be passed in the environment variables: -// NETCUP_CUSTOMER_NUMBER, NETCUP_API_KEY, NETCUP_API_PASSWORD -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NETCUP_CUSTOMER_NUMBER", "NETCUP_API_KEY", "NETCUP_API_PASSWORD") - if err != nil { - return nil, fmt.Errorf("netcup: %v", err) - } - - config := NewDefaultConfig() - config.Customer = values["NETCUP_CUSTOMER_NUMBER"] - config.Key = values["NETCUP_API_KEY"] - config.Password = values["NETCUP_API_PASSWORD"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for netcup. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("netcup: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.Customer, config.Key, config.Password) - if err != nil { - return nil, fmt.Errorf("netcup: %v", err) - } - - client.HTTPClient = config.HTTPClient - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("netcup: failed to find DNSZone, %v", err) - } - - sessionID, err := d.client.Login() - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - defer func() { - err = d.client.Logout(sessionID) - if err != nil { - log.Print("netcup: %v", err) - } - }() - - hostname := strings.Replace(fqdn, "."+zone, "", 1) - record := internal.DNSRecord{ - Hostname: hostname, - RecordType: "TXT", - Destination: value, - TTL: d.config.TTL, - } - - zone = dns01.UnFqdn(zone) - - records, err := d.client.GetDNSRecords(zone, sessionID) - if err != nil { - // skip no existing records - log.Infof("no existing records, error ignored: %v", err) - } - - records = append(records, record) - - err = d.client.UpdateDNSRecord(sessionID, zone, records) - if err != nil { - return fmt.Errorf("netcup: failed to add TXT-Record: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domainName, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domainName, keyAuth) - - zone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("netcup: failed to find DNSZone, %v", err) - } - - sessionID, err := d.client.Login() - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - defer func() { - err = d.client.Logout(sessionID) - if err != nil { - log.Print("netcup: %v", err) - } - }() - - hostname := strings.Replace(fqdn, "."+zone, "", 1) - - zone = dns01.UnFqdn(zone) - - records, err := d.client.GetDNSRecords(zone, sessionID) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - record := internal.DNSRecord{ - Hostname: hostname, - RecordType: "TXT", - Destination: value, - } - - idx, err := internal.GetDNSRecordIdx(records, record) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - records[idx].DeleteRecord = true - - err = d.client.UpdateDNSRecord(sessionID, zone, []internal.DNSRecord{records[idx]}) - if err != nil { - return fmt.Errorf("netcup: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go deleted file mode 100644 index a2eb8a763..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/internal/client.go +++ /dev/null @@ -1,234 +0,0 @@ -package internal - -import ( - "bytes" - "crypto/hmac" - "crypto/sha1" - "encoding/base64" - "encoding/xml" - "errors" - "fmt" - "net/http" - "time" -) - -const ( - defaultBaseURL = "https://dns.api.nifcloud.com" - apiVersion = "2012-12-12N2013-12-16" - // XMLNs XML NS of Route53 - XMLNs = "https://route53.amazonaws.com/doc/2012-12-12/" -) - -// ChangeResourceRecordSetsRequest is a complex type that contains change information for the resource record set. -type ChangeResourceRecordSetsRequest struct { - XMLNs string `xml:"xmlns,attr"` - ChangeBatch ChangeBatch `xml:"ChangeBatch"` -} - -// ChangeResourceRecordSetsResponse is a complex type containing the response for the request. -type ChangeResourceRecordSetsResponse struct { - ChangeInfo ChangeInfo `xml:"ChangeInfo"` -} - -// GetChangeResponse is a complex type that contains the ChangeInfo element. -type GetChangeResponse struct { - ChangeInfo ChangeInfo `xml:"ChangeInfo"` -} - -// ErrorResponse is the information for any errors. -type ErrorResponse struct { - Error struct { - Type string `xml:"Type"` - Message string `xml:"Message"` - Code string `xml:"Code"` - } `xml:"Error"` - RequestID string `xml:"RequestId"` -} - -// ChangeBatch is the information for a change request. -type ChangeBatch struct { - Changes Changes `xml:"Changes"` - Comment string `xml:"Comment"` -} - -// Changes is array of Change. -type Changes struct { - Change []Change `xml:"Change"` -} - -// Change is the information for each resource record set that you want to change. -type Change struct { - Action string `xml:"Action"` - ResourceRecordSet ResourceRecordSet `xml:"ResourceRecordSet"` -} - -// ResourceRecordSet is the information about the resource record set to create or delete. -type ResourceRecordSet struct { - Name string `xml:"Name"` - Type string `xml:"Type"` - TTL int `xml:"TTL"` - ResourceRecords ResourceRecords `xml:"ResourceRecords"` -} - -// ResourceRecords is array of ResourceRecord. -type ResourceRecords struct { - ResourceRecord []ResourceRecord `xml:"ResourceRecord"` -} - -// ResourceRecord is the information specific to the resource record. -type ResourceRecord struct { - Value string `xml:"Value"` -} - -// ChangeInfo is A complex type that describes change information about changes made to your hosted zone. -type ChangeInfo struct { - ID string `xml:"Id"` - Status string `xml:"Status"` - SubmittedAt string `xml:"SubmittedAt"` -} - -// NewClient Creates a new client of NIFCLOUD DNS -func NewClient(accessKey string, secretKey string) (*Client, error) { - if len(accessKey) == 0 || len(secretKey) == 0 { - return nil, errors.New("credentials missing") - } - - return &Client{ - accessKey: accessKey, - secretKey: secretKey, - BaseURL: defaultBaseURL, - HTTPClient: &http.Client{}, - }, nil -} - -// Client client of NIFCLOUD DNS -type Client struct { - accessKey string - secretKey string - BaseURL string - HTTPClient *http.Client -} - -// ChangeResourceRecordSets Call ChangeResourceRecordSets API and return response. -func (c *Client) ChangeResourceRecordSets(hostedZoneID string, input ChangeResourceRecordSetsRequest) (*ChangeResourceRecordSetsResponse, error) { - requestURL := fmt.Sprintf("%s/%s/hostedzone/%s/rrset", c.BaseURL, apiVersion, hostedZoneID) - - body := &bytes.Buffer{} - body.Write([]byte(xml.Header)) - err := xml.NewEncoder(body).Encode(input) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, requestURL, body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "text/xml; charset=utf-8") - - err = c.sign(req) - if err != nil { - return nil, fmt.Errorf("an error occurred during the creation of the signature: %v", err) - } - - res, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - if res.Body == nil { - return nil, errors.New("the response body is nil") - } - - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - errResp := &ErrorResponse{} - err = xml.NewDecoder(res.Body).Decode(errResp) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the error body to XML: %v", err) - } - - return nil, fmt.Errorf("an error occurred: %s", errResp.Error.Message) - } - - output := &ChangeResourceRecordSetsResponse{} - err = xml.NewDecoder(res.Body).Decode(output) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the response body to XML: %v", err) - } - - return output, err -} - -// GetChange Call GetChange API and return response. -func (c *Client) GetChange(statusID string) (*GetChangeResponse, error) { - requestURL := fmt.Sprintf("%s/%s/change/%s", c.BaseURL, apiVersion, statusID) - - req, err := http.NewRequest(http.MethodGet, requestURL, nil) - if err != nil { - return nil, err - } - - err = c.sign(req) - if err != nil { - return nil, fmt.Errorf("an error occurred during the creation of the signature: %v", err) - } - - res, err := c.HTTPClient.Do(req) - if err != nil { - return nil, err - } - if res.Body == nil { - return nil, errors.New("the response body is nil") - } - - defer res.Body.Close() - - if res.StatusCode != http.StatusOK { - errResp := &ErrorResponse{} - err = xml.NewDecoder(res.Body).Decode(errResp) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the error body to XML: %v", err) - } - - return nil, fmt.Errorf("an error occurred: %s", errResp.Error.Message) - } - - output := &GetChangeResponse{} - err = xml.NewDecoder(res.Body).Decode(output) - if err != nil { - return nil, fmt.Errorf("an error occurred while unmarshaling the response body to XML: %v", err) - } - - return output, nil -} - -func (c *Client) sign(req *http.Request) error { - if req.Header.Get("Date") == "" { - location, err := time.LoadLocation("GMT") - if err != nil { - return err - } - - req.Header.Set("Date", time.Now().In(location).Format(time.RFC1123)) - } - - if req.URL.Path == "" { - req.URL.Path += "/" - } - - mac := hmac.New(sha1.New, []byte(c.secretKey)) - _, err := mac.Write([]byte(req.Header.Get("Date"))) - if err != nil { - return err - } - - hashed := mac.Sum(nil) - signature := base64.StdEncoding.EncodeToString(hashed) - - auth := fmt.Sprintf("NIFTY3-HTTPS NiftyAccessKeyId=%s,Algorithm=HmacSHA1,Signature=%s", c.accessKey, signature) - req.Header.Set("X-Nifty-Authorization", auth) - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go b/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go deleted file mode 100644 index ed1d7ecbc..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/nifcloud/nifcloud.go +++ /dev/null @@ -1,156 +0,0 @@ -// Package nifcloud implements a DNS provider for solving the DNS-01 challenge using NIFCLOUD DNS. -package nifcloud - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/providers/dns/nifcloud/internal" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - AccessKey string - SecretKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NIFCLOUD_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NIFCLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("NIFCLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NIFCLOUD_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *internal.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for the NIFCLOUD DNS service. -// Credentials must be passed in the environment variables: -// NIFCLOUD_ACCESS_KEY_ID and NIFCLOUD_SECRET_ACCESS_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NIFCLOUD_ACCESS_KEY_ID", "NIFCLOUD_SECRET_ACCESS_KEY") - if err != nil { - return nil, fmt.Errorf("nifcloud: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = env.GetOrFile("NIFCLOUD_DNS_ENDPOINT") - config.AccessKey = values["NIFCLOUD_ACCESS_KEY_ID"] - config.SecretKey = values["NIFCLOUD_SECRET_ACCESS_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for NIFCLOUD. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("nifcloud: the configuration of the DNS provider is nil") - } - - client, err := internal.NewClient(config.AccessKey, config.SecretKey) - if err != nil { - return nil, fmt.Errorf("nifcloud: %v", err) - } - - if config.HTTPClient != nil { - client.HTTPClient = config.HTTPClient - } - - if len(config.BaseURL) > 0 { - client.BaseURL = config.BaseURL - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("CREATE", fqdn, value, domain, d.config.TTL) - if err != nil { - return fmt.Errorf("nifcloud: %v", err) - } - return err -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("DELETE", fqdn, value, domain, d.config.TTL) - if err != nil { - return fmt.Errorf("nifcloud: %v", err) - } - return err -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) changeRecord(action, fqdn, value, domain string, ttl int) error { - name := dns01.UnFqdn(fqdn) - - reqParams := internal.ChangeResourceRecordSetsRequest{ - XMLNs: internal.XMLNs, - ChangeBatch: internal.ChangeBatch{ - Comment: "Managed by Lego", - Changes: internal.Changes{ - Change: []internal.Change{ - { - Action: action, - ResourceRecordSet: internal.ResourceRecordSet{ - Name: name, - Type: "TXT", - TTL: ttl, - ResourceRecords: internal.ResourceRecords{ - ResourceRecord: []internal.ResourceRecord{ - { - Value: value, - }, - }, - }, - }, - }, - }, - }, - }, - } - - resp, err := d.client.ChangeResourceRecordSets(domain, reqParams) - if err != nil { - return fmt.Errorf("failed to change NIFCLOUD record set: %v", err) - } - - statusID := resp.ChangeInfo.ID - - return wait.For("nifcloud", 120*time.Second, 4*time.Second, func() (bool, error) { - resp, err := d.client.GetChange(statusID) - if err != nil { - return false, fmt.Errorf("failed to query NIFCLOUD DNS change status: %v", err) - } - return resp.ChangeInfo.Status == "INSYNC", nil - }) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go b/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go deleted file mode 100644 index 9ecc43868..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ns1/ns1.go +++ /dev/null @@ -1,162 +0,0 @@ -// Package ns1 implements a DNS provider for solving the DNS-01 challenge using NS1 DNS. -package ns1 - -import ( - "errors" - "fmt" - "net/http" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "gopkg.in/ns1/ns1-go.v2/rest" - "gopkg.in/ns1/ns1-go.v2/rest/model/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("NS1_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("NS1_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("NS1_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("NS1_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *rest.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for NS1. -// Credentials must be passed in the environment variables: NS1_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("NS1_API_KEY") - if err != nil { - return nil, fmt.Errorf("ns1: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["NS1_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for NS1. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ns1: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("ns1: credentials missing") - } - - client := rest.NewClient(config.HTTPClient, rest.SetAPIKey(config.APIKey)) - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("ns1: %v", err) - } - - record, _, err := d.client.Records.Get(zone.Zone, dns01.UnFqdn(fqdn), "TXT") - - // Create a new record - if err == rest.ErrRecordMissing || record == nil { - log.Infof("Create a new record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, fqdn) - - record = dns.NewRecord(zone.Zone, dns01.UnFqdn(fqdn), "TXT") - record.TTL = d.config.TTL - record.Answers = []*dns.Answer{{Rdata: []string{value}}} - - _, err = d.client.Records.Create(record) - if err != nil { - return fmt.Errorf("ns1: failed to create record [zone: %q, fqdn: %q]: %v", zone.Zone, fqdn, err) - } - - return nil - } - - if err != nil { - return fmt.Errorf("ns1: failed to get the existing record: %v", err) - } - - // Update the existing records - record.Answers = append(record.Answers, &dns.Answer{Rdata: []string{value}}) - - log.Infof("Update an existing record for [zone: %s, fqdn: %s, domain: %s]", zone.Zone, fqdn, domain) - - _, err = d.client.Records.Update(record) - if err != nil { - return fmt.Errorf("ns1: failed to update record [zone: %q, fqdn: %q]: %v", zone.Zone, fqdn, err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("ns1: %v", err) - } - - name := dns01.UnFqdn(fqdn) - _, err = d.client.Records.Delete(zone.Zone, name, "TXT") - if err != nil { - return fmt.Errorf("ns1: failed to delete record [zone: %q, domain: %q]: %v", zone.Zone, name, err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(fqdn string) (*dns.Zone, error) { - authZone, err := getAuthZone(fqdn) - if err != nil { - return nil, fmt.Errorf("failed to extract auth zone from fqdn %q: %v", fqdn, err) - } - - zone, _, err := d.client.Zones.Get(authZone) - if err != nil { - return nil, fmt.Errorf("failed to get zone [authZone: %q, fqdn: %q]: %v", authZone, fqdn, err) - } - - return zone, nil -} - -func getAuthZone(fqdn string) (string, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - return strings.TrimSuffix(authZone, "."), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go deleted file mode 100644 index afde36827..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/configprovider.go +++ /dev/null @@ -1,101 +0,0 @@ -package oraclecloud - -import ( - "crypto/rsa" - "encoding/base64" - "fmt" - "io/ioutil" - "os" - - "github.com/go-acme/lego/platform/config/env" - "github.com/oracle/oci-go-sdk/common" -) - -const ( - ociPrivkey = "OCI_PRIVKEY" - ociPrivkeyPass = "OCI_PRIVKEY_PASS" - ociTenancyOCID = "OCI_TENANCY_OCID" - ociUserOCID = "OCI_USER_OCID" - ociPubkeyFingerprint = "OCI_PUBKEY_FINGERPRINT" - ociRegion = "OCI_REGION" -) - -type configProvider struct { - values map[string]string - privateKeyPassphrase string -} - -func newConfigProvider(values map[string]string) *configProvider { - return &configProvider{ - values: values, - privateKeyPassphrase: env.GetOrFile(ociPrivkeyPass), - } -} - -func (p *configProvider) PrivateRSAKey() (*rsa.PrivateKey, error) { - privateKey, err := getPrivateKey(ociPrivkey) - if err != nil { - return nil, err - } - - return common.PrivateKeyFromBytes(privateKey, common.String(p.privateKeyPassphrase)) -} - -func (p *configProvider) KeyID() (string, error) { - tenancy, err := p.TenancyOCID() - if err != nil { - return "", err - } - - user, err := p.UserOCID() - if err != nil { - return "", err - } - - fingerprint, err := p.KeyFingerprint() - if err != nil { - return "", err - } - - return fmt.Sprintf("%s/%s/%s", tenancy, user, fingerprint), nil -} - -func (p *configProvider) TenancyOCID() (value string, err error) { - return p.values[ociTenancyOCID], nil -} - -func (p *configProvider) UserOCID() (string, error) { - return p.values[ociUserOCID], nil -} - -func (p *configProvider) KeyFingerprint() (string, error) { - return p.values[ociPubkeyFingerprint], nil -} - -func (p *configProvider) Region() (string, error) { - return p.values[ociRegion], nil -} - -func getPrivateKey(envVar string) ([]byte, error) { - envVarValue := os.Getenv(envVar) - if envVarValue != "" { - bytes, err := base64.StdEncoding.DecodeString(envVarValue) - if err != nil { - return nil, fmt.Errorf("failed to read base64 value %s (defined by env var %s): %s", envVarValue, envVar, err) - } - return bytes, nil - } - - fileVar := envVar + "_FILE" - fileVarValue := os.Getenv(fileVar) - if fileVarValue == "" { - return nil, fmt.Errorf("no value provided for: %s or %s", envVar, fileVar) - } - - fileContents, err := ioutil.ReadFile(fileVarValue) - if err != nil { - return nil, fmt.Errorf("failed to read the file %s (defined by env var %s): %s", fileVarValue, fileVar, err) - } - - return fileContents, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go b/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go deleted file mode 100644 index 9218cb8c5..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/oraclecloud/oraclecloud.go +++ /dev/null @@ -1,175 +0,0 @@ -package oraclecloud - -import ( - "context" - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/oracle/oci-go-sdk/common" - "github.com/oracle/oci-go-sdk/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - CompartmentID string - OCIConfigProvider common.ConfigurationProvider - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("OCI_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("OCI_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OCI_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OCI_HTTP_TIMEOUT", 60*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - client *dns.DnsClient - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for OracleCloud. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(ociPrivkey, ociTenancyOCID, ociUserOCID, ociPubkeyFingerprint, ociRegion, "OCI_COMPARTMENT_OCID") - if err != nil { - return nil, fmt.Errorf("oraclecloud: %v", err) - } - - config := NewDefaultConfig() - config.CompartmentID = values["OCI_COMPARTMENT_OCID"] - config.OCIConfigProvider = newConfigProvider(values) - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OracleCloud. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("oraclecloud: the configuration of the DNS provider is nil") - } - - if config.CompartmentID == "" { - return nil, errors.New("oraclecloud: CompartmentID is missing") - } - - if config.OCIConfigProvider == nil { - return nil, errors.New("oraclecloud: OCIConfigProvider is missing") - } - - client, err := dns.NewDnsClientWithConfigurationProvider(config.OCIConfigProvider) - if err != nil { - return nil, fmt.Errorf("oraclecloud: %v", err) - } - - if config.HTTPClient != nil { - client.HTTPClient = config.HTTPClient - } - - return &DNSProvider{client: &client, config: config}, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // generate request to dns.PatchDomainRecordsRequest - recordOperation := dns.RecordOperation{ - Domain: common.String(dns01.UnFqdn(fqdn)), - Rdata: common.String(value), - Rtype: common.String("TXT"), - Ttl: common.Int(d.config.TTL), - IsProtected: common.Bool(false), - } - - request := dns.PatchDomainRecordsRequest{ - CompartmentId: common.String(d.config.CompartmentID), - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - PatchDomainRecordsDetails: dns.PatchDomainRecordsDetails{ - Items: []dns.RecordOperation{recordOperation}, - }, - } - - _, err := d.client.PatchDomainRecords(context.Background(), request) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // search to TXT record's hash to delete - getRequest := dns.GetDomainRecordsRequest{ - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - CompartmentId: common.String(d.config.CompartmentID), - Rtype: common.String("TXT"), - } - - ctx := context.Background() - - domainRecords, err := d.client.GetDomainRecords(ctx, getRequest) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - if *domainRecords.OpcTotalItems == 0 { - return fmt.Errorf("oraclecloud: no record to CleanUp") - } - - var deleteHash *string - for _, record := range domainRecords.RecordCollection.Items { - if record.Rdata != nil && *record.Rdata == `"`+value+`"` { - deleteHash = record.RecordHash - break - } - } - - if deleteHash == nil { - return fmt.Errorf("oraclecloud: no record to CleanUp") - } - - recordOperation := dns.RecordOperation{ - RecordHash: deleteHash, - Operation: dns.RecordOperationOperationRemove, - } - - patchRequest := dns.PatchDomainRecordsRequest{ - ZoneNameOrId: common.String(domain), - Domain: common.String(dns01.UnFqdn(fqdn)), - PatchDomainRecordsDetails: dns.PatchDomainRecordsDetails{ - Items: []dns.RecordOperation{recordOperation}, - }, - CompartmentId: common.String(d.config.CompartmentID), - } - - _, err = d.client.PatchDomainRecords(ctx, patchRequest) - if err != nil { - return fmt.Errorf("oraclecloud: %v", err) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/client.go b/vendor/github.com/go-acme/lego/providers/dns/otc/client.go deleted file mode 100644 index 1cd71f551..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/client.go +++ /dev/null @@ -1,263 +0,0 @@ -package otc - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" -) - -type recordset struct { - Name string `json:"name"` - Description string `json:"description"` - Type string `json:"type"` - TTL int `json:"ttl"` - Records []string `json:"records"` -} - -type nameResponse struct { - Name string `json:"name"` -} - -type userResponse struct { - Name string `json:"name"` - Password string `json:"password"` - Domain nameResponse `json:"domain"` -} - -type passwordResponse struct { - User userResponse `json:"user"` -} - -type identityResponse struct { - Methods []string `json:"methods"` - Password passwordResponse `json:"password"` -} - -type scopeResponse struct { - Project nameResponse `json:"project"` -} - -type authResponse struct { - Identity identityResponse `json:"identity"` - Scope scopeResponse `json:"scope"` -} - -type loginResponse struct { - Auth authResponse `json:"auth"` -} - -type endpointResponse struct { - Token token `json:"token"` -} - -type token struct { - Catalog []catalog `json:"catalog"` -} - -type catalog struct { - Type string `json:"type"` - Endpoints []endpoint `json:"endpoints"` -} - -type endpoint struct { - URL string `json:"url"` -} - -type zoneItem struct { - ID string `json:"id"` -} - -type zonesResponse struct { - Zones []zoneItem `json:"zones"` -} - -type recordSet struct { - ID string `json:"id"` -} - -type recordSetsResponse struct { - RecordSets []recordSet `json:"recordsets"` -} - -// Starts a new OTC API Session. Authenticates using userName, password -// and receives a token to be used in for subsequent requests. -func (d *DNSProvider) login() error { - return d.loginRequest() -} - -func (d *DNSProvider) loginRequest() error { - userResp := userResponse{ - Name: d.config.UserName, - Password: d.config.Password, - Domain: nameResponse{ - Name: d.config.DomainName, - }, - } - - loginResp := loginResponse{ - Auth: authResponse{ - Identity: identityResponse{ - Methods: []string{"password"}, - Password: passwordResponse{ - User: userResp, - }, - }, - Scope: scopeResponse{ - Project: nameResponse{ - Name: d.config.ProjectName, - }, - }, - }, - } - - body, err := json.Marshal(loginResp) - if err != nil { - return err - } - - req, err := http.NewRequest(http.MethodPost, d.config.IdentityEndpoint, bytes.NewReader(body)) - if err != nil { - return err - } - req.Header.Set("Content-Type", "application/json") - - client := &http.Client{Timeout: d.config.HTTPClient.Timeout} - resp, err := client.Do(req) - if err != nil { - return err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return fmt.Errorf("OTC API request failed with HTTP status code %d", resp.StatusCode) - } - - d.token = resp.Header.Get("X-Subject-Token") - - if d.token == "" { - return fmt.Errorf("unable to get auth token") - } - - var endpointResp endpointResponse - - err = json.NewDecoder(resp.Body).Decode(&endpointResp) - if err != nil { - return err - } - - var endpoints []endpoint - for _, v := range endpointResp.Token.Catalog { - if v.Type == "dns" { - endpoints = append(endpoints, v.Endpoints...) - } - } - - if len(endpoints) > 0 { - d.baseURL = fmt.Sprintf("%s/v2", endpoints[0].URL) - } else { - return fmt.Errorf("unable to get dns endpoint") - } - - return nil -} - -func (d *DNSProvider) getZoneID(zone string) (string, error) { - resource := fmt.Sprintf("zones?name=%s", zone) - resp, err := d.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - var zonesRes zonesResponse - err = json.NewDecoder(resp).Decode(&zonesRes) - if err != nil { - return "", err - } - - if len(zonesRes.Zones) < 1 { - return "", fmt.Errorf("zone %s not found", zone) - } - - if len(zonesRes.Zones) > 1 { - return "", fmt.Errorf("to many zones found") - } - - if zonesRes.Zones[0].ID == "" { - return "", fmt.Errorf("id not found") - } - - return zonesRes.Zones[0].ID, nil -} - -func (d *DNSProvider) getRecordSetID(zoneID string, fqdn string) (string, error) { - resource := fmt.Sprintf("zones/%s/recordsets?type=TXT&name=%s", zoneID, fqdn) - resp, err := d.sendRequest(http.MethodGet, resource, nil) - if err != nil { - return "", err - } - - var recordSetsRes recordSetsResponse - err = json.NewDecoder(resp).Decode(&recordSetsRes) - if err != nil { - return "", err - } - - if len(recordSetsRes.RecordSets) < 1 { - return "", fmt.Errorf("record not found") - } - - if len(recordSetsRes.RecordSets) > 1 { - return "", fmt.Errorf("to many records found") - } - - if recordSetsRes.RecordSets[0].ID == "" { - return "", fmt.Errorf("id not found") - } - - return recordSetsRes.RecordSets[0].ID, nil -} - -func (d *DNSProvider) deleteRecordSet(zoneID, recordID string) error { - resource := fmt.Sprintf("zones/%s/recordsets/%s", zoneID, recordID) - - _, err := d.sendRequest(http.MethodDelete, resource, nil) - return err -} - -func (d *DNSProvider) sendRequest(method, resource string, payload interface{}) (io.Reader, error) { - url := fmt.Sprintf("%s/%s", d.baseURL, resource) - - body, err := json.Marshal(payload) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, url, bytes.NewReader(body)) - if err != nil { - return nil, err - } - req.Header.Set("Content-Type", "application/json") - if len(d.token) > 0 { - req.Header.Set("X-Auth-Token", d.token) - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - - if resp.StatusCode >= 400 { - return nil, fmt.Errorf("OTC API request %s failed with HTTP status code %d", url, resp.StatusCode) - } - - body1, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return bytes.NewReader(body1), nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go b/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go deleted file mode 100644 index 94eb6c227..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/otc/otc.go +++ /dev/null @@ -1,179 +0,0 @@ -// Package otc implements a DNS provider for solving the DNS-01 challenge using Open Telekom Cloud Managed DNS. -package otc - -import ( - "errors" - "fmt" - "net" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -const defaultIdentityEndpoint = "https://iam.eu-de.otc.t-systems.com:443/v3/auth/tokens" - -// minTTL 300 is otc minimum value for ttl -const minTTL = 300 - -// Config is used to configure the creation of the DNSProvider -type Config struct { - IdentityEndpoint string - DomainName string - ProjectName string - UserName string - Password string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - IdentityEndpoint: env.GetOrDefaultString("OTC_IDENTITY_ENDPOINT", defaultIdentityEndpoint), - PropagationTimeout: env.GetOrDefaultSecond("OTC_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OTC_POLLING_INTERVAL", dns01.DefaultPollingInterval), - TTL: env.GetOrDefaultInt("OTC_TTL", minTTL), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OTC_HTTP_TIMEOUT", 10*time.Second), - Transport: &http.Transport{ - Proxy: http.ProxyFromEnvironment, - DialContext: (&net.Dialer{ - Timeout: 30 * time.Second, - KeepAlive: 30 * time.Second, - DualStack: true, - }).DialContext, - MaxIdleConns: 100, - IdleConnTimeout: 90 * time.Second, - TLSHandshakeTimeout: 10 * time.Second, - ExpectContinueTimeout: 1 * time.Second, - - // Workaround for keep alive bug in otc api - DisableKeepAlives: true, - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that uses -// OTC's Managed DNS API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - baseURL string - token string -} - -// NewDNSProvider returns a DNSProvider instance configured for OTC DNS. -// Credentials must be passed in the environment variables: OTC_USER_NAME, -// OTC_DOMAIN_NAME, OTC_PASSWORD OTC_PROJECT_NAME and OTC_IDENTITY_ENDPOINT. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("OTC_DOMAIN_NAME", "OTC_USER_NAME", "OTC_PASSWORD", "OTC_PROJECT_NAME") - if err != nil { - return nil, fmt.Errorf("otc: %v", err) - } - - config := NewDefaultConfig() - config.DomainName = values["OTC_DOMAIN_NAME"] - config.UserName = values["OTC_USER_NAME"] - config.Password = values["OTC_PASSWORD"] - config.ProjectName = values["OTC_PROJECT_NAME"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OTC DNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("otc: the configuration of the DNS provider is nil") - } - - if config.DomainName == "" || config.UserName == "" || config.Password == "" || config.ProjectName == "" { - return nil, fmt.Errorf("otc: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("otc: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - if config.IdentityEndpoint == "" { - config.IdentityEndpoint = defaultIdentityEndpoint - } - - return &DNSProvider{config: config}, nil -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("otc: unable to get zone: %s", err) - } - - resource := fmt.Sprintf("zones/%s/recordsets", zoneID) - - r1 := &recordset{ - Name: fqdn, - Description: "Added TXT record for ACME dns-01 challenge using lego client", - Type: "TXT", - TTL: d.config.TTL, - Records: []string{fmt.Sprintf("\"%s\"", value)}, - } - - _, err = d.sendRequest(http.MethodPost, resource, r1) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - err = d.login() - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - zoneID, err := d.getZoneID(authZone) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - - recordID, err := d.getRecordSetID(zoneID, fqdn) - if err != nil { - return fmt.Errorf("otc: unable go get record %s for zone %s: %s", fqdn, domain, err) - } - - err = d.deleteRecordSet(zoneID, recordID) - if err != nil { - return fmt.Errorf("otc: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go b/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go deleted file mode 100644 index dae9e1e7c..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/ovh/ovh.go +++ /dev/null @@ -1,203 +0,0 @@ -// Package ovh implements a DNS provider for solving the DNS-01 challenge using OVH DNS. -package ovh - -import ( - "errors" - "fmt" - "net/http" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/ovh/go-ovh/ovh" -) - -// OVH API reference: https://eu.api.ovh.com/ -// Create a Token: https://eu.api.ovh.com/createToken/ - -// Record a DNS record -type Record struct { - ID int `json:"id,omitempty"` - FieldType string `json:"fieldType,omitempty"` - SubDomain string `json:"subDomain,omitempty"` - Target string `json:"target,omitempty"` - TTL int `json:"ttl,omitempty"` - Zone string `json:"zone,omitempty"` -} - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIEndpoint string - ApplicationKey string - ApplicationSecret string - ConsumerKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("OVH_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("OVH_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("OVH_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("OVH_HTTP_TIMEOUT", ovh.DefaultTimeout), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// that uses OVH's REST API to manage TXT records for a domain. -type DNSProvider struct { - config *Config - client *ovh.Client - recordIDs map[string]int - recordIDsMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for OVH -// Credentials must be passed in the environment variable: -// OVH_ENDPOINT : it must be ovh-eu or ovh-ca -// OVH_APPLICATION_KEY -// OVH_APPLICATION_SECRET -// OVH_CONSUMER_KEY -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("OVH_ENDPOINT", "OVH_APPLICATION_KEY", "OVH_APPLICATION_SECRET", "OVH_CONSUMER_KEY") - if err != nil { - return nil, fmt.Errorf("ovh: %v", err) - } - - config := NewDefaultConfig() - config.APIEndpoint = values["OVH_ENDPOINT"] - config.ApplicationKey = values["OVH_APPLICATION_KEY"] - config.ApplicationSecret = values["OVH_APPLICATION_SECRET"] - config.ConsumerKey = values["OVH_CONSUMER_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for OVH. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("ovh: the configuration of the DNS provider is nil") - } - - if config.APIEndpoint == "" || config.ApplicationKey == "" || config.ApplicationSecret == "" || config.ConsumerKey == "" { - return nil, fmt.Errorf("ovh: credentials missing") - } - - client, err := ovh.NewClient( - config.APIEndpoint, - config.ApplicationKey, - config.ApplicationSecret, - config.ConsumerKey, - ) - if err != nil { - return nil, fmt.Errorf("ovh: %v", err) - } - - client.Client = config.HTTPClient - - return &DNSProvider{ - config: config, - client: client, - recordIDs: make(map[string]int), - }, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - // Parse domain name - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("ovh: could not determine zone for domain: '%s'. %s", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - subDomain := d.extractRecordName(fqdn, authZone) - - reqURL := fmt.Sprintf("/domain/zone/%s/record", authZone) - reqData := Record{FieldType: "TXT", SubDomain: subDomain, Target: value, TTL: d.config.TTL} - - // Create TXT record - var respData Record - err = d.client.Post(reqURL, reqData, &respData) - if err != nil { - return fmt.Errorf("ovh: error when call api to add record (%s): %v", reqURL, err) - } - - // Apply the change - reqURL = fmt.Sprintf("/domain/zone/%s/refresh", authZone) - err = d.client.Post(reqURL, nil, nil) - if err != nil { - return fmt.Errorf("ovh: error when call api to refresh zone (%s): %v", reqURL, err) - } - - d.recordIDsMu.Lock() - d.recordIDs[fqdn] = respData.ID - d.recordIDsMu.Unlock() - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - // get the record's unique ID from when we created it - d.recordIDsMu.Lock() - recordID, ok := d.recordIDs[fqdn] - d.recordIDsMu.Unlock() - if !ok { - return fmt.Errorf("ovh: unknown record ID for '%s'", fqdn) - } - - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return fmt.Errorf("ovh: could not determine zone for domain: '%s'. %s", domain, err) - } - - authZone = dns01.UnFqdn(authZone) - - reqURL := fmt.Sprintf("/domain/zone/%s/record/%d", authZone, recordID) - - err = d.client.Delete(reqURL, nil) - if err != nil { - return fmt.Errorf("ovh: error when call OVH api to delete challenge record (%s): %v", reqURL, err) - } - - // Apply the change - reqURL = fmt.Sprintf("/domain/zone/%s/refresh", authZone) - err = d.client.Post(reqURL, nil, nil) - if err != nil { - return fmt.Errorf("ovh: error when call api to refresh zone (%s): %v", reqURL, err) - } - - // Delete record ID from map - d.recordIDsMu.Lock() - delete(d.recordIDs, fqdn) - d.recordIDsMu.Unlock() - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go b/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go deleted file mode 100644 index c66181eff..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/client.go +++ /dev/null @@ -1,220 +0,0 @@ -package pdns - -import ( - "encoding/json" - "fmt" - "io" - "net/http" - "strconv" - "strings" - - "github.com/go-acme/lego/challenge/dns01" -) - -type Record struct { - Content string `json:"content"` - Disabled bool `json:"disabled"` - - // pre-v1 API - Name string `json:"name"` - Type string `json:"type"` - TTL int `json:"ttl,omitempty"` -} - -type hostedZone struct { - ID string `json:"id"` - Name string `json:"name"` - URL string `json:"url"` - RRSets []rrSet `json:"rrsets"` - - // pre-v1 API - Records []Record `json:"records"` -} - -type rrSet struct { - Name string `json:"name"` - Type string `json:"type"` - Kind string `json:"kind"` - ChangeType string `json:"changetype"` - Records []Record `json:"records"` - TTL int `json:"ttl,omitempty"` -} - -type rrSets struct { - RRSets []rrSet `json:"rrsets"` -} - -type apiError struct { - ShortMsg string `json:"error"` -} - -func (a apiError) Error() string { - return a.ShortMsg -} - -type apiVersion struct { - URL string `json:"url"` - Version int `json:"version"` -} - -func (d *DNSProvider) getHostedZone(fqdn string) (*hostedZone, error) { - var zone hostedZone - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return nil, err - } - - u := "/servers/localhost/zones" - result, err := d.sendRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - var zones []hostedZone - err = json.Unmarshal(result, &zones) - if err != nil { - return nil, err - } - - u = "" - for _, zone := range zones { - if dns01.UnFqdn(zone.Name) == dns01.UnFqdn(authZone) { - u = zone.URL - break - } - } - - result, err = d.sendRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - err = json.Unmarshal(result, &zone) - if err != nil { - return nil, err - } - - // convert pre-v1 API result - if len(zone.Records) > 0 { - zone.RRSets = []rrSet{} - for _, record := range zone.Records { - set := rrSet{ - Name: record.Name, - Type: record.Type, - Records: []Record{record}, - } - zone.RRSets = append(zone.RRSets, set) - } - } - - return &zone, nil -} - -func (d *DNSProvider) findTxtRecord(fqdn string) (*rrSet, error) { - zone, err := d.getHostedZone(fqdn) - if err != nil { - return nil, err - } - - _, err = d.sendRequest(http.MethodGet, zone.URL, nil) - if err != nil { - return nil, err - } - - for _, set := range zone.RRSets { - if (set.Name == dns01.UnFqdn(fqdn) || set.Name == fqdn) && set.Type == "TXT" { - return &set, nil - } - } - - return nil, nil -} - -func (d *DNSProvider) getAPIVersion() (int, error) { - result, err := d.sendRequest(http.MethodGet, "/api", nil) - if err != nil { - return 0, err - } - - var versions []apiVersion - err = json.Unmarshal(result, &versions) - if err != nil { - return 0, err - } - - latestVersion := 0 - for _, v := range versions { - if v.Version > latestVersion { - latestVersion = v.Version - } - } - - return latestVersion, err -} - -func (d *DNSProvider) sendRequest(method, uri string, body io.Reader) (json.RawMessage, error) { - req, err := d.makeRequest(method, uri, body) - if err != nil { - return nil, err - } - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error talking to PDNS API -> %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusUnprocessableEntity && (resp.StatusCode < 200 || resp.StatusCode >= 300) { - return nil, fmt.Errorf("unexpected HTTP status code %d when fetching '%s'", resp.StatusCode, req.URL) - } - - var msg json.RawMessage - err = json.NewDecoder(resp.Body).Decode(&msg) - if err != nil { - if err == io.EOF { - // empty body - return nil, nil - } - // other error - return nil, err - } - - // check for PowerDNS error message - if len(msg) > 0 && msg[0] == '{' { - var errInfo apiError - err = json.Unmarshal(msg, &errInfo) - if err != nil { - return nil, err - } - if errInfo.ShortMsg != "" { - return nil, fmt.Errorf("error talking to PDNS API -> %v", errInfo) - } - } - return msg, nil -} - -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (*http.Request, error) { - var path = "" - if d.config.Host.Path != "/" { - path = d.config.Host.Path - } - - if !strings.HasPrefix(uri, "/") { - uri = "/" + uri - } - - if d.apiVersion > 0 && !strings.HasPrefix(uri, "/api/v") { - uri = "/api/v" + strconv.Itoa(d.apiVersion) + uri - } - - u := d.config.Host.Scheme + "://" + d.config.Host.Host + path + uri - req, err := http.NewRequest(method, u, body) - if err != nil { - return nil, err - } - - req.Header.Set("X-API-Key", d.config.APIKey) - - return req, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go b/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go deleted file mode 100644 index 87adedb2a..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/pdns/pdns.go +++ /dev/null @@ -1,198 +0,0 @@ -// Package pdns implements a DNS provider for solving the DNS-01 challenge using PowerDNS nameserver. -package pdns - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - Host *url.URL - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("PDNS_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("PDNS_PROPAGATION_TIMEOUT", 120*time.Second), - PollingInterval: env.GetOrDefaultSecond("PDNS_POLLING_INTERVAL", 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("PDNS_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -type DNSProvider struct { - apiVersion int - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for pdns. -// Credentials must be passed in the environment variable: -// PDNS_API_URL and PDNS_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("PDNS_API_KEY", "PDNS_API_URL") - if err != nil { - return nil, fmt.Errorf("pdns: %v", err) - } - - hostURL, err := url.Parse(values["PDNS_API_URL"]) - if err != nil { - return nil, fmt.Errorf("pdns: %v", err) - } - - config := NewDefaultConfig() - config.Host = hostURL - config.APIKey = values["PDNS_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for pdns. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("pdns: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("pdns: API key missing") - } - - if config.Host == nil || config.Host.Host == "" { - return nil, fmt.Errorf("pdns: API URL missing") - } - - d := &DNSProvider{config: config} - - apiVersion, err := d.getAPIVersion() - if err != nil { - log.Warnf("pdns: failed to get API version %v", err) - } - d.apiVersion = apiVersion - - return d, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - name := fqdn - - // pre-v1 API wants non-fqdn - if d.apiVersion == 0 { - name = dns01.UnFqdn(fqdn) - } - - rec := Record{ - Content: "\"" + value + "\"", - Disabled: false, - - // pre-v1 API - Type: "TXT", - Name: name, - TTL: d.config.TTL, - } - - // Look for existing records. - existingRrSet, err := d.findTxtRecord(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - // merge the existing and new records - var records []Record - if existingRrSet != nil { - records = existingRrSet.Records - } - records = append(records, rec) - - rrsets := rrSets{ - RRSets: []rrSet{ - { - Name: name, - ChangeType: "REPLACE", - Type: "TXT", - Kind: "Master", - TTL: d.config.TTL, - Records: records, - }, - }, - } - - body, err := json.Marshal(rrsets) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - _, err = d.sendRequest(http.MethodPatch, zone.URL, bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zone, err := d.getHostedZone(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - set, err := d.findTxtRecord(fqdn) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - if set == nil { - return fmt.Errorf("pdns: no existing record found for %s", fqdn) - } - - rrsets := rrSets{ - RRSets: []rrSet{ - { - Name: set.Name, - Type: set.Type, - ChangeType: "DELETE", - }, - }, - } - body, err := json.Marshal(rrsets) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - - _, err = d.sendRequest(http.MethodPatch, zone.URL, bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("pdns: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go deleted file mode 100644 index ce9b2de93..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/client.go +++ /dev/null @@ -1,205 +0,0 @@ -package rackspace - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - - "github.com/go-acme/lego/challenge/dns01" -) - -// APIKeyCredentials API credential -type APIKeyCredentials struct { - Username string `json:"username"` - APIKey string `json:"apiKey"` -} - -// Auth auth credentials -type Auth struct { - APIKeyCredentials `json:"RAX-KSKEY:apiKeyCredentials"` -} - -// AuthData Auth data -type AuthData struct { - Auth `json:"auth"` -} - -// Identity Identity -type Identity struct { - Access Access `json:"access"` -} - -// Access Access -type Access struct { - ServiceCatalog []ServiceCatalog `json:"serviceCatalog"` - Token Token `json:"token"` -} - -// Token Token -type Token struct { - ID string `json:"id"` -} - -// ServiceCatalog ServiceCatalog -type ServiceCatalog struct { - Endpoints []Endpoint `json:"endpoints"` - Name string `json:"name"` -} - -// Endpoint Endpoint -type Endpoint struct { - PublicURL string `json:"publicURL"` - TenantID string `json:"tenantId"` -} - -// ZoneSearchResponse represents the response when querying Rackspace DNS zones -type ZoneSearchResponse struct { - TotalEntries int `json:"totalEntries"` - HostedZones []HostedZone `json:"domains"` -} - -// HostedZone HostedZone -type HostedZone struct { - ID int `json:"id"` - Name string `json:"name"` -} - -// Records is the list of records sent/received from the DNS API -type Records struct { - Record []Record `json:"records"` -} - -// Record represents a Rackspace DNS record -type Record struct { - Name string `json:"name"` - Type string `json:"type"` - Data string `json:"data"` - TTL int `json:"ttl,omitempty"` - ID string `json:"id,omitempty"` -} - -// getHostedZoneID performs a lookup to get the DNS zone which needs -// modifying for a given FQDN -func (d *DNSProvider) getHostedZoneID(fqdn string) (int, error) { - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return 0, err - } - - result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains?name=%s", dns01.UnFqdn(authZone)), nil) - if err != nil { - return 0, err - } - - var zoneSearchResponse ZoneSearchResponse - err = json.Unmarshal(result, &zoneSearchResponse) - if err != nil { - return 0, err - } - - // If nothing was returned, or for whatever reason more than 1 was returned (the search uses exact match, so should not occur) - if zoneSearchResponse.TotalEntries != 1 { - return 0, fmt.Errorf("found %d zones for %s in Rackspace for domain %s", zoneSearchResponse.TotalEntries, authZone, fqdn) - } - - return zoneSearchResponse.HostedZones[0].ID, nil -} - -// findTxtRecord searches a DNS zone for a TXT record with a specific name -func (d *DNSProvider) findTxtRecord(fqdn string, zoneID int) (*Record, error) { - result, err := d.makeRequest(http.MethodGet, fmt.Sprintf("/domains/%d/records?type=TXT&name=%s", zoneID, dns01.UnFqdn(fqdn)), nil) - if err != nil { - return nil, err - } - - var records Records - err = json.Unmarshal(result, &records) - if err != nil { - return nil, err - } - - switch len(records.Record) { - case 1: - case 0: - return nil, fmt.Errorf("no TXT record found for %s", fqdn) - default: - return nil, fmt.Errorf("more than 1 TXT record found for %s", fqdn) - } - - return &records.Record[0], nil -} - -// makeRequest is a wrapper function used for making DNS API requests -func (d *DNSProvider) makeRequest(method, uri string, body io.Reader) (json.RawMessage, error) { - url := d.cloudDNSEndpoint + uri - - req, err := http.NewRequest(method, url, body) - if err != nil { - return nil, err - } - - req.Header.Set("X-Auth-Token", d.token) - req.Header.Set("Content-Type", "application/json") - - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying DNS API: %v", err) - } - - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusAccepted { - return nil, fmt.Errorf("request failed for %s %s. Response code: %d", method, url, resp.StatusCode) - } - - var r json.RawMessage - err = json.NewDecoder(resp.Body).Decode(&r) - if err != nil { - return nil, fmt.Errorf("JSON decode failed for %s %s. Response code: %d", method, url, resp.StatusCode) - } - - return r, nil -} - -func login(config *Config) (*Identity, error) { - authData := AuthData{ - Auth: Auth{ - APIKeyCredentials: APIKeyCredentials{ - Username: config.APIUser, - APIKey: config.APIKey, - }, - }, - } - - body, err := json.Marshal(authData) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(http.MethodPost, config.BaseURL, bytes.NewReader(body)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - resp, err := config.HTTPClient.Do(req) - if err != nil { - return nil, fmt.Errorf("error querying Identity API: %v", err) - } - defer resp.Body.Close() - - if resp.StatusCode != http.StatusOK { - return nil, fmt.Errorf("authentication failed: response code: %d", resp.StatusCode) - } - - var identity Identity - err = json.NewDecoder(resp.Body).Decode(&identity) - if err != nil { - return nil, err - } - - return &identity, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go b/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go deleted file mode 100644 index 91b5a56ae..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rackspace/rackspace.go +++ /dev/null @@ -1,159 +0,0 @@ -// Package rackspace implements a DNS provider for solving the DNS-01 challenge using rackspace DNS. -package rackspace - -import ( - "bytes" - "encoding/json" - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// defaultBaseURL represents the Identity API endpoint to call -const defaultBaseURL = "https://identity.api.rackspacecloud.com/v2.0/tokens" - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIUser string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: defaultBaseURL, - TTL: env.GetOrDefaultInt("RACKSPACE_TTL", 300), - PropagationTimeout: env.GetOrDefaultSecond("RACKSPACE_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("RACKSPACE_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("RACKSPACE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface -// used to store the reusable token and DNS API endpoint -type DNSProvider struct { - config *Config - token string - cloudDNSEndpoint string -} - -// NewDNSProvider returns a DNSProvider instance configured for Rackspace. -// Credentials must be passed in the environment variables: -// RACKSPACE_USER and RACKSPACE_API_KEY. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("RACKSPACE_USER", "RACKSPACE_API_KEY") - if err != nil { - return nil, fmt.Errorf("rackspace: %v", err) - } - - config := NewDefaultConfig() - config.APIUser = values["RACKSPACE_USER"] - config.APIKey = values["RACKSPACE_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Rackspace. -// It authenticates against the API, also grabbing the DNS Endpoint. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("rackspace: the configuration of the DNS provider is nil") - } - - if config.APIUser == "" || config.APIKey == "" { - return nil, fmt.Errorf("rackspace: credentials missing") - } - - identity, err := login(config) - if err != nil { - return nil, fmt.Errorf("rackspace: %v", err) - } - - // Iterate through the Service Catalog to get the DNS Endpoint - var dnsEndpoint string - for _, service := range identity.Access.ServiceCatalog { - if service.Name == "cloudDNS" { - dnsEndpoint = service.Endpoints[0].PublicURL - break - } - } - - if dnsEndpoint == "" { - return nil, fmt.Errorf("rackspace: failed to populate DNS endpoint, check Rackspace API for changes") - } - - return &DNSProvider{ - config: config, - token: identity.Access.Token.ID, - cloudDNSEndpoint: dnsEndpoint, - }, nil - -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - rec := Records{ - Record: []Record{{ - Name: dns01.UnFqdn(fqdn), - Type: "TXT", - Data: value, - TTL: d.config.TTL, - }}, - } - - body, err := json.Marshal(rec) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - _, err = d.makeRequest(http.MethodPost, fmt.Sprintf("/domains/%d/records", zoneID), bytes.NewReader(body)) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - record, err := d.findTxtRecord(fqdn, zoneID) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - - _, err = d.makeRequest(http.MethodDelete, fmt.Sprintf("/domains/%d/records?id=%s", zoneID, record.ID), nil) - if err != nil { - return fmt.Errorf("rackspace: %v", err) - } - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go b/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go deleted file mode 100644 index 75e3d55f9..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/rfc2136/rfc2136.go +++ /dev/null @@ -1,183 +0,0 @@ -// Package rfc2136 implements a DNS provider for solving the DNS-01 challenge using the rfc2136 dynamic update. -package rfc2136 - -import ( - "errors" - "fmt" - "net" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/miekg/dns" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Nameserver string - TSIGAlgorithm string - TSIGKey string - TSIGSecret string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - SequenceInterval time.Duration - DNSTimeout time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TSIGAlgorithm: env.GetOrDefaultString("RFC2136_TSIG_ALGORITHM", dns.HmacMD5), - TTL: env.GetOrDefaultInt("RFC2136_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("RFC2136_PROPAGATION_TIMEOUT", env.GetOrDefaultSecond("RFC2136_TIMEOUT", 60*time.Second)), - PollingInterval: env.GetOrDefaultSecond("RFC2136_POLLING_INTERVAL", 2*time.Second), - SequenceInterval: env.GetOrDefaultSecond("RFC2136_SEQUENCE_INTERVAL", dns01.DefaultPropagationTimeout), - DNSTimeout: env.GetOrDefaultSecond("RFC2136_DNS_TIMEOUT", 10*time.Second), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface that -// uses dynamic DNS updates (RFC 2136) to create TXT records on a nameserver. -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for rfc2136 -// dynamic update. Configured with environment variables: -// RFC2136_NAMESERVER: Network address in the form "host" or "host:port". -// RFC2136_TSIG_ALGORITHM: Defaults to hmac-md5.sig-alg.reg.int. (HMAC-MD5). -// See https://github.com/miekg/dns/blob/master/tsig.go for supported values. -// RFC2136_TSIG_KEY: Name of the secret key as defined in DNS server configuration. -// RFC2136_TSIG_SECRET: Secret key payload. -// RFC2136_PROPAGATION_TIMEOUT: DNS propagation timeout in time.ParseDuration format. (60s) -// To disable TSIG authentication, leave the RFC2136_TSIG* variables unset. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("RFC2136_NAMESERVER") - if err != nil { - return nil, fmt.Errorf("rfc2136: %v", err) - } - - config := NewDefaultConfig() - config.Nameserver = values["RFC2136_NAMESERVER"] - config.TSIGKey = env.GetOrFile("RFC2136_TSIG_KEY") - config.TSIGSecret = env.GetOrFile("RFC2136_TSIG_SECRET") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for rfc2136. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("rfc2136: the configuration of the DNS provider is nil") - } - - if config.Nameserver == "" { - return nil, fmt.Errorf("rfc2136: nameserver missing") - } - - if config.TSIGAlgorithm == "" { - config.TSIGAlgorithm = dns.HmacMD5 - } - - // Append the default DNS port if none is specified. - if _, _, err := net.SplitHostPort(config.Nameserver); err != nil { - if strings.Contains(err.Error(), "missing port") { - config.Nameserver = net.JoinHostPort(config.Nameserver, "53") - } else { - return nil, fmt.Errorf("rfc2136: %v", err) - } - } - - if len(config.TSIGKey) == 0 && len(config.TSIGSecret) > 0 || - len(config.TSIGKey) > 0 && len(config.TSIGSecret) == 0 { - config.TSIGKey = "" - config.TSIGSecret = "" - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Sequential All DNS challenges for this provider will be resolved sequentially. -// Returns the interval between each iteration. -func (d *DNSProvider) Sequential() time.Duration { - return d.config.SequenceInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("INSERT", fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("rfc2136: failed to insert: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - err := d.changeRecord("REMOVE", fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("rfc2136: failed to remove: %v", err) - } - return nil -} - -func (d *DNSProvider) changeRecord(action, fqdn, value string, ttl int) error { - // Find the zone for the given fqdn - zone, err := dns01.FindZoneByFqdnCustom(fqdn, []string{d.config.Nameserver}) - if err != nil { - return err - } - - // Create RR - rr := new(dns.TXT) - rr.Hdr = dns.RR_Header{Name: fqdn, Rrtype: dns.TypeTXT, Class: dns.ClassINET, Ttl: uint32(ttl)} - rr.Txt = []string{value} - rrs := []dns.RR{rr} - - // Create dynamic update packet - m := new(dns.Msg) - m.SetUpdate(zone) - switch action { - case "INSERT": - // Always remove old challenge left over from who knows what. - m.RemoveRRset(rrs) - m.Insert(rrs) - case "REMOVE": - m.Remove(rrs) - default: - return fmt.Errorf("unexpected action: %s", action) - } - - // Setup client - c := &dns.Client{Timeout: d.config.DNSTimeout} - c.SingleInflight = true - - // TSIG authentication / msg signing - if len(d.config.TSIGKey) > 0 && len(d.config.TSIGSecret) > 0 { - m.SetTsig(dns.Fqdn(d.config.TSIGKey), d.config.TSIGAlgorithm, 300, time.Now().Unix()) - c.TsigSecret = map[string]string{dns.Fqdn(d.config.TSIGKey): d.config.TSIGSecret} - } - - // Send the query - reply, _, err := c.Exchange(m, d.config.Nameserver) - if err != nil { - return fmt.Errorf("DNS update failed: %v", err) - } - if reply != nil && reply.Rcode != dns.RcodeSuccess { - return fmt.Errorf("DNS update failed: server replied: %s", dns.RcodeToString[reply.Rcode]) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go b/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go deleted file mode 100644 index 6d06de7fc..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/route53/route53.go +++ /dev/null @@ -1,279 +0,0 @@ -// Package route53 implements a DNS provider for solving the DNS-01 challenge using AWS Route 53 DNS. -package route53 - -import ( - "errors" - "fmt" - "math/rand" - "strings" - "time" - - "github.com/aws/aws-sdk-go/aws" - "github.com/aws/aws-sdk-go/aws/client" - "github.com/aws/aws-sdk-go/aws/request" - "github.com/aws/aws-sdk-go/aws/session" - "github.com/aws/aws-sdk-go/service/route53" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/platform/wait" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - MaxRetries int - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration - HostedZoneID string -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - MaxRetries: env.GetOrDefaultInt("AWS_MAX_RETRIES", 5), - TTL: env.GetOrDefaultInt("AWS_TTL", 10), - PropagationTimeout: env.GetOrDefaultSecond("AWS_PROPAGATION_TIMEOUT", 2*time.Minute), - PollingInterval: env.GetOrDefaultSecond("AWS_POLLING_INTERVAL", 4*time.Second), - HostedZoneID: env.GetOrFile("AWS_HOSTED_ZONE_ID"), - } -} - -// DNSProvider implements the acme.ChallengeProvider interface -type DNSProvider struct { - client *route53.Route53 - config *Config -} - -// customRetryer implements the client.Retryer interface by composing the DefaultRetryer. -// It controls the logic for retrying recoverable request errors (e.g. when rate limits are exceeded). -type customRetryer struct { - client.DefaultRetryer -} - -// RetryRules overwrites the DefaultRetryer's method. -// It uses a basic exponential backoff algorithm: -// that returns an initial delay of ~400ms with an upper limit of ~30 seconds, -// which should prevent causing a high number of consecutive throttling errors. -// For reference: Route 53 enforces an account-wide(!) 5req/s query limit. -func (d customRetryer) RetryRules(r *request.Request) time.Duration { - retryCount := r.RetryCount - if retryCount > 7 { - retryCount = 7 - } - - delay := (1 << uint(retryCount)) * (rand.Intn(50) + 200) - return time.Duration(delay) * time.Millisecond -} - -// NewDNSProvider returns a DNSProvider instance configured for the AWS Route 53 service. -// -// AWS Credentials are automatically detected in the following locations and prioritized in the following order: -// 1. Environment variables: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, -// AWS_REGION, [AWS_SESSION_TOKEN] -// 2. Shared credentials file (defaults to ~/.aws/credentials) -// 3. Amazon EC2 IAM role -// -// If AWS_HOSTED_ZONE_ID is not set, Lego tries to determine the correct public hosted zone via the FQDN. -// -// See also: https://github.com/aws/aws-sdk-go/wiki/configuring-sdk -func NewDNSProvider() (*DNSProvider, error) { - return NewDNSProviderConfig(NewDefaultConfig()) -} - -// NewDNSProviderConfig takes a given config ans returns a custom configured DNSProvider instance -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("route53: the configuration of the Route53 DNS provider is nil") - } - - retry := customRetryer{} - retry.NumMaxRetries = config.MaxRetries - sessionCfg := request.WithRetryer(aws.NewConfig(), retry) - - sess, err := session.NewSessionWithOptions(session.Options{Config: *sessionCfg}) - if err != nil { - return nil, err - } - - cl := route53.New(sess) - return &DNSProvider{client: cl, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS -// propagation. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record using the specified parameters -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - hostedZoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("route53: failed to determine hosted zone ID: %v", err) - } - - records, err := d.getExistingRecordSets(hostedZoneID, fqdn) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - - realValue := `"` + value + `"` - - var found bool - for _, record := range records { - if aws.StringValue(record.Value) == realValue { - found = true - } - } - - if !found { - records = append(records, &route53.ResourceRecord{Value: aws.String(realValue)}) - } - - recordSet := &route53.ResourceRecordSet{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - TTL: aws.Int64(int64(d.config.TTL)), - ResourceRecords: records, - } - - err = d.changeRecord(route53.ChangeActionUpsert, hostedZoneID, recordSet) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - hostedZoneID, err := d.getHostedZoneID(fqdn) - if err != nil { - return fmt.Errorf("failed to determine Route 53 hosted zone ID: %v", err) - } - - records, err := d.getExistingRecordSets(hostedZoneID, fqdn) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - - if len(records) == 0 { - return nil - } - - recordSet := &route53.ResourceRecordSet{ - Name: aws.String(fqdn), - Type: aws.String("TXT"), - TTL: aws.Int64(int64(d.config.TTL)), - ResourceRecords: records, - } - - err = d.changeRecord(route53.ChangeActionDelete, hostedZoneID, recordSet) - if err != nil { - return fmt.Errorf("route53: %v", err) - } - return nil -} - -func (d *DNSProvider) changeRecord(action, hostedZoneID string, recordSet *route53.ResourceRecordSet) error { - recordSetInput := &route53.ChangeResourceRecordSetsInput{ - HostedZoneId: aws.String(hostedZoneID), - ChangeBatch: &route53.ChangeBatch{ - Comment: aws.String("Managed by Lego"), - Changes: []*route53.Change{{ - Action: aws.String(action), - ResourceRecordSet: recordSet, - }}, - }, - } - - resp, err := d.client.ChangeResourceRecordSets(recordSetInput) - if err != nil { - return fmt.Errorf("failed to change record set: %v", err) - } - - changeID := resp.ChangeInfo.Id - - return wait.For("route53", d.config.PropagationTimeout, d.config.PollingInterval, func() (bool, error) { - reqParams := &route53.GetChangeInput{Id: changeID} - - resp, err := d.client.GetChange(reqParams) - if err != nil { - return false, fmt.Errorf("failed to query change status: %v", err) - } - - if aws.StringValue(resp.ChangeInfo.Status) == route53.ChangeStatusInsync { - return true, nil - } - return false, fmt.Errorf("unable to retrieve change: ID=%s", aws.StringValue(changeID)) - }) -} - -func (d *DNSProvider) getExistingRecordSets(hostedZoneID string, fqdn string) ([]*route53.ResourceRecord, error) { - listInput := &route53.ListResourceRecordSetsInput{ - HostedZoneId: aws.String(hostedZoneID), - StartRecordName: aws.String(fqdn), - StartRecordType: aws.String("TXT"), - } - - recordSetsOutput, err := d.client.ListResourceRecordSets(listInput) - if err != nil { - return nil, err - } - - if recordSetsOutput == nil { - return nil, nil - } - - var records []*route53.ResourceRecord - - for _, recordSet := range recordSetsOutput.ResourceRecordSets { - if aws.StringValue(recordSet.Name) == fqdn { - records = append(records, recordSet.ResourceRecords...) - } - } - - return records, nil -} - -func (d *DNSProvider) getHostedZoneID(fqdn string) (string, error) { - if d.config.HostedZoneID != "" { - return d.config.HostedZoneID, nil - } - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return "", err - } - - // .DNSName should not have a trailing dot - reqParams := &route53.ListHostedZonesByNameInput{ - DNSName: aws.String(dns01.UnFqdn(authZone)), - } - resp, err := d.client.ListHostedZonesByName(reqParams) - if err != nil { - return "", err - } - - var hostedZoneID string - for _, hostedZone := range resp.HostedZones { - // .Name has a trailing dot - if !aws.BoolValue(hostedZone.Config.PrivateZone) && aws.StringValue(hostedZone.Name) == authZone { - hostedZoneID = aws.StringValue(hostedZone.Id) - break - } - } - - if len(hostedZoneID) == 0 { - return "", fmt.Errorf("zone %s not found for domain %s", authZone, fqdn) - } - - if strings.HasPrefix(hostedZoneID, "/hostedzone/") { - hostedZoneID = strings.TrimPrefix(hostedZoneID, "/hostedzone/") - } - - return hostedZoneID, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go deleted file mode 100644 index 10b8a1f68..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/client.go +++ /dev/null @@ -1,106 +0,0 @@ -package sakuracloud - -import ( - "fmt" - "net/http" - "strings" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/sacloud/libsacloud/api" - "github.com/sacloud/libsacloud/sacloud" -) - -const sacloudAPILockKey = "lego/dns/sacloud" - -func (d *DNSProvider) addTXTRecord(fqdn, domain, value string, ttl int) error { - sacloud.LockByKey(sacloudAPILockKey) - defer sacloud.UnlockByKey(sacloudAPILockKey) - - zone, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("sakuracloud: %v", err) - } - - name := d.extractRecordName(fqdn, zone.Name) - - zone.AddRecord(zone.CreateNewRecord(name, "TXT", value, ttl)) - _, err = d.client.Update(zone.ID, zone) - if err != nil { - return fmt.Errorf("sakuracloud: API call failed: %v", err) - } - - return nil -} - -func (d *DNSProvider) cleanupTXTRecord(fqdn, domain string) error { - sacloud.LockByKey(sacloudAPILockKey) - defer sacloud.UnlockByKey(sacloudAPILockKey) - - zone, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("sakuracloud: %v", err) - } - - records := d.findTxtRecords(fqdn, zone) - - for _, record := range records { - var updRecords []sacloud.DNSRecordSet - for _, r := range zone.Settings.DNS.ResourceRecordSets { - if !(r.Name == record.Name && r.Type == record.Type && r.RData == record.RData) { - updRecords = append(updRecords, r) - } - } - zone.Settings.DNS.ResourceRecordSets = updRecords - } - - _, err = d.client.Update(zone.ID, zone) - if err != nil { - return fmt.Errorf("sakuracloud: API call failed: %v", err) - } - return nil -} - -func (d *DNSProvider) getHostedZone(domain string) (*sacloud.DNS, error) { - authZone, err := dns01.FindZoneByFqdn(dns01.ToFqdn(domain)) - if err != nil { - return nil, err - } - - zoneName := dns01.UnFqdn(authZone) - - res, err := d.client.Reset().WithNameLike(zoneName).Find() - if err != nil { - if notFound, ok := err.(api.Error); ok && notFound.ResponseCode() == http.StatusNotFound { - return nil, fmt.Errorf("zone %s not found on SakuraCloud DNS: %v", zoneName, err) - } - return nil, fmt.Errorf("API call failed: %v", err) - } - - for _, zone := range res.CommonServiceDNSItems { - if zone.Name == zoneName { - return &zone, nil - } - } - - return nil, fmt.Errorf("zone %s not found", zoneName) -} - -func (d *DNSProvider) findTxtRecords(fqdn string, zone *sacloud.DNS) []sacloud.DNSRecordSet { - recordName := d.extractRecordName(fqdn, zone.Name) - - var res []sacloud.DNSRecordSet - for _, record := range zone.Settings.DNS.ResourceRecordSets { - if record.Name == recordName && record.Type == "TXT" { - res = append(res, record) - } - } - return res -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go b/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go deleted file mode 100644 index 87f55a0e5..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/sakuracloud/sakuracloud.go +++ /dev/null @@ -1,101 +0,0 @@ -// Package sakuracloud implements a DNS provider for solving the DNS-01 challenge using SakuraCloud DNS. -package sakuracloud - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/sacloud/libsacloud/api" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Token string - Secret string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("SAKURACLOUD_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("SAKURACLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("SAKURACLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("SAKURACLOUD_HTTP_TIMEOUT", 10*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *api.DNSAPI -} - -// NewDNSProvider returns a DNSProvider instance configured for SakuraCloud. -// Credentials must be passed in the environment variables: SAKURACLOUD_ACCESS_TOKEN & SAKURACLOUD_ACCESS_TOKEN_SECRET -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("SAKURACLOUD_ACCESS_TOKEN", "SAKURACLOUD_ACCESS_TOKEN_SECRET") - if err != nil { - return nil, fmt.Errorf("sakuracloud: %v", err) - } - - config := NewDefaultConfig() - config.Token = values["SAKURACLOUD_ACCESS_TOKEN"] - config.Secret = values["SAKURACLOUD_ACCESS_TOKEN_SECRET"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for SakuraCloud. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("sakuracloud: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("sakuracloud: AccessToken is missing") - } - - if config.Secret == "" { - return nil, errors.New("sakuracloud: AccessSecret is missing") - } - - apiClient := api.NewClient(config.Token, config.Secret, "is1a") - if config.HTTPClient == nil { - apiClient.HTTPClient = http.DefaultClient - } else { - apiClient.HTTPClient = config.HTTPClient - } - - return &DNSProvider{ - client: apiClient.GetDNSAPI(), - config: config, - }, nil -} - -// Present creates a TXT record to fulfill the dns-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - return d.addTXTRecord(fqdn, domain, value, d.config.TTL) -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - return d.cleanupTXTRecord(fqdn, domain) -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go deleted file mode 100644 index 8457bc4aa..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/internal/client.go +++ /dev/null @@ -1,221 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -// Domain represents domain name. -type Domain struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` -} - -// Record represents DNS record. -type Record struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` // Record type (SOA, NS, A/AAAA, CNAME, SRV, MX, TXT, SPF) - TTL int `json:"ttl,omitempty"` - Email string `json:"email,omitempty"` // Email of domain's admin (only for SOA records) - Content string `json:"content,omitempty"` // Record content (not for SRV) -} - -// APIError API error message -type APIError struct { - Description string `json:"error"` - Code int `json:"code"` - Field string `json:"field"` -} - -func (a *APIError) Error() string { - return fmt.Sprintf("API error: %d - %s - %s", a.Code, a.Description, a.Field) -} - -// ClientOpts represents options to init client. -type ClientOpts struct { - BaseURL string - Token string - UserAgent string - HTTPClient *http.Client -} - -// Client represents DNS client. -type Client struct { - baseURL string - token string - userAgent string - httpClient *http.Client -} - -// NewClient returns a client instance. -func NewClient(opts ClientOpts) *Client { - if opts.HTTPClient == nil { - opts.HTTPClient = &http.Client{} - } - - return &Client{ - token: opts.Token, - baseURL: opts.BaseURL, - httpClient: opts.HTTPClient, - userAgent: opts.UserAgent, - } -} - -// GetDomainByName gets Domain object by its name. If `domainName` level > 2 and there is -// no such domain on the account - it'll recursively search for the first -// which is exists in Selectel Domain API. -func (c *Client) GetDomainByName(domainName string) (*Domain, error) { - uri := fmt.Sprintf("/%s", domainName) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - domain := &Domain{} - resp, err := c.do(req, domain) - if err != nil { - switch { - case resp.StatusCode == http.StatusNotFound && strings.Count(domainName, ".") > 1: - // Look up for the next sub domain - subIndex := strings.Index(domainName, ".") - return c.GetDomainByName(domainName[subIndex+1:]) - default: - return nil, err - } - } - - return domain, nil -} - -// AddRecord adds Record for given domain. -func (c *Client) AddRecord(domainID int, body Record) (*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodPost, uri, body) - if err != nil { - return nil, err - } - - record := &Record{} - _, err = c.do(req, record) - if err != nil { - return nil, err - } - - return record, nil -} - -// ListRecords returns list records for specific domain. -func (c *Client) ListRecords(domainID int) ([]*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var records []*Record - _, err = c.do(req, &records) - if err != nil { - return nil, err - } - return records, nil -} - -// DeleteRecord deletes specific record. -func (c *Client) DeleteRecord(domainID, recordID int) error { - uri := fmt.Sprintf("/%d/records/%d", domainID, recordID) - req, err := c.newRequest(http.MethodDelete, uri, nil) - if err != nil { - return err - } - - _, err = c.do(req, nil) - return err -} - -func (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) { - buf := new(bytes.Buffer) - - if body != nil { - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, fmt.Errorf("failed to encode request body with error: %v", err) - } - } - - req, err := http.NewRequest(method, c.baseURL+uri, buf) - if err != nil { - return nil, fmt.Errorf("failed to create new http request with error: %v", err) - } - - req.Header.Add("X-Token", c.token) - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - - return req, nil -} - -func (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) { - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("request failed with error: %v", err) - } - - err = checkResponse(resp) - if err != nil { - return resp, err - } - - if to != nil { - if err = unmarshalBody(resp, to); err != nil { - return resp, err - } - } - - return resp, nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest && - resp.StatusCode <= http.StatusNetworkAuthenticationRequired { - - if resp.Body == nil { - return fmt.Errorf("request failed with status code %d and empty body", resp.StatusCode) - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - apiError := APIError{} - err = json.Unmarshal(body, &apiError) - if err != nil { - return fmt.Errorf("request failed with status code %d, response body: %s", resp.StatusCode, string(body)) - } - - return fmt.Errorf("request failed with status code %d: %v", resp.StatusCode, apiError) - } - - return nil -} - -func unmarshalBody(resp *http.Response, to interface{}) error { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - err = json.Unmarshal(body, to) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go b/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go deleted file mode 100644 index 83abe257d..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/selectel/selectel.go +++ /dev/null @@ -1,154 +0,0 @@ -// Package selectel implements a DNS provider for solving the DNS-01 challenge using Selectel Domains API. -// Selectel Domain API reference: https://kb.selectel.com/23136054.html -// Token: https://my.selectel.ru/profile/apikeys -package selectel - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/go-acme/lego/providers/dns/selectel/internal" -) - -const ( - defaultBaseURL = "https://api.selectel.ru/domains/v1" - minTTL = 60 -) - -const ( - envNamespace = "SELECTEL_" - baseURLEnvVar = envNamespace + "BASE_URL" - apiTokenEnvVar = envNamespace + "API_TOKEN" - ttlEnvVar = envNamespace + "TTL" - propagationTimeoutEnvVar = envNamespace + "PROPAGATION_TIMEOUT" - pollingIntervalEnvVar = envNamespace + "POLLING_INTERVAL" - httpTimeoutEnvVar = envNamespace + "HTTP_TIMEOUT" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - BaseURL string - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider. -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: env.GetOrDefaultString(baseURLEnvVar, defaultBaseURL), - TTL: env.GetOrDefaultInt(ttlEnvVar, minTTL), - PropagationTimeout: env.GetOrDefaultSecond(propagationTimeoutEnvVar, 120*time.Second), - PollingInterval: env.GetOrDefaultSecond(pollingIntervalEnvVar, 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond(httpTimeoutEnvVar, 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Selectel Domains API. -// API token must be passed in the environment variable SELECTEL_API_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiTokenEnvVar) - if err != nil { - return nil, fmt.Errorf("selectel: %v", err) - } - - config := NewDefaultConfig() - config.Token = values[apiTokenEnvVar] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for selectel. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("selectel: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("selectel: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("selectel: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := internal.NewClient(internal.ClientOpts{ - BaseURL: config.BaseURL, - Token: config.Token, - HTTPClient: config.HTTPClient, - }) - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the Timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - txtRecord := internal.Record{ - Type: "TXT", - TTL: d.config.TTL, - Name: fqdn, - Content: value, - } - _, err = d.client.AddRecord(domainObj.ID, txtRecord) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - return nil -} - -// CleanUp removes a TXT record used for DNS-01 challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - recordName := dns01.UnFqdn(fqdn) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - records, err := d.client.ListRecords(domainObj.ID) - if err != nil { - return fmt.Errorf("selectel: %v", err) - } - - // Delete records with specific FQDN - var lastErr error - for _, record := range records { - if record.Name == recordName { - err = d.client.DeleteRecord(domainObj.ID, record.ID) - if err != nil { - lastErr = fmt.Errorf("selectel: %v", err) - } - } - } - - return lastErr -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go b/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go deleted file mode 100644 index 141c4f41d..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/client.go +++ /dev/null @@ -1,217 +0,0 @@ -package stackpath - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "path" - - "github.com/go-acme/lego/challenge/dns01" - "golang.org/x/net/publicsuffix" -) - -// Zones is the response struct from the Stackpath api GetZones -type Zones struct { - Zones []Zone `json:"zones"` -} - -// Zone a DNS zone representation -type Zone struct { - ID string - Domain string -} - -// Records is the response struct from the Stackpath api GetZoneRecords -type Records struct { - Records []Record `json:"records"` -} - -// Record a DNS record representation -type Record struct { - ID string `json:"id,omitempty"` - Name string `json:"name"` - Type string `json:"type"` - TTL int `json:"ttl"` - Data string `json:"data"` -} - -// ErrorResponse the API error response representation -type ErrorResponse struct { - Code int `json:"code"` - Message string `json:"error"` -} - -func (e *ErrorResponse) Error() string { - return fmt.Sprintf("%d %s", e.Code, e.Message) -} - -// https://developer.stackpath.com/en/api/dns/#operation/GetZones -func (d *DNSProvider) getZones(domain string) (*Zone, error) { - domain = dns01.UnFqdn(domain) - tld, err := publicsuffix.EffectiveTLDPlusOne(domain) - if err != nil { - return nil, err - } - - req, err := d.newRequest(http.MethodGet, "/zones", nil) - if err != nil { - return nil, err - } - - query := req.URL.Query() - query.Add("page_request.filter", fmt.Sprintf("domain='%s'", tld)) - req.URL.RawQuery = query.Encode() - - var zones Zones - err = d.do(req, &zones) - if err != nil { - return nil, err - } - - if len(zones.Zones) == 0 { - return nil, fmt.Errorf("did not find zone with domain %s", domain) - } - - return &zones.Zones[0], nil -} - -// https://developer.stackpath.com/en/api/dns/#operation/GetZoneRecords -func (d *DNSProvider) getZoneRecords(name string, zone *Zone) ([]Record, error) { - u := fmt.Sprintf("/zones/%s/records", zone.ID) - req, err := d.newRequest(http.MethodGet, u, nil) - if err != nil { - return nil, err - } - - query := req.URL.Query() - query.Add("page_request.filter", fmt.Sprintf("name='%s' and type='TXT'", name)) - req.URL.RawQuery = query.Encode() - - var records Records - err = d.do(req, &records) - if err != nil { - return nil, err - } - - if len(records.Records) == 0 { - return nil, fmt.Errorf("did not find record with name %s", name) - } - - return records.Records, nil -} - -// https://developer.stackpath.com/en/api/dns/#operation/CreateZoneRecord -func (d *DNSProvider) createZoneRecord(zone *Zone, record Record) error { - u := fmt.Sprintf("/zones/%s/records", zone.ID) - req, err := d.newRequest(http.MethodPost, u, record) - if err != nil { - return err - } - - return d.do(req, nil) -} - -// https://developer.stackpath.com/en/api/dns/#operation/DeleteZoneRecord -func (d *DNSProvider) deleteZoneRecord(zone *Zone, record Record) error { - u := fmt.Sprintf("/zones/%s/records/%s", zone.ID, record.ID) - req, err := d.newRequest(http.MethodDelete, u, nil) - if err != nil { - return err - } - - return d.do(req, nil) -} - -func (d *DNSProvider) newRequest(method, urlStr string, body interface{}) (*http.Request, error) { - u, err := d.BaseURL.Parse(path.Join(d.config.StackID, urlStr)) - if err != nil { - return nil, err - } - - if body == nil { - var req *http.Request - req, err = http.NewRequest(method, u.String(), nil) - if err != nil { - return nil, err - } - - return req, nil - } - - reqBody, err := json.Marshal(body) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, u.String(), bytes.NewBuffer(reqBody)) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - - return req, nil -} - -func (d *DNSProvider) do(req *http.Request, v interface{}) error { - resp, err := d.client.Do(req) - if err != nil { - return err - } - - err = checkResponse(resp) - if err != nil { - return err - } - - if v == nil { - return nil - } - - raw, err := readBody(resp) - if err != nil { - return fmt.Errorf("failed to read body: %v", err) - } - - err = json.Unmarshal(raw, v) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(raw)) - } - - return nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode > 299 { - data, err := readBody(resp) - if err != nil { - return &ErrorResponse{Code: resp.StatusCode, Message: err.Error()} - } - - errResp := &ErrorResponse{} - err = json.Unmarshal(data, errResp) - if err != nil { - return &ErrorResponse{Code: resp.StatusCode, Message: fmt.Sprintf("unmarshaling error: %v: %s", err, string(data))} - } - return errResp - } - - return nil -} - -func readBody(resp *http.Response) ([]byte, error) { - if resp.Body == nil { - return nil, fmt.Errorf("response body is nil") - } - - defer resp.Body.Close() - - rawBody, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - - return rawBody, nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go b/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go deleted file mode 100644 index 48f77e99a..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/stackpath/stackpath.go +++ /dev/null @@ -1,150 +0,0 @@ -// Package stackpath implements a DNS provider for solving the DNS-01 challenge using Stackpath DNS. -// https://developer.stackpath.com/en/api/dns/ -package stackpath - -import ( - "context" - "errors" - "fmt" - "net/http" - "net/url" - "strings" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/log" - "github.com/go-acme/lego/platform/config/env" - "golang.org/x/oauth2/clientcredentials" -) - -const ( - defaultBaseURL = "https://gateway.stackpath.com/dns/v1/stacks/" - defaultAuthURL = "https://gateway.stackpath.com/identity/v1/oauth2/token" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - ClientID string - ClientSecret string - StackID string - TTL int - PropagationTimeout time.Duration - PollingInterval time.Duration -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("STACKPATH_TTL", 120), - PropagationTimeout: env.GetOrDefaultSecond("STACKPATH_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("STACKPATH_POLLING_INTERVAL", dns01.DefaultPollingInterval), - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - BaseURL *url.URL - client *http.Client - config *Config -} - -// NewDNSProvider returns a DNSProvider instance configured for Stackpath. -// Credentials must be passed in the environment variables: -// STACKPATH_CLIENT_ID, STACKPATH_CLIENT_SECRET, and STACKPATH_STACK_ID. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("STACKPATH_CLIENT_ID", "STACKPATH_CLIENT_SECRET", "STACKPATH_STACK_ID") - if err != nil { - return nil, fmt.Errorf("stackpath: %v", err) - } - - config := NewDefaultConfig() - config.ClientID = values["STACKPATH_CLIENT_ID"] - config.ClientSecret = values["STACKPATH_CLIENT_SECRET"] - config.StackID = values["STACKPATH_STACK_ID"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Stackpath. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("stackpath: the configuration of the DNS provider is nil") - } - - if len(config.ClientID) == 0 || len(config.ClientSecret) == 0 { - return nil, errors.New("stackpath: credentials missing") - } - - if len(config.StackID) == 0 { - return nil, errors.New("stackpath: stack id missing") - } - - baseURL, _ := url.Parse(defaultBaseURL) - - return &DNSProvider{ - BaseURL: baseURL, - client: getOathClient(config), - config: config, - }, nil -} - -func getOathClient(config *Config) *http.Client { - oathConfig := &clientcredentials.Config{ - TokenURL: defaultAuthURL, - ClientID: config.ClientID, - ClientSecret: config.ClientSecret, - } - - return oathConfig.Client(context.Background()) -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - zone, err := d.getZones(domain) - if err != nil { - return fmt.Errorf("stackpath: %v", err) - } - - fqdn, value := dns01.GetRecord(domain, keyAuth) - parts := strings.Split(fqdn, ".") - - record := Record{ - Name: parts[0], - Type: "TXT", - TTL: d.config.TTL, - Data: value, - } - - return d.createZoneRecord(zone, record) -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - zone, err := d.getZones(domain) - if err != nil { - return fmt.Errorf("stackpath: %v", err) - } - - fqdn, _ := dns01.GetRecord(domain, keyAuth) - parts := strings.Split(fqdn, ".") - - records, err := d.getZoneRecords(parts[0], zone) - if err != nil { - return err - } - - for _, record := range records { - err = d.deleteZoneRecord(zone, record) - if err != nil { - log.Printf("stackpath: failed to delete TXT record: %v", err) - } - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go b/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go deleted file mode 100644 index 2343696bc..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/transip/transip.go +++ /dev/null @@ -1,160 +0,0 @@ -// Package transip implements a DNS provider for solving the DNS-01 challenge using TransIP. -package transip - -import ( - "errors" - "fmt" - "strings" - "sync" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" - "github.com/transip/gotransip" - transipdomain "github.com/transip/gotransip/domain" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - AccountName string - PrivateKeyPath string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int64 -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: int64(env.GetOrDefaultInt("TRANSIP_TTL", 10)), - PropagationTimeout: env.GetOrDefaultSecond("TRANSIP_PROPAGATION_TIMEOUT", 10*time.Minute), - PollingInterval: env.GetOrDefaultSecond("TRANSIP_POLLING_INTERVAL", 10*time.Second), - } -} - -// DNSProvider describes a provider for TransIP -type DNSProvider struct { - config *Config - client gotransip.Client - dnsEntriesMu sync.Mutex -} - -// NewDNSProvider returns a DNSProvider instance configured for TransIP. -// Credentials must be passed in the environment variables: -// TRANSIP_ACCOUNTNAME, TRANSIP_PRIVATEKEYPATH. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("TRANSIP_ACCOUNT_NAME", "TRANSIP_PRIVATE_KEY_PATH") - if err != nil { - return nil, fmt.Errorf("transip: %v", err) - } - - config := NewDefaultConfig() - config.AccountName = values["TRANSIP_ACCOUNT_NAME"] - config.PrivateKeyPath = values["TRANSIP_PRIVATE_KEY_PATH"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for TransIP. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("transip: the configuration of the DNS provider is nil") - } - - client, err := gotransip.NewSOAPClient(gotransip.ClientConfig{ - AccountName: config.AccountName, - PrivateKeyPath: config.PrivateKeyPath, - }) - if err != nil { - return nil, fmt.Errorf("transip: %v", err) - } - - return &DNSProvider{client: client, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domainName := dns01.UnFqdn(authZone) - - // get the subDomain - subDomain := strings.TrimSuffix(dns01.UnFqdn(fqdn), "."+domainName) - - // use mutex to prevent race condition from GetInfo until SetDNSEntries - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - // get all DNS entries - info, err := transipdomain.GetInfo(d.client, domainName) - if err != nil { - return fmt.Errorf("transip: error for %s in Present: %v", domain, err) - } - - // include the new DNS entry - dnsEntries := append(info.DNSEntries, transipdomain.DNSEntry{ - Name: subDomain, - TTL: d.config.TTL, - Type: transipdomain.DNSEntryTypeTXT, - Content: value, - }) - - // set the updated DNS entries - err = transipdomain.SetDNSEntries(d.client, domainName, dnsEntries) - if err != nil { - return fmt.Errorf("transip: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - authZone, err := dns01.FindZoneByFqdn(fqdn) - if err != nil { - return err - } - - domainName := dns01.UnFqdn(authZone) - - // get the subDomain - subDomain := strings.TrimSuffix(dns01.UnFqdn(fqdn), "."+domainName) - - // use mutex to prevent race condition from GetInfo until SetDNSEntries - d.dnsEntriesMu.Lock() - defer d.dnsEntriesMu.Unlock() - - // get all DNS entries - info, err := transipdomain.GetInfo(d.client, domainName) - if err != nil { - return fmt.Errorf("transip: error for %s in CleanUp: %v", fqdn, err) - } - - // loop through the existing entries and remove the specific record - updatedEntries := info.DNSEntries[:0] - for _, e := range info.DNSEntries { - if e.Name != subDomain { - updatedEntries = append(updatedEntries, e) - } - } - - // set the updated DNS entries - err = transipdomain.SetDNSEntries(d.client, domainName, updatedEntries) - if err != nil { - return fmt.Errorf("transip: couldn't get Record ID in CleanUp: %sv", err) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vegadns/vegadns.go b/vendor/github.com/go-acme/lego/providers/dns/vegadns/vegadns.go deleted file mode 100644 index a5a043fda..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vegadns/vegadns.go +++ /dev/null @@ -1,113 +0,0 @@ -// Package vegadns implements a DNS provider for solving the DNS-01 challenge using VegaDNS. -package vegadns - -import ( - "errors" - "fmt" - "strings" - "time" - - vegaClient "github.com/OpenDNS/vegadns2client" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - BaseURL string - APIKey string - APISecret string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("VEGADNS_TTL", 10), - PropagationTimeout: env.GetOrDefaultSecond("VEGADNS_PROPAGATION_TIMEOUT", 12*time.Minute), - PollingInterval: env.GetOrDefaultSecond("VEGADNS_POLLING_INTERVAL", 1*time.Minute), - } -} - -// DNSProvider describes a provider for VegaDNS -type DNSProvider struct { - config *Config - client vegaClient.VegaDNSClient -} - -// NewDNSProvider returns a DNSProvider instance configured for VegaDNS. -// Credentials must be passed in the environment variables: -// VEGADNS_URL, SECRET_VEGADNS_KEY, SECRET_VEGADNS_SECRET. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("VEGADNS_URL") - if err != nil { - return nil, fmt.Errorf("vegadns: %v", err) - } - - config := NewDefaultConfig() - config.BaseURL = values["VEGADNS_URL"] - config.APIKey = env.GetOrFile("SECRET_VEGADNS_KEY") - config.APISecret = env.GetOrFile("SECRET_VEGADNS_SECRET") - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for VegaDNS. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("vegadns: the configuration of the DNS provider is nil") - } - - vega := vegaClient.NewVegaDNSClient(config.BaseURL) - vega.APIKey = config.APIKey - vega.APISecret = config.APISecret - - return &DNSProvider{client: vega, config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - _, domainID, err := d.client.GetAuthZone(fqdn) - if err != nil { - return fmt.Errorf("vegadns: can't find Authoritative Zone for %s in Present: %v", fqdn, err) - } - - err = d.client.CreateTXT(domainID, fqdn, value, d.config.TTL) - if err != nil { - return fmt.Errorf("vegadns: %v", err) - } - return nil -} - -// CleanUp removes the TXT record matching the specified parameters -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - _, domainID, err := d.client.GetAuthZone(fqdn) - if err != nil { - return fmt.Errorf("vegadns: can't find Authoritative Zone for %s in CleanUp: %v", fqdn, err) - } - - txt := strings.TrimSuffix(fqdn, ".") - - recordID, err := d.client.GetRecordID(domainID, txt, "TXT") - if err != nil { - return fmt.Errorf("vegadns: couldn't get Record ID in CleanUp: %s", err) - } - - err = d.client.DeleteRecord(recordID) - if err != nil { - return fmt.Errorf("vegadns: %v", err) - } - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vscale/internal/client.go b/vendor/github.com/go-acme/lego/providers/dns/vscale/internal/client.go deleted file mode 100644 index 7ce7495e9..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vscale/internal/client.go +++ /dev/null @@ -1,221 +0,0 @@ -package internal - -import ( - "bytes" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "strings" -) - -// Domain represents domain name. -type Domain struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` -} - -// Record represents DNS record. -type Record struct { - ID int `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Type string `json:"type,omitempty"` // Record type (SOA, NS, A/AAAA, CNAME, SRV, MX, TXT, SPF) - TTL int `json:"ttl,omitempty"` - Email string `json:"email,omitempty"` // Email of domain's admin (only for SOA records) - Content string `json:"content,omitempty"` // Record content (not for SRV) -} - -// APIError API error message -type APIError struct { - Description string `json:"error"` - Code int `json:"code"` - Field string `json:"field"` -} - -func (a *APIError) Error() string { - return fmt.Sprintf("API error: %d - %s - %s", a.Code, a.Description, a.Field) -} - -// ClientOpts represents options to init client. -type ClientOpts struct { - BaseURL string - Token string - UserAgent string - HTTPClient *http.Client -} - -// Client represents DNS client. -type Client struct { - baseURL string - token string - userAgent string - httpClient *http.Client -} - -// NewClient returns a client instance. -func NewClient(opts ClientOpts) *Client { - if opts.HTTPClient == nil { - opts.HTTPClient = &http.Client{} - } - - return &Client{ - token: opts.Token, - baseURL: opts.BaseURL, - httpClient: opts.HTTPClient, - userAgent: opts.UserAgent, - } -} - -// GetDomainByName gets Domain object by its name. If `domainName` level > 2 and there is -// no such domain on the account - it'll recursively search for the first -// which is exists in Vscale Domains API. -func (c *Client) GetDomainByName(domainName string) (*Domain, error) { - uri := fmt.Sprintf("/%s", domainName) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - domain := &Domain{} - resp, err := c.do(req, domain) - if err != nil { - switch { - case resp.StatusCode == http.StatusNotFound && strings.Count(domainName, ".") > 1: - // Look up for the next sub domain - subIndex := strings.Index(domainName, ".") - return c.GetDomainByName(domainName[subIndex+1:]) - default: - return nil, err - } - } - - return domain, nil -} - -// AddRecord adds Record for given domain. -func (c *Client) AddRecord(domainID int, body Record) (*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodPost, uri, body) - if err != nil { - return nil, err - } - - record := &Record{} - _, err = c.do(req, record) - if err != nil { - return nil, err - } - - return record, nil -} - -// ListRecords returns list records for specific domain. -func (c *Client) ListRecords(domainID int) ([]*Record, error) { - uri := fmt.Sprintf("/%d/records/", domainID) - req, err := c.newRequest(http.MethodGet, uri, nil) - if err != nil { - return nil, err - } - - var records []*Record - _, err = c.do(req, &records) - if err != nil { - return nil, err - } - return records, nil -} - -// DeleteRecord deletes specific record. -func (c *Client) DeleteRecord(domainID, recordID int) error { - uri := fmt.Sprintf("/%d/records/%d", domainID, recordID) - req, err := c.newRequest(http.MethodDelete, uri, nil) - if err != nil { - return err - } - - _, err = c.do(req, nil) - return err -} - -func (c *Client) newRequest(method, uri string, body interface{}) (*http.Request, error) { - buf := new(bytes.Buffer) - - if body != nil { - err := json.NewEncoder(buf).Encode(body) - if err != nil { - return nil, fmt.Errorf("failed to encode request body with error: %v", err) - } - } - - req, err := http.NewRequest(method, c.baseURL+uri, buf) - if err != nil { - return nil, fmt.Errorf("failed to create new http request with error: %v", err) - } - - req.Header.Add("X-Token", c.token) - req.Header.Add("Content-Type", "application/json") - req.Header.Add("Accept", "application/json") - - return req, nil -} - -func (c *Client) do(req *http.Request, to interface{}) (*http.Response, error) { - resp, err := c.httpClient.Do(req) - if err != nil { - return nil, fmt.Errorf("request failed with error: %v", err) - } - - err = checkResponse(resp) - if err != nil { - return resp, err - } - - if to != nil { - if err = unmarshalBody(resp, to); err != nil { - return resp, err - } - } - - return resp, nil -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode >= http.StatusBadRequest && - resp.StatusCode <= http.StatusNetworkAuthenticationRequired { - - if resp.Body == nil { - return fmt.Errorf("request failed with status code %d and empty body", resp.StatusCode) - } - - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - apiError := APIError{} - err = json.Unmarshal(body, &apiError) - if err != nil { - return fmt.Errorf("request failed with status code %d, response body: %s", resp.StatusCode, string(body)) - } - - return fmt.Errorf("request failed with status code %d: %v", resp.StatusCode, apiError) - } - - return nil -} - -func unmarshalBody(resp *http.Response, to interface{}) error { - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - defer resp.Body.Close() - - err = json.Unmarshal(body, to) - if err != nil { - return fmt.Errorf("unmarshaling error: %v: %s", err, string(body)) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go b/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go deleted file mode 100644 index f6ce20754..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vscale/vscale.go +++ /dev/null @@ -1,155 +0,0 @@ -// Package vscale implements a DNS provider for solving the DNS-01 challenge using Vscale Domains API. -// Vscale Domain API reference: https://developers.vscale.io/documentation/api/v1/#api-Domains -// Token: https://vscale.io/panel/settings/tokens/ -package vscale - -import ( - "errors" - "fmt" - "net/http" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/providers/dns/vscale/internal" - - "github.com/go-acme/lego/platform/config/env" -) - -const ( - defaultBaseURL = "https://api.vscale.io/v1/domains" - minTTL = 60 -) - -const ( - envNamespace = "VSCALE_" - baseURLEnvVar = envNamespace + "BASE_URL" - apiTokenEnvVar = envNamespace + "API_TOKEN" - ttlEnvVar = envNamespace + "TTL" - propagationTimeoutEnvVar = envNamespace + "PROPAGATION_TIMEOUT" - pollingIntervalEnvVar = envNamespace + "POLLING_INTERVAL" - httpTimeoutEnvVar = envNamespace + "HTTP_TIMEOUT" -) - -// Config is used to configure the creation of the DNSProvider. -type Config struct { - BaseURL string - Token string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider. -func NewDefaultConfig() *Config { - return &Config{ - BaseURL: env.GetOrDefaultString(baseURLEnvVar, defaultBaseURL), - TTL: env.GetOrDefaultInt(ttlEnvVar, minTTL), - PropagationTimeout: env.GetOrDefaultSecond(propagationTimeoutEnvVar, 120*time.Second), - PollingInterval: env.GetOrDefaultSecond(pollingIntervalEnvVar, 2*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond(httpTimeoutEnvVar, 30*time.Second), - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *internal.Client -} - -// NewDNSProvider returns a DNSProvider instance configured for Vscale Domains API. -// API token must be passed in the environment variable VSCALE_API_TOKEN. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get(apiTokenEnvVar) - if err != nil { - return nil, fmt.Errorf("vscale: %v", err) - } - - config := NewDefaultConfig() - config.Token = values[apiTokenEnvVar] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Vscale. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("vscale: the configuration of the DNS provider is nil") - } - - if config.Token == "" { - return nil, errors.New("vscale: credentials missing") - } - - if config.TTL < minTTL { - return nil, fmt.Errorf("vscale: invalid TTL, TTL (%d) must be greater than %d", config.TTL, minTTL) - } - - client := internal.NewClient(internal.ClientOpts{ - BaseURL: config.BaseURL, - Token: config.Token, - HTTPClient: config.HTTPClient, - }) - - return &DNSProvider{config: config, client: client}, nil -} - -// Timeout returns the Timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - txtRecord := internal.Record{ - Type: "TXT", - TTL: d.config.TTL, - Name: fqdn, - Content: value, - } - _, err = d.client.AddRecord(domainObj.ID, txtRecord) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - return nil -} - -// CleanUp removes a TXT record used for DNS-01 challenge. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - recordName := dns01.UnFqdn(fqdn) - - domainObj, err := d.client.GetDomainByName(domain) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - records, err := d.client.ListRecords(domainObj.ID) - if err != nil { - return fmt.Errorf("vscale: %v", err) - } - - // Delete records with specific FQDN - var lastErr error - for _, record := range records { - if record.Name == recordName { - err = d.client.DeleteRecord(domainObj.ID, record.ID) - if err != nil { - lastErr = fmt.Errorf("vscale: %v", err) - } - } - } - - return lastErr -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go b/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go deleted file mode 100644 index 94e5d8639..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/vultr/vultr.go +++ /dev/null @@ -1,179 +0,0 @@ -// Package vultr implements a DNS provider for solving the DNS-01 challenge using the vultr DNS. -// See https://www.vultr.com/api/#dns -package vultr - -import ( - "crypto/tls" - "errors" - "fmt" - "net/http" - "strings" - "time" - - vultr "github.com/JamesClonk/vultr/lib" - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - TTL int - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - return &Config{ - TTL: env.GetOrDefaultInt("VULTR_TTL", dns01.DefaultTTL), - PropagationTimeout: env.GetOrDefaultSecond("VULTR_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout), - PollingInterval: env.GetOrDefaultSecond("VULTR_POLLING_INTERVAL", dns01.DefaultPollingInterval), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("VULTR_HTTP_TIMEOUT", 0), - // from Vultr Client - Transport: &http.Transport{ - TLSNextProto: make(map[string]func(string, *tls.Conn) http.RoundTripper), - }, - }, - } -} - -// DNSProvider is an implementation of the acme.ChallengeProvider interface. -type DNSProvider struct { - config *Config - client *vultr.Client -} - -// NewDNSProvider returns a DNSProvider instance with a configured Vultr client. -// Authentication uses the VULTR_API_KEY environment variable. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("VULTR_API_KEY") - if err != nil { - return nil, fmt.Errorf("vultr: %v", err) - } - - config := NewDefaultConfig() - config.APIKey = values["VULTR_API_KEY"] - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider instance configured for Vultr. -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("vultr: the configuration of the DNS provider is nil") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("vultr: credentials missing") - } - - options := &vultr.Options{ - HTTPClient: config.HTTPClient, - } - client := vultr.NewClient(config.APIKey, options) - - return &DNSProvider{client: client, config: config}, nil -} - -// Present creates a TXT record to fulfill the DNS-01 challenge. -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - zoneDomain, err := d.getHostedZone(domain) - if err != nil { - return fmt.Errorf("vultr: %v", err) - } - - name := d.extractRecordName(fqdn, zoneDomain) - - err = d.client.CreateDNSRecord(zoneDomain, name, "TXT", `"`+value+`"`, 0, d.config.TTL) - if err != nil { - return fmt.Errorf("vultr: API call failed: %v", err) - } - - return nil -} - -// CleanUp removes the TXT record matching the specified parameters. -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - fqdn, _ := dns01.GetRecord(domain, keyAuth) - - zoneDomain, records, err := d.findTxtRecords(domain, fqdn) - if err != nil { - return fmt.Errorf("vultr: %v", err) - } - - var allErr []string - for _, rec := range records { - err := d.client.DeleteDNSRecord(zoneDomain, rec.RecordID) - if err != nil { - allErr = append(allErr, err.Error()) - } - } - - if len(allErr) > 0 { - return errors.New(strings.Join(allErr, ": ")) - } - - return nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -func (d *DNSProvider) getHostedZone(domain string) (string, error) { - domains, err := d.client.GetDNSDomains() - if err != nil { - return "", fmt.Errorf("API call failed: %v", err) - } - - var hostedDomain vultr.DNSDomain - for _, dom := range domains { - if strings.HasSuffix(domain, dom.Domain) { - if len(dom.Domain) > len(hostedDomain.Domain) { - hostedDomain = dom - } - } - } - if hostedDomain.Domain == "" { - return "", fmt.Errorf("no matching Vultr domain found for domain %s", domain) - } - - return hostedDomain.Domain, nil -} - -func (d *DNSProvider) findTxtRecords(domain, fqdn string) (string, []vultr.DNSRecord, error) { - zoneDomain, err := d.getHostedZone(domain) - if err != nil { - return "", nil, err - } - - var records []vultr.DNSRecord - result, err := d.client.GetDNSRecords(zoneDomain) - if err != nil { - return "", records, fmt.Errorf("API call has failed: %v", err) - } - - recordName := d.extractRecordName(fqdn, zoneDomain) - for _, record := range result { - if record.Type == "TXT" && record.Name == recordName { - records = append(records, record) - } - } - - return zoneDomain, records, nil -} - -func (d *DNSProvider) extractRecordName(fqdn, domain string) string { - name := dns01.UnFqdn(fqdn) - if idx := strings.Index(name, "."+domain); idx != -1 { - return name[:idx] - } - return name -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go b/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go deleted file mode 100644 index b48808b84..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/client.go +++ /dev/null @@ -1,132 +0,0 @@ -package zoneee - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "io/ioutil" - "net/http" - "path" -) - -const defaultEndpoint = "https://api.zone.eu/v2/dns/" - -type txtRecord struct { - // Identifier (identificator) - ID string `json:"id,omitempty"` - // Hostname - Name string `json:"name"` - // TXT content value - Destination string `json:"destination"` - // Can this record be deleted - Delete bool `json:"delete,omitempty"` - // Can this record be modified - Modify bool `json:"modify,omitempty"` - // API url to get this entity - ResourceURL string `json:"resource_url,omitempty"` -} - -func (d *DNSProvider) addTxtRecord(domain string, record txtRecord) ([]txtRecord, error) { - reqBody := &bytes.Buffer{} - if err := json.NewEncoder(reqBody).Encode(record); err != nil { - return nil, err - } - - req, err := d.makeRequest(http.MethodPost, path.Join(domain, "txt"), reqBody) - if err != nil { - return nil, err - } - - var resp []txtRecord - if err := d.sendRequest(req, &resp); err != nil { - return nil, err - } - return resp, nil -} - -func (d *DNSProvider) getTxtRecords(domain string) ([]txtRecord, error) { - req, err := d.makeRequest(http.MethodGet, path.Join(domain, "txt"), nil) - if err != nil { - return nil, err - } - - var resp []txtRecord - if err := d.sendRequest(req, &resp); err != nil { - return nil, err - } - return resp, nil -} - -func (d *DNSProvider) removeTxtRecord(domain, id string) error { - req, err := d.makeRequest(http.MethodDelete, path.Join(domain, "txt", id), nil) - if err != nil { - return err - } - - return d.sendRequest(req, nil) -} - -func (d *DNSProvider) makeRequest(method, resource string, body io.Reader) (*http.Request, error) { - uri, err := d.config.Endpoint.Parse(resource) - if err != nil { - return nil, err - } - - req, err := http.NewRequest(method, uri.String(), body) - if err != nil { - return nil, err - } - - req.Header.Set("Content-Type", "application/json") - req.SetBasicAuth(d.config.Username, d.config.APIKey) - - return req, nil -} - -func (d *DNSProvider) sendRequest(req *http.Request, result interface{}) error { - resp, err := d.config.HTTPClient.Do(req) - if err != nil { - return err - } - - if err = checkResponse(resp); err != nil { - return err - } - - defer resp.Body.Close() - - if result == nil { - return nil - } - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return err - } - - err = json.Unmarshal(raw, result) - if err != nil { - return fmt.Errorf("unmarshaling %T error [status code=%d]: %v: %s", result, resp.StatusCode, err, string(raw)) - } - return err -} - -func checkResponse(resp *http.Response) error { - if resp.StatusCode < http.StatusBadRequest { - return nil - } - - if resp.Body == nil { - return fmt.Errorf("response body is nil, status code=%d", resp.StatusCode) - } - - defer resp.Body.Close() - - raw, err := ioutil.ReadAll(resp.Body) - if err != nil { - return fmt.Errorf("unable to read body: status code=%d, error=%v", resp.StatusCode, err) - } - - return fmt.Errorf("status code=%d: %s", resp.StatusCode, string(raw)) -} diff --git a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go b/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go deleted file mode 100644 index 8ede3d6ca..000000000 --- a/vendor/github.com/go-acme/lego/providers/dns/zoneee/zoneee.go +++ /dev/null @@ -1,134 +0,0 @@ -// Package zoneee implements a DNS provider for solving the DNS-01 challenge through zone.ee. -package zoneee - -import ( - "errors" - "fmt" - "net/http" - "net/url" - "time" - - "github.com/go-acme/lego/challenge/dns01" - "github.com/go-acme/lego/platform/config/env" -) - -// Config is used to configure the creation of the DNSProvider -type Config struct { - Endpoint *url.URL - Username string - APIKey string - PropagationTimeout time.Duration - PollingInterval time.Duration - HTTPClient *http.Client -} - -// NewDefaultConfig returns a default configuration for the DNSProvider -func NewDefaultConfig() *Config { - endpoint, _ := url.Parse(defaultEndpoint) - - return &Config{ - Endpoint: endpoint, - // zone.ee can take up to 5min to propagate according to the support - PropagationTimeout: env.GetOrDefaultSecond("ZONEEE_PROPAGATION_TIMEOUT", 5*time.Minute), - PollingInterval: env.GetOrDefaultSecond("ZONEEE_POLLING_INTERVAL", 5*time.Second), - HTTPClient: &http.Client{ - Timeout: env.GetOrDefaultSecond("ZONEEE_HTTP_TIMEOUT", 30*time.Second), - }, - } -} - -// DNSProvider describes a provider for acme-proxy -type DNSProvider struct { - config *Config -} - -// NewDNSProvider returns a DNSProvider instance. -func NewDNSProvider() (*DNSProvider, error) { - values, err := env.Get("ZONEEE_API_USER", "ZONEEE_API_KEY") - if err != nil { - return nil, fmt.Errorf("zoneee: %v", err) - } - - rawEndpoint := env.GetOrDefaultString("ZONEEE_ENDPOINT", defaultEndpoint) - endpoint, err := url.Parse(rawEndpoint) - if err != nil { - return nil, fmt.Errorf("zoneee: %v", err) - } - - config := NewDefaultConfig() - config.Username = values["ZONEEE_API_USER"] - config.APIKey = values["ZONEEE_API_KEY"] - config.Endpoint = endpoint - - return NewDNSProviderConfig(config) -} - -// NewDNSProviderConfig return a DNSProvider . -func NewDNSProviderConfig(config *Config) (*DNSProvider, error) { - if config == nil { - return nil, errors.New("zoneee: the configuration of the DNS provider is nil") - } - - if config.Username == "" { - return nil, fmt.Errorf("zoneee: credentials missing: username") - } - - if config.APIKey == "" { - return nil, fmt.Errorf("zoneee: credentials missing: API key") - } - - if config.Endpoint == nil { - return nil, errors.New("zoneee: the endpoint is missing") - } - - return &DNSProvider{config: config}, nil -} - -// Timeout returns the timeout and interval to use when checking for DNS propagation. -// Adjusting here to cope with spikes in propagation times. -func (d *DNSProvider) Timeout() (timeout, interval time.Duration) { - return d.config.PropagationTimeout, d.config.PollingInterval -} - -// Present creates a TXT record to fulfill the dns-01 challenge -func (d *DNSProvider) Present(domain, token, keyAuth string) error { - fqdn, value := dns01.GetRecord(domain, keyAuth) - - record := txtRecord{ - Name: fqdn[:len(fqdn)-1], - Destination: value, - } - - _, err := d.addTxtRecord(domain, record) - if err != nil { - return fmt.Errorf("zoneee: %v", err) - } - return nil -} - -// CleanUp removes the TXT record previously created -func (d *DNSProvider) CleanUp(domain, token, keyAuth string) error { - _, value := dns01.GetRecord(domain, keyAuth) - - records, err := d.getTxtRecords(domain) - if err != nil { - return fmt.Errorf("zoneee: %v", err) - } - - var id string - for _, record := range records { - if record.Destination == value { - id = record.ID - } - } - - if id == "" { - return fmt.Errorf("zoneee: txt record does not exist for %v", value) - } - - if err = d.removeTxtRecord(domain, id); err != nil { - return fmt.Errorf("zoneee: %v", err) - } - - return nil -} diff --git a/vendor/github.com/go-acme/lego/registration/registar.go b/vendor/github.com/go-acme/lego/registration/registar.go deleted file mode 100644 index 09e866574..000000000 --- a/vendor/github.com/go-acme/lego/registration/registar.go +++ /dev/null @@ -1,146 +0,0 @@ -package registration - -import ( - "errors" - "net/http" - - "github.com/go-acme/lego/acme" - "github.com/go-acme/lego/acme/api" - "github.com/go-acme/lego/log" -) - -// Resource represents all important information about a registration -// of which the client needs to keep track itself. -// Deprecated: will be remove in the future (acme.ExtendedAccount). -type Resource struct { - Body acme.Account `json:"body,omitempty"` - URI string `json:"uri,omitempty"` -} - -type RegisterOptions struct { - TermsOfServiceAgreed bool -} - -type RegisterEABOptions struct { - TermsOfServiceAgreed bool - Kid string - HmacEncoded string -} - -type Registrar struct { - core *api.Core - user User -} - -func NewRegistrar(core *api.Core, user User) *Registrar { - return &Registrar{ - core: core, - user: user, - } -} - -// Register the current account to the ACME server. -func (r *Registrar) Register(options RegisterOptions) (*Resource, error) { - if r == nil || r.user == nil { - return nil, errors.New("acme: cannot register a nil client or user") - } - - accMsg := acme.Account{ - TermsOfServiceAgreed: options.TermsOfServiceAgreed, - Contact: []string{}, - } - - if r.user.GetEmail() != "" { - log.Infof("acme: Registering account for %s", r.user.GetEmail()) - accMsg.Contact = []string{"mailto:" + r.user.GetEmail()} - } - - account, err := r.core.Accounts.New(accMsg) - if err != nil { - // FIXME seems impossible - errorDetails, ok := err.(acme.ProblemDetails) - if !ok || errorDetails.HTTPStatus != http.StatusConflict { - return nil, err - } - } - - return &Resource{URI: account.Location, Body: account.Account}, nil -} - -// RegisterWithExternalAccountBinding Register the current account to the ACME server. -func (r *Registrar) RegisterWithExternalAccountBinding(options RegisterEABOptions) (*Resource, error) { - accMsg := acme.Account{ - TermsOfServiceAgreed: options.TermsOfServiceAgreed, - Contact: []string{}, - } - - if r.user.GetEmail() != "" { - log.Infof("acme: Registering account for %s", r.user.GetEmail()) - accMsg.Contact = []string{"mailto:" + r.user.GetEmail()} - } - - account, err := r.core.Accounts.NewEAB(accMsg, options.Kid, options.HmacEncoded) - if err != nil { - errorDetails, ok := err.(acme.ProblemDetails) - // FIXME seems impossible - if !ok || errorDetails.HTTPStatus != http.StatusConflict { - return nil, err - } - } - - return &Resource{URI: account.Location, Body: account.Account}, nil -} - -// QueryRegistration runs a POST request on the client's registration and returns the result. -// -// This is similar to the Register function, -// but acting on an existing registration link and resource. -func (r *Registrar) QueryRegistration() (*Resource, error) { - if r == nil || r.user == nil { - return nil, errors.New("acme: cannot query the registration of a nil client or user") - } - - // Log the URL here instead of the email as the email may not be set - log.Infof("acme: Querying account for %s", r.user.GetRegistration().URI) - - account, err := r.core.Accounts.Get(r.user.GetRegistration().URI) - if err != nil { - return nil, err - } - - return &Resource{ - Body: account, - // Location: header is not returned so this needs to be populated off of existing URI - URI: r.user.GetRegistration().URI, - }, nil -} - -// DeleteRegistration deletes the client's user registration from the ACME server. -func (r *Registrar) DeleteRegistration() error { - if r == nil || r.user == nil { - return errors.New("acme: cannot unregister a nil client or user") - } - - log.Infof("acme: Deleting account for %s", r.user.GetEmail()) - - return r.core.Accounts.Deactivate(r.user.GetRegistration().URI) -} - -// ResolveAccountByKey will attempt to look up an account using the given account key -// and return its registration resource. -func (r *Registrar) ResolveAccountByKey() (*Resource, error) { - log.Infof("acme: Trying to resolve account by key") - - accMsg := acme.Account{OnlyReturnExisting: true} - accountTransit, err := r.core.Accounts.New(accMsg) - if err != nil { - return nil, err - } - - account, err := r.core.Accounts.Get(accountTransit.Location) - if err != nil { - return nil, err - } - - return &Resource{URI: accountTransit.Location, Body: account}, nil -} diff --git a/vendor/github.com/go-acme/lego/registration/user.go b/vendor/github.com/go-acme/lego/registration/user.go deleted file mode 100644 index 1e29300e2..000000000 --- a/vendor/github.com/go-acme/lego/registration/user.go +++ /dev/null @@ -1,13 +0,0 @@ -package registration - -import ( - "crypto" -) - -// User interface is to be implemented by users of this library. -// It is used by the client type to get user specific information. -type User interface { - GetEmail() string - GetRegistration() *Resource - GetPrivateKey() crypto.PrivateKey -} diff --git a/vendor/github.com/go-check/check/LICENSE b/vendor/github.com/go-check/check/LICENSE deleted file mode 100644 index 545cf2d33..000000000 --- a/vendor/github.com/go-check/check/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Gocheck - A rich testing framework for Go - -Copyright (c) 2010-2013 Gustavo Niemeyer - -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -1. Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/go-check/check/benchmark.go b/vendor/github.com/go-check/check/benchmark.go deleted file mode 100644 index 46ea9dc6d..000000000 --- a/vendor/github.com/go-check/check/benchmark.go +++ /dev/null @@ -1,187 +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. - -package check - -import ( - "fmt" - "runtime" - "time" -) - -var memStats runtime.MemStats - -// testingB is a type passed to Benchmark functions to manage benchmark -// timing and to specify the number of iterations to run. -type timer struct { - start time.Time // Time test or benchmark started - duration time.Duration - N int - bytes int64 - timerOn bool - benchTime time.Duration - // The initial states of memStats.Mallocs and memStats.TotalAlloc. - startAllocs uint64 - startBytes uint64 - // The net total of this test after being run. - netAllocs uint64 - netBytes uint64 -} - -// StartTimer starts timing a test. This function is called automatically -// before a benchmark starts, but it can also used to resume timing after -// a call to StopTimer. -func (c *C) StartTimer() { - if !c.timerOn { - c.start = time.Now() - c.timerOn = true - - runtime.ReadMemStats(&memStats) - c.startAllocs = memStats.Mallocs - c.startBytes = memStats.TotalAlloc - } -} - -// StopTimer stops timing a test. This can be used to pause the timer -// while performing complex initialization that you don't -// want to measure. -func (c *C) StopTimer() { - if c.timerOn { - c.duration += time.Now().Sub(c.start) - c.timerOn = false - runtime.ReadMemStats(&memStats) - c.netAllocs += memStats.Mallocs - c.startAllocs - c.netBytes += memStats.TotalAlloc - c.startBytes - } -} - -// ResetTimer sets the elapsed benchmark time to zero. -// It does not affect whether the timer is running. -func (c *C) ResetTimer() { - if c.timerOn { - c.start = time.Now() - runtime.ReadMemStats(&memStats) - c.startAllocs = memStats.Mallocs - c.startBytes = memStats.TotalAlloc - } - c.duration = 0 - c.netAllocs = 0 - c.netBytes = 0 -} - -// SetBytes informs the number of bytes that the benchmark processes -// on each iteration. If this is called in a benchmark it will also -// report MB/s. -func (c *C) SetBytes(n int64) { - c.bytes = n -} - -func (c *C) nsPerOp() int64 { - if c.N <= 0 { - return 0 - } - return c.duration.Nanoseconds() / int64(c.N) -} - -func (c *C) mbPerSec() float64 { - if c.bytes <= 0 || c.duration <= 0 || c.N <= 0 { - return 0 - } - return (float64(c.bytes) * float64(c.N) / 1e6) / c.duration.Seconds() -} - -func (c *C) timerString() string { - if c.N <= 0 { - return fmt.Sprintf("%3.3fs", float64(c.duration.Nanoseconds())/1e9) - } - mbs := c.mbPerSec() - mb := "" - if mbs != 0 { - mb = fmt.Sprintf("\t%7.2f MB/s", mbs) - } - nsop := c.nsPerOp() - ns := fmt.Sprintf("%10d ns/op", nsop) - if c.N > 0 && nsop < 100 { - // The format specifiers here make sure that - // the ones digits line up for all three possible formats. - if nsop < 10 { - ns = fmt.Sprintf("%13.2f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) - } else { - ns = fmt.Sprintf("%12.1f ns/op", float64(c.duration.Nanoseconds())/float64(c.N)) - } - } - memStats := "" - if c.benchMem { - allocedBytes := fmt.Sprintf("%8d B/op", int64(c.netBytes)/int64(c.N)) - allocs := fmt.Sprintf("%8d allocs/op", int64(c.netAllocs)/int64(c.N)) - memStats = fmt.Sprintf("\t%s\t%s", allocedBytes, allocs) - } - return fmt.Sprintf("%8d\t%s%s%s", c.N, ns, mb, memStats) -} - -func min(x, y int) int { - if x > y { - return y - } - return x -} - -func max(x, y int) int { - if x < y { - return y - } - return x -} - -// roundDown10 rounds a number down to the nearest power of 10. -func roundDown10(n int) int { - var tens = 0 - // tens = floor(log_10(n)) - for n > 10 { - n = n / 10 - tens++ - } - // result = 10^tens - result := 1 - for i := 0; i < tens; i++ { - result *= 10 - } - return result -} - -// roundUp rounds x up to a number of the form [1eX, 2eX, 5eX]. -func roundUp(n int) int { - base := roundDown10(n) - if n < (2 * base) { - return 2 * base - } - if n < (5 * base) { - return 5 * base - } - return 10 * base -} diff --git a/vendor/github.com/go-check/check/check.go b/vendor/github.com/go-check/check/check.go deleted file mode 100644 index e8f23f9d1..000000000 --- a/vendor/github.com/go-check/check/check.go +++ /dev/null @@ -1,888 +0,0 @@ -// Package check is a rich testing extension for Go's testing package. -// -// For details about the project, see: -// -// http://labix.org/gocheck -// -package check - -import ( - "bytes" - "errors" - "fmt" - "io" - "math/rand" - "os" - "path" - "path/filepath" - "reflect" - "regexp" - "runtime" - "strconv" - "strings" - "sync" - "sync/atomic" - "time" -) - -// ----------------------------------------------------------------------- -// Internal type which deals with suite method calling. - -const ( - fixtureKd = iota - testKd -) - -type funcKind int - -const ( - succeededSt = iota - failedSt - skippedSt - panickedSt - fixturePanickedSt - missedSt -) - -type funcStatus uint32 - -// A method value can't reach its own Method structure. -type methodType struct { - reflect.Value - Info reflect.Method -} - -func newMethod(receiver reflect.Value, i int) *methodType { - return &methodType{receiver.Method(i), receiver.Type().Method(i)} -} - -func (method *methodType) PC() uintptr { - return method.Info.Func.Pointer() -} - -func (method *methodType) suiteName() string { - t := method.Info.Type.In(0) - if t.Kind() == reflect.Ptr { - t = t.Elem() - } - return t.Name() -} - -func (method *methodType) String() string { - return method.suiteName() + "." + method.Info.Name -} - -func (method *methodType) matches(re *regexp.Regexp) bool { - return (re.MatchString(method.Info.Name) || - re.MatchString(method.suiteName()) || - re.MatchString(method.String())) -} - -type C struct { - method *methodType - kind funcKind - testName string - _status funcStatus - logb *logger - logw io.Writer - done chan *C - reason string - mustFail bool - tempDir *tempDir - benchMem bool - startTime time.Time - timer -} - -func (c *C) status() funcStatus { - return funcStatus(atomic.LoadUint32((*uint32)(&c._status))) -} - -func (c *C) setStatus(s funcStatus) { - atomic.StoreUint32((*uint32)(&c._status), uint32(s)) -} - -func (c *C) stopNow() { - runtime.Goexit() -} - -// logger is a concurrency safe byte.Buffer -type logger struct { - sync.Mutex - writer bytes.Buffer -} - -func (l *logger) Write(buf []byte) (int, error) { - l.Lock() - defer l.Unlock() - return l.writer.Write(buf) -} - -func (l *logger) WriteTo(w io.Writer) (int64, error) { - l.Lock() - defer l.Unlock() - return l.writer.WriteTo(w) -} - -func (l *logger) String() string { - l.Lock() - defer l.Unlock() - return l.writer.String() -} - -// ----------------------------------------------------------------------- -// Handling of temporary files and directories. - -type tempDir struct { - sync.Mutex - path string - counter int -} - -func (td *tempDir) newPath() string { - td.Lock() - defer td.Unlock() - if td.path == "" { - var err error - for i := 0; i != 100; i++ { - path := fmt.Sprintf("%s%ccheck-%d", os.TempDir(), os.PathSeparator, rand.Int()) - if err = os.Mkdir(path, 0700); err == nil { - td.path = path - break - } - } - if td.path == "" { - panic("Couldn't create temporary directory: " + err.Error()) - } - } - result := filepath.Join(td.path, strconv.Itoa(td.counter)) - td.counter++ - return result -} - -func (td *tempDir) removeAll() { - td.Lock() - defer td.Unlock() - if td.path != "" { - err := os.RemoveAll(td.path) - if err != nil { - fmt.Fprintf(os.Stderr, "WARNING: Error cleaning up temporaries: "+err.Error()) - } - } -} - -// Create a new temporary directory which is automatically removed after -// the suite finishes running. -func (c *C) MkDir() string { - path := c.tempDir.newPath() - if err := os.Mkdir(path, 0700); err != nil { - panic(fmt.Sprintf("Couldn't create temporary directory %s: %s", path, err.Error())) - } - return path -} - -// ----------------------------------------------------------------------- -// Low-level logging functions. - -func (c *C) log(args ...interface{}) { - c.writeLog([]byte(fmt.Sprint(args...) + "\n")) -} - -func (c *C) logf(format string, args ...interface{}) { - c.writeLog([]byte(fmt.Sprintf(format+"\n", args...))) -} - -func (c *C) logNewLine() { - c.writeLog([]byte{'\n'}) -} - -func (c *C) writeLog(buf []byte) { - c.logb.Write(buf) - if c.logw != nil { - c.logw.Write(buf) - } -} - -func hasStringOrError(x interface{}) (ok bool) { - _, ok = x.(fmt.Stringer) - if ok { - return - } - _, ok = x.(error) - return -} - -func (c *C) logValue(label string, value interface{}) { - if label == "" { - if hasStringOrError(value) { - c.logf("... %#v (%q)", value, value) - } else { - c.logf("... %#v", value) - } - } else if value == nil { - c.logf("... %s = nil", label) - } else { - if hasStringOrError(value) { - fv := fmt.Sprintf("%#v", value) - qv := fmt.Sprintf("%q", value) - if fv != qv { - c.logf("... %s %s = %s (%s)", label, reflect.TypeOf(value), fv, qv) - return - } - } - if s, ok := value.(string); ok && isMultiLine(s) { - c.logf(`... %s %s = "" +`, label, reflect.TypeOf(value)) - c.logMultiLine(s) - } else { - c.logf("... %s %s = %#v", label, reflect.TypeOf(value), value) - } - } -} - -func (c *C) logMultiLine(s string) { - b := make([]byte, 0, len(s)*2) - i := 0 - n := len(s) - for i < n { - j := i + 1 - for j < n && s[j-1] != '\n' { - j++ - } - b = append(b, "... "...) - b = strconv.AppendQuote(b, s[i:j]) - if j < n { - b = append(b, " +"...) - } - b = append(b, '\n') - i = j - } - c.writeLog(b) -} - -func isMultiLine(s string) bool { - for i := 0; i+1 < len(s); i++ { - if s[i] == '\n' { - return true - } - } - return false -} - -func (c *C) logString(issue string) { - c.log("... ", issue) -} - -func (c *C) logCaller(skip int) { - // This is a bit heavier than it ought to be. - skip++ // Our own frame. - pc, callerFile, callerLine, ok := runtime.Caller(skip) - if !ok { - return - } - var testFile string - var testLine int - testFunc := runtime.FuncForPC(c.method.PC()) - if runtime.FuncForPC(pc) != testFunc { - for { - skip++ - if pc, file, line, ok := runtime.Caller(skip); ok { - // Note that the test line may be different on - // distinct calls for the same test. Showing - // the "internal" line is helpful when debugging. - if runtime.FuncForPC(pc) == testFunc { - testFile, testLine = file, line - break - } - } else { - break - } - } - } - if testFile != "" && (testFile != callerFile || testLine != callerLine) { - c.logCode(testFile, testLine) - } - c.logCode(callerFile, callerLine) -} - -func (c *C) logCode(path string, line int) { - c.logf("%s:%d:", nicePath(path), line) - code, err := printLine(path, line) - if code == "" { - code = "..." // XXX Open the file and take the raw line. - if err != nil { - code += err.Error() - } - } - c.log(indent(code, " ")) -} - -var valueGo = filepath.Join("reflect", "value.go") -var asmGo = filepath.Join("runtime", "asm_") - -func (c *C) logPanic(skip int, value interface{}) { - skip++ // Our own frame. - initialSkip := skip - for ; ; skip++ { - if pc, file, line, ok := runtime.Caller(skip); ok { - if skip == initialSkip { - c.logf("... Panic: %s (PC=0x%X)\n", value, pc) - } - name := niceFuncName(pc) - path := nicePath(file) - if strings.Contains(path, "/gopkg.in/check.v") { - continue - } - if name == "Value.call" && strings.HasSuffix(path, valueGo) { - continue - } - if (name == "call16" || name == "call32") && strings.Contains(path, asmGo) { - continue - } - c.logf("%s:%d\n in %s", nicePath(file), line, name) - } else { - break - } - } -} - -func (c *C) logSoftPanic(issue string) { - c.log("... Panic: ", issue) -} - -func (c *C) logArgPanic(method *methodType, expectedType string) { - c.logf("... Panic: %s argument should be %s", - niceFuncName(method.PC()), expectedType) -} - -// ----------------------------------------------------------------------- -// Some simple formatting helpers. - -var initWD, initWDErr = os.Getwd() - -func init() { - if initWDErr == nil { - initWD = strings.Replace(initWD, "\\", "/", -1) + "/" - } -} - -func nicePath(path string) string { - if initWDErr == nil { - if strings.HasPrefix(path, initWD) { - return path[len(initWD):] - } - } - return path -} - -func niceFuncPath(pc uintptr) string { - function := runtime.FuncForPC(pc) - if function != nil { - filename, line := function.FileLine(pc) - return fmt.Sprintf("%s:%d", nicePath(filename), line) - } - return "" -} - -func niceFuncName(pc uintptr) string { - function := runtime.FuncForPC(pc) - if function != nil { - name := path.Base(function.Name()) - if i := strings.Index(name, "."); i > 0 { - name = name[i+1:] - } - if strings.HasPrefix(name, "(*") { - if i := strings.Index(name, ")"); i > 0 { - name = name[2:i] + name[i+1:] - } - } - if i := strings.LastIndex(name, ".*"); i != -1 { - name = name[:i] + "." + name[i+2:] - } - if i := strings.LastIndex(name, "·"); i != -1 { - name = name[:i] + "." + name[i+2:] - } - return name - } - return "" -} - -// ----------------------------------------------------------------------- -// Result tracker to aggregate call results. - -type Result struct { - Succeeded int - Failed int - Skipped int - Panicked int - FixturePanicked int - ExpectedFailures int - Missed int // Not even tried to run, related to a panic in the fixture. - RunError error // Houston, we've got a problem. - WorkDir string // If KeepWorkDir is true -} - -type resultTracker struct { - result Result - _lastWasProblem bool - _waiting int - _missed int - _expectChan chan *C - _doneChan chan *C - _stopChan chan bool -} - -func newResultTracker() *resultTracker { - return &resultTracker{_expectChan: make(chan *C), // Synchronous - _doneChan: make(chan *C, 32), // Asynchronous - _stopChan: make(chan bool)} // Synchronous -} - -func (tracker *resultTracker) start() { - go tracker._loopRoutine() -} - -func (tracker *resultTracker) waitAndStop() { - <-tracker._stopChan -} - -func (tracker *resultTracker) expectCall(c *C) { - tracker._expectChan <- c -} - -func (tracker *resultTracker) callDone(c *C) { - tracker._doneChan <- c -} - -func (tracker *resultTracker) _loopRoutine() { - for { - var c *C - if tracker._waiting > 0 { - // Calls still running. Can't stop. - select { - // XXX Reindent this (not now to make diff clear) - case <-tracker._expectChan: - tracker._waiting++ - case c = <-tracker._doneChan: - tracker._waiting-- - switch c.status() { - case succeededSt: - if c.kind == testKd { - if c.mustFail { - tracker.result.ExpectedFailures++ - } else { - tracker.result.Succeeded++ - } - } - case failedSt: - tracker.result.Failed++ - case panickedSt: - if c.kind == fixtureKd { - tracker.result.FixturePanicked++ - } else { - tracker.result.Panicked++ - } - case fixturePanickedSt: - // Track it as missed, since the panic - // was on the fixture, not on the test. - tracker.result.Missed++ - case missedSt: - tracker.result.Missed++ - case skippedSt: - if c.kind == testKd { - tracker.result.Skipped++ - } - } - } - } else { - // No calls. Can stop, but no done calls here. - select { - case tracker._stopChan <- true: - return - case <-tracker._expectChan: - tracker._waiting++ - case <-tracker._doneChan: - panic("Tracker got an unexpected done call.") - } - } - } -} - -// ----------------------------------------------------------------------- -// The underlying suite runner. - -type suiteRunner struct { - suite interface{} - setUpSuite, tearDownSuite *methodType - setUpTest, tearDownTest *methodType - tests []*methodType - tracker *resultTracker - tempDir *tempDir - keepDir bool - output *outputWriter - reportedProblemLast bool - benchTime time.Duration - benchMem bool - abort bool -} - -type RunConf struct { - Output io.Writer - Stream bool - Verbose bool - Filter string - Benchmark bool - BenchmarkTime time.Duration // Defaults to 1 second - BenchmarkMem bool - KeepWorkDir bool - Abort bool -} - -// Create a new suiteRunner able to run all methods in the given suite. -func newSuiteRunner(suite interface{}, runConf *RunConf) *suiteRunner { - var conf RunConf - if runConf != nil { - conf = *runConf - } - if conf.Output == nil { - conf.Output = os.Stdout - } - if conf.Benchmark { - conf.Verbose = true - } - - suiteType := reflect.TypeOf(suite) - suiteNumMethods := suiteType.NumMethod() - suiteValue := reflect.ValueOf(suite) - - runner := &suiteRunner{ - suite: suite, - output: newOutputWriter(conf.Output, conf.Stream, conf.Verbose), - tracker: newResultTracker(), - benchTime: conf.BenchmarkTime, - benchMem: conf.BenchmarkMem, - tempDir: &tempDir{}, - keepDir: conf.KeepWorkDir, - tests: make([]*methodType, 0, suiteNumMethods), - abort: conf.Abort, - } - if runner.benchTime == 0 { - runner.benchTime = 1 * time.Second - } - - var filterRegexp *regexp.Regexp - if conf.Filter != "" { - regexp, err := regexp.Compile(conf.Filter) - if err != nil { - msg := "Bad filter expression: " + err.Error() - runner.tracker.result.RunError = errors.New(msg) - return runner - } - filterRegexp = regexp - } - - for i := 0; i != suiteNumMethods; i++ { - method := newMethod(suiteValue, i) - switch method.Info.Name { - case "SetUpSuite": - runner.setUpSuite = method - case "TearDownSuite": - runner.tearDownSuite = method - case "SetUpTest": - runner.setUpTest = method - case "TearDownTest": - runner.tearDownTest = method - default: - prefix := "Test" - if conf.Benchmark { - prefix = "Benchmark" - } - if !strings.HasPrefix(method.Info.Name, prefix) { - continue - } - if filterRegexp == nil || method.matches(filterRegexp) { - runner.tests = append(runner.tests, method) - } - } - } - return runner -} - -// Run all methods in the given suite. -func (runner *suiteRunner) run() *Result { - if runner.tracker.result.RunError == nil && len(runner.tests) > 0 { - runner.tracker.start() - if runner.checkFixtureArgs() { - c := runner.runFixture(runner.setUpSuite, "", nil) - if c == nil || c.status() == succeededSt { - for i := 0; i != len(runner.tests); i++ { - c := runner.runTest(runner.tests[i]) - status := c.status() - if status == fixturePanickedSt || runner.abort && - (status == failedSt || status == panickedSt) { - runner.skipTests(missedSt, runner.tests[i+1:]) - break - } - } - } else if c != nil && c.status() == skippedSt { - runner.skipTests(skippedSt, runner.tests) - } else { - runner.skipTests(missedSt, runner.tests) - } - runner.runFixture(runner.tearDownSuite, "", nil) - } else { - runner.skipTests(missedSt, runner.tests) - } - runner.tracker.waitAndStop() - if runner.keepDir { - runner.tracker.result.WorkDir = runner.tempDir.path - } else { - runner.tempDir.removeAll() - } - } - return &runner.tracker.result -} - -// Skip all methods in the given suite. -func (runner *suiteRunner) skip() *Result { - if runner.tracker.result.RunError == nil && len(runner.tests) > 0 { - runner.tracker.start() - runner.skipTests(missedSt, runner.tests) - runner.tracker.waitAndStop() - } - return &runner.tracker.result -} - -// Create a call object with the given suite method, and fork a -// goroutine with the provided dispatcher for running it. -func (runner *suiteRunner) forkCall(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { - var logw io.Writer - if runner.output.Stream { - logw = runner.output - } - if logb == nil { - logb = new(logger) - } - c := &C{ - method: method, - kind: kind, - testName: testName, - logb: logb, - logw: logw, - tempDir: runner.tempDir, - done: make(chan *C, 1), - timer: timer{benchTime: runner.benchTime}, - startTime: time.Now(), - benchMem: runner.benchMem, - } - runner.tracker.expectCall(c) - go (func() { - runner.reportCallStarted(c) - defer runner.callDone(c) - dispatcher(c) - })() - return c -} - -// Same as forkCall(), but wait for call to finish before returning. -func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C { - c := runner.forkCall(method, kind, testName, logb, dispatcher) - <-c.done - return c -} - -// Handle a finished call. If there were any panics, update the call status -// accordingly. Then, mark the call as done and report to the tracker. -func (runner *suiteRunner) callDone(c *C) { - value := recover() - if value != nil { - switch v := value.(type) { - case *fixturePanic: - if v.status == skippedSt { - c.setStatus(skippedSt) - } else { - c.logSoftPanic("Fixture has panicked (see related PANIC)") - c.setStatus(fixturePanickedSt) - } - default: - c.logPanic(1, value) - c.setStatus(panickedSt) - } - } - if c.mustFail { - switch c.status() { - case failedSt: - c.setStatus(succeededSt) - case succeededSt: - c.setStatus(failedSt) - c.logString("Error: Test succeeded, but was expected to fail") - c.logString("Reason: " + c.reason) - } - } - - runner.reportCallDone(c) - c.done <- c -} - -// Runs a fixture call synchronously. The fixture will still be run in a -// goroutine like all suite methods, but this method will not return -// while the fixture goroutine is not done, because the fixture must be -// run in a desired order. -func (runner *suiteRunner) runFixture(method *methodType, testName string, logb *logger) *C { - if method != nil { - c := runner.runFunc(method, fixtureKd, testName, logb, func(c *C) { - c.ResetTimer() - c.StartTimer() - defer c.StopTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - }) - return c - } - return nil -} - -// Run the fixture method with runFixture(), but panic with a fixturePanic{} -// in case the fixture method panics. This makes it easier to track the -// fixture panic together with other call panics within forkTest(). -func (runner *suiteRunner) runFixtureWithPanic(method *methodType, testName string, logb *logger, skipped *bool) *C { - if skipped != nil && *skipped { - return nil - } - c := runner.runFixture(method, testName, logb) - if c != nil && c.status() != succeededSt { - if skipped != nil { - *skipped = c.status() == skippedSt - } - panic(&fixturePanic{c.status(), method}) - } - return c -} - -type fixturePanic struct { - status funcStatus - method *methodType -} - -// Run the suite test method, together with the test-specific fixture, -// asynchronously. -func (runner *suiteRunner) forkTest(method *methodType) *C { - testName := method.String() - return runner.forkCall(method, testKd, testName, nil, func(c *C) { - var skipped bool - defer runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, &skipped) - defer c.StopTimer() - benchN := 1 - for { - runner.runFixtureWithPanic(runner.setUpTest, testName, c.logb, &skipped) - mt := c.method.Type() - if mt.NumIn() != 1 || mt.In(0) != reflect.TypeOf(c) { - // Rather than a plain panic, provide a more helpful message when - // the argument type is incorrect. - c.setStatus(panickedSt) - c.logArgPanic(c.method, "*check.C") - return - } - if strings.HasPrefix(c.method.Info.Name, "Test") { - c.ResetTimer() - c.StartTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - return - } - if !strings.HasPrefix(c.method.Info.Name, "Benchmark") { - panic("unexpected method prefix: " + c.method.Info.Name) - } - - runtime.GC() - c.N = benchN - c.ResetTimer() - c.StartTimer() - c.method.Call([]reflect.Value{reflect.ValueOf(c)}) - c.StopTimer() - if c.status() != succeededSt || c.duration >= c.benchTime || benchN >= 1e9 { - return - } - perOpN := int(1e9) - if c.nsPerOp() != 0 { - perOpN = int(c.benchTime.Nanoseconds() / c.nsPerOp()) - } - - // Logic taken from the stock testing package: - // - Run more iterations than we think we'll need for a second (1.5x). - // - Don't grow too fast in case we had timing errors previously. - // - Be sure to run at least one more than last time. - benchN = max(min(perOpN+perOpN/2, 100*benchN), benchN+1) - benchN = roundUp(benchN) - - skipped = true // Don't run the deferred one if this panics. - runner.runFixtureWithPanic(runner.tearDownTest, testName, nil, nil) - skipped = false - } - }) -} - -// Same as forkTest(), but wait for the test to finish before returning. -func (runner *suiteRunner) runTest(method *methodType) *C { - c := runner.forkTest(method) - <-c.done - return c -} - -// Helper to mark tests as skipped or missed. A bit heavy for what -// it does, but it enables homogeneous handling of tracking, including -// nice verbose output. -func (runner *suiteRunner) skipTests(status funcStatus, methods []*methodType) { - for _, method := range methods { - runner.runFunc(method, testKd, "", nil, func(c *C) { - c.setStatus(status) - }) - } -} - -// Verify if the fixture arguments are *check.C. In case of errors, -// log the error as a panic in the fixture method call, and return false. -func (runner *suiteRunner) checkFixtureArgs() bool { - succeeded := true - argType := reflect.TypeOf(&C{}) - for _, method := range []*methodType{runner.setUpSuite, runner.tearDownSuite, runner.setUpTest, runner.tearDownTest} { - if method != nil { - mt := method.Type() - if mt.NumIn() != 1 || mt.In(0) != argType { - succeeded = false - runner.runFunc(method, fixtureKd, "", nil, func(c *C) { - c.logArgPanic(method, "*check.C") - c.setStatus(panickedSt) - }) - } - } - } - return succeeded -} - -func (runner *suiteRunner) reportCallStarted(c *C) { - runner.output.WriteCallStarted("START", c) -} - -func (runner *suiteRunner) reportCallDone(c *C) { - runner.tracker.callDone(c) - switch c.status() { - case succeededSt: - if c.mustFail { - runner.output.WriteCallSuccess("FAIL EXPECTED", c) - } else { - runner.output.WriteCallSuccess("PASS", c) - } - case skippedSt: - runner.output.WriteCallSuccess("SKIP", c) - case failedSt: - runner.output.WriteCallProblem("FAIL", c) - case panickedSt: - runner.output.WriteCallProblem("PANIC", c) - case fixturePanickedSt: - // That's a testKd call reporting that its fixture - // has panicked. The fixture call which caused the - // panic itself was tracked above. We'll report to - // aid debugging. - runner.output.WriteCallProblem("PANIC", c) - case missedSt: - runner.output.WriteCallSuccess("MISS", c) - } -} diff --git a/vendor/github.com/go-check/check/checkers.go b/vendor/github.com/go-check/check/checkers.go deleted file mode 100644 index 06608adf6..000000000 --- a/vendor/github.com/go-check/check/checkers.go +++ /dev/null @@ -1,461 +0,0 @@ -package check - -import ( - "fmt" - "reflect" - "regexp" -) - -// ----------------------------------------------------------------------- -// CommentInterface and Commentf helper, to attach extra information to checks. - -type comment struct { - format string - args []interface{} -} - -// Commentf returns an infomational value to use with Assert or Check calls. -// If the checker test fails, the provided arguments will be passed to -// fmt.Sprintf, and will be presented next to the logged failure. -// -// For example: -// -// c.Assert(v, Equals, 42, Commentf("Iteration #%d failed.", i)) -// -// Note that if the comment is constant, a better option is to -// simply use a normal comment right above or next to the line, as -// it will also get printed with any errors: -// -// c.Assert(l, Equals, 8192) // Ensure buffer size is correct (bug #123) -// -func Commentf(format string, args ...interface{}) CommentInterface { - return &comment{format, args} -} - -// CommentInterface must be implemented by types that attach extra -// information to failed checks. See the Commentf function for details. -type CommentInterface interface { - CheckCommentString() string -} - -func (c *comment) CheckCommentString() string { - return fmt.Sprintf(c.format, c.args...) -} - -// ----------------------------------------------------------------------- -// The Checker interface. - -// The Checker interface must be provided by checkers used with -// the Assert and Check verification methods. -type Checker interface { - Info() *CheckerInfo - Check(params []interface{}, names []string) (result bool, error string) -} - -// See the Checker interface. -type CheckerInfo struct { - Name string - Params []string -} - -func (info *CheckerInfo) Info() *CheckerInfo { - return info -} - -// ----------------------------------------------------------------------- -// Not checker logic inverter. - -// The Not checker inverts the logic of the provided checker. The -// resulting checker will succeed where the original one failed, and -// vice-versa. -// -// For example: -// -// c.Assert(a, Not(Equals), b) -// -func Not(checker Checker) Checker { - return ¬Checker{checker} -} - -type notChecker struct { - sub Checker -} - -func (checker *notChecker) Info() *CheckerInfo { - info := *checker.sub.Info() - info.Name = "Not(" + info.Name + ")" - return &info -} - -func (checker *notChecker) Check(params []interface{}, names []string) (result bool, error string) { - result, _ = checker.sub.Check(params, names) - result = !result - return -} - -// ----------------------------------------------------------------------- -// IsNil checker. - -type isNilChecker struct { - *CheckerInfo -} - -// The IsNil checker tests whether the obtained value is nil. -// -// For example: -// -// c.Assert(err, IsNil) -// -var IsNil Checker = &isNilChecker{ - &CheckerInfo{Name: "IsNil", Params: []string{"value"}}, -} - -func (checker *isNilChecker) Check(params []interface{}, names []string) (result bool, error string) { - return isNil(params[0]), "" -} - -func isNil(obtained interface{}) (result bool) { - if obtained == nil { - result = true - } else { - switch v := reflect.ValueOf(obtained); v.Kind() { - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: - return v.IsNil() - } - } - return -} - -// ----------------------------------------------------------------------- -// NotNil checker. Alias for Not(IsNil), since it's so common. - -type notNilChecker struct { - *CheckerInfo -} - -// The NotNil checker verifies that the obtained value is not nil. -// -// For example: -// -// c.Assert(iface, NotNil) -// -// This is an alias for Not(IsNil), made available since it's a -// fairly common check. -// -var NotNil Checker = ¬NilChecker{ - &CheckerInfo{Name: "NotNil", Params: []string{"value"}}, -} - -func (checker *notNilChecker) Check(params []interface{}, names []string) (result bool, error string) { - return !isNil(params[0]), "" -} - -// ----------------------------------------------------------------------- -// Equals checker. - -type equalsChecker struct { - *CheckerInfo -} - -// The Equals checker verifies that the obtained value is equal to -// the expected value, according to usual Go semantics for ==. -// -// For example: -// -// c.Assert(value, Equals, 42) -// -var Equals Checker = &equalsChecker{ - &CheckerInfo{Name: "Equals", Params: []string{"obtained", "expected"}}, -} - -func (checker *equalsChecker) Check(params []interface{}, names []string) (result bool, error string) { - defer func() { - if v := recover(); v != nil { - result = false - error = fmt.Sprint(v) - } - }() - return params[0] == params[1], "" -} - -// ----------------------------------------------------------------------- -// DeepEquals checker. - -type deepEqualsChecker struct { - *CheckerInfo -} - -// The DeepEquals checker verifies that the obtained value is deep-equal to -// the expected value. The check will work correctly even when facing -// slices, interfaces, and values of different types (which always fail -// the test). -// -// For example: -// -// c.Assert(value, DeepEquals, 42) -// c.Assert(array, DeepEquals, []string{"hi", "there"}) -// -var DeepEquals Checker = &deepEqualsChecker{ - &CheckerInfo{Name: "DeepEquals", Params: []string{"obtained", "expected"}}, -} - -func (checker *deepEqualsChecker) Check(params []interface{}, names []string) (result bool, error string) { - return reflect.DeepEqual(params[0], params[1]), "" -} - -// ----------------------------------------------------------------------- -// HasLen checker. - -type hasLenChecker struct { - *CheckerInfo -} - -// The HasLen checker verifies that the obtained value has the -// provided length. In many cases this is superior to using Equals -// in conjunction with the len function because in case the check -// fails the value itself will be printed, instead of its length, -// providing more details for figuring the problem. -// -// For example: -// -// c.Assert(list, HasLen, 5) -// -var HasLen Checker = &hasLenChecker{ - &CheckerInfo{Name: "HasLen", Params: []string{"obtained", "n"}}, -} - -func (checker *hasLenChecker) Check(params []interface{}, names []string) (result bool, error string) { - n, ok := params[1].(int) - if !ok { - return false, "n must be an int" - } - value := reflect.ValueOf(params[0]) - switch value.Kind() { - case reflect.Map, reflect.Array, reflect.Slice, reflect.Chan, reflect.String: - default: - return false, "obtained value type has no length" - } - if value.Len() == n { - return true, "" - } - return false, fmt.Sprintf("obtained length = %d", value.Len()) -} - -// ----------------------------------------------------------------------- -// ErrorMatches checker. - -type errorMatchesChecker struct { - *CheckerInfo -} - -// The ErrorMatches checker verifies that the error value -// is non nil and matches the regular expression provided. -// -// For example: -// -// c.Assert(err, ErrorMatches, "perm.*denied") -// -var ErrorMatches Checker = errorMatchesChecker{ - &CheckerInfo{Name: "ErrorMatches", Params: []string{"value", "regex"}}, -} - -func (checker errorMatchesChecker) Check(params []interface{}, names []string) (result bool, errStr string) { - if params[0] == nil { - return false, "Error value is nil" - } - err, ok := params[0].(error) - if !ok { - return false, "Value is not an error" - } - params[0] = err.Error() - names[0] = "error" - return matches(params[0], params[1]) -} - -// ----------------------------------------------------------------------- -// Matches checker. - -type matchesChecker struct { - *CheckerInfo -} - -// The Matches checker verifies that the string provided as the obtained -// value (or the string resulting from obtained.String()) matches the -// regular expression provided. -// -// For example: -// -// c.Assert(err, Matches, "perm.*denied") -// -var Matches Checker = &matchesChecker{ - &CheckerInfo{Name: "Matches", Params: []string{"value", "regex"}}, -} - -func (checker *matchesChecker) Check(params []interface{}, names []string) (result bool, error string) { - return matches(params[0], params[1]) -} - -func matches(value, regex interface{}) (result bool, error string) { - reStr, ok := regex.(string) - if !ok { - return false, "Regex must be a string" - } - valueStr, valueIsStr := value.(string) - if !valueIsStr { - if valueWithStr, valueHasStr := value.(fmt.Stringer); valueHasStr { - valueStr, valueIsStr = valueWithStr.String(), true - } - } - if valueIsStr { - matches, err := regexp.MatchString("^"+reStr+"$", valueStr) - if err != nil { - return false, "Can't compile regex: " + err.Error() - } - return matches, "" - } - return false, "Obtained value is not a string and has no .String()" -} - -// ----------------------------------------------------------------------- -// Panics checker. - -type panicsChecker struct { - *CheckerInfo -} - -// The Panics checker verifies that calling the provided zero-argument -// function will cause a panic which is deep-equal to the provided value. -// -// For example: -// -// c.Assert(func() { f(1, 2) }, Panics, &SomeErrorType{"BOOM"}). -// -// -var Panics Checker = &panicsChecker{ - &CheckerInfo{Name: "Panics", Params: []string{"function", "expected"}}, -} - -func (checker *panicsChecker) Check(params []interface{}, names []string) (result bool, error string) { - f := reflect.ValueOf(params[0]) - if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { - return false, "Function must take zero arguments" - } - defer func() { - // If the function has not panicked, then don't do the check. - if error != "" { - return - } - params[0] = recover() - names[0] = "panic" - result = reflect.DeepEqual(params[0], params[1]) - }() - f.Call(nil) - return false, "Function has not panicked" -} - -type panicMatchesChecker struct { - *CheckerInfo -} - -// The PanicMatches checker verifies that calling the provided zero-argument -// function will cause a panic with an error value matching -// the regular expression provided. -// -// For example: -// -// c.Assert(func() { f(1, 2) }, PanicMatches, `open.*: no such file or directory`). -// -// -var PanicMatches Checker = &panicMatchesChecker{ - &CheckerInfo{Name: "PanicMatches", Params: []string{"function", "expected"}}, -} - -func (checker *panicMatchesChecker) Check(params []interface{}, names []string) (result bool, errmsg string) { - f := reflect.ValueOf(params[0]) - if f.Kind() != reflect.Func || f.Type().NumIn() != 0 { - return false, "Function must take zero arguments" - } - defer func() { - // If the function has not panicked, then don't do the check. - if errmsg != "" { - return - } - obtained := recover() - names[0] = "panic" - if e, ok := obtained.(error); ok { - params[0] = e.Error() - } else if _, ok := obtained.(string); ok { - params[0] = obtained - } else { - errmsg = "Panic value is not a string or an error" - return - } - result, errmsg = matches(params[0], params[1]) - }() - f.Call(nil) - return false, "Function has not panicked" -} - -// ----------------------------------------------------------------------- -// FitsTypeOf checker. - -type fitsTypeChecker struct { - *CheckerInfo -} - -// The FitsTypeOf checker verifies that the obtained value is -// assignable to a variable with the same type as the provided -// sample value. -// -// For example: -// -// c.Assert(value, FitsTypeOf, int64(0)) -// c.Assert(value, FitsTypeOf, os.Error(nil)) -// -var FitsTypeOf Checker = &fitsTypeChecker{ - &CheckerInfo{Name: "FitsTypeOf", Params: []string{"obtained", "sample"}}, -} - -func (checker *fitsTypeChecker) Check(params []interface{}, names []string) (result bool, error string) { - obtained := reflect.ValueOf(params[0]) - sample := reflect.ValueOf(params[1]) - if !obtained.IsValid() { - return false, "" - } - if !sample.IsValid() { - return false, "Invalid sample value" - } - return obtained.Type().AssignableTo(sample.Type()), "" -} - -// ----------------------------------------------------------------------- -// Implements checker. - -type implementsChecker struct { - *CheckerInfo -} - -// The Implements checker verifies that the obtained value -// implements the interface specified via a pointer to an interface -// variable. -// -// For example: -// -// var e os.Error -// c.Assert(err, Implements, &e) -// -var Implements Checker = &implementsChecker{ - &CheckerInfo{Name: "Implements", Params: []string{"obtained", "ifaceptr"}}, -} - -func (checker *implementsChecker) Check(params []interface{}, names []string) (result bool, error string) { - obtained := reflect.ValueOf(params[0]) - ifaceptr := reflect.ValueOf(params[1]) - if !obtained.IsValid() { - return false, "" - } - if !ifaceptr.IsValid() || ifaceptr.Kind() != reflect.Ptr || ifaceptr.Elem().Kind() != reflect.Interface { - return false, "ifaceptr should be a pointer to an interface variable" - } - return obtained.Type().Implements(ifaceptr.Elem().Type()), "" -} diff --git a/vendor/github.com/go-check/check/helpers.go b/vendor/github.com/go-check/check/helpers.go deleted file mode 100644 index 52dc0823a..000000000 --- a/vendor/github.com/go-check/check/helpers.go +++ /dev/null @@ -1,231 +0,0 @@ -package check - -import ( - "fmt" - "strings" - "time" -) - -// TestName returns the current test name in the form "SuiteName.TestName" -func (c *C) TestName() string { - return c.testName -} - -// ----------------------------------------------------------------------- -// Basic succeeding/failing logic. - -// Failed returns whether the currently running test has already failed. -func (c *C) Failed() bool { - return c.status() == failedSt -} - -// Fail marks the currently running test as failed. -// -// Something ought to have been previously logged so the developer can tell -// what went wrong. The higher level helper functions will fail the test -// and do the logging properly. -func (c *C) Fail() { - c.setStatus(failedSt) -} - -// FailNow marks the currently running test as failed and stops running it. -// Something ought to have been previously logged so the developer can tell -// what went wrong. The higher level helper functions will fail the test -// and do the logging properly. -func (c *C) FailNow() { - c.Fail() - c.stopNow() -} - -// Succeed marks the currently running test as succeeded, undoing any -// previous failures. -func (c *C) Succeed() { - c.setStatus(succeededSt) -} - -// SucceedNow marks the currently running test as succeeded, undoing any -// previous failures, and stops running the test. -func (c *C) SucceedNow() { - c.Succeed() - c.stopNow() -} - -// ExpectFailure informs that the running test is knowingly broken for -// the provided reason. If the test does not fail, an error will be reported -// to raise attention to this fact. This method is useful to temporarily -// disable tests which cover well known problems until a better time to -// fix the problem is found, without forgetting about the fact that a -// failure still exists. -func (c *C) ExpectFailure(reason string) { - if reason == "" { - panic("Missing reason why the test is expected to fail") - } - c.mustFail = true - c.reason = reason -} - -// Skip skips the running test for the provided reason. If run from within -// SetUpTest, the individual test being set up will be skipped, and if run -// from within SetUpSuite, the whole suite is skipped. -func (c *C) Skip(reason string) { - if reason == "" { - panic("Missing reason why the test is being skipped") - } - c.reason = reason - c.setStatus(skippedSt) - c.stopNow() -} - -// ----------------------------------------------------------------------- -// Basic logging. - -// GetTestLog returns the current test error output. -func (c *C) GetTestLog() string { - return c.logb.String() -} - -// Log logs some information into the test error output. -// The provided arguments are assembled together into a string with fmt.Sprint. -func (c *C) Log(args ...interface{}) { - c.log(args...) -} - -// Log logs some information into the test error output. -// The provided arguments are assembled together into a string with fmt.Sprintf. -func (c *C) Logf(format string, args ...interface{}) { - c.logf(format, args...) -} - -// Output enables *C to be used as a logger in functions that require only -// the minimum interface of *log.Logger. -func (c *C) Output(calldepth int, s string) error { - d := time.Now().Sub(c.startTime) - msec := d / time.Millisecond - sec := d / time.Second - min := d / time.Minute - - c.Logf("[LOG] %d:%02d.%03d %s", min, sec%60, msec%1000, s) - return nil -} - -// Error logs an error into the test error output and marks the test as failed. -// The provided arguments are assembled together into a string with fmt.Sprint. -func (c *C) Error(args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) - c.logNewLine() - c.Fail() -} - -// Errorf logs an error into the test error output and marks the test as failed. -// The provided arguments are assembled together into a string with fmt.Sprintf. -func (c *C) Errorf(format string, args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprintf("Error: "+format, args...)) - c.logNewLine() - c.Fail() -} - -// Fatal logs an error into the test error output, marks the test as failed, and -// stops the test execution. The provided arguments are assembled together into -// a string with fmt.Sprint. -func (c *C) Fatal(args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprint(args...))) - c.logNewLine() - c.FailNow() -} - -// Fatlaf logs an error into the test error output, marks the test as failed, and -// stops the test execution. The provided arguments are assembled together into -// a string with fmt.Sprintf. -func (c *C) Fatalf(format string, args ...interface{}) { - c.logCaller(1) - c.logString(fmt.Sprint("Error: ", fmt.Sprintf(format, args...))) - c.logNewLine() - c.FailNow() -} - -// ----------------------------------------------------------------------- -// Generic checks and assertions based on checkers. - -// Check verifies if the first value matches the expected value according -// to the provided checker. If they do not match, an error is logged, the -// test is marked as failed, and the test execution continues. -// -// Some checkers may not need the expected argument (e.g. IsNil). -// -// Extra arguments provided to the function are logged next to the reported -// problem when the matching fails. -func (c *C) Check(obtained interface{}, checker Checker, args ...interface{}) bool { - return c.internalCheck("Check", obtained, checker, args...) -} - -// Assert ensures that the first value matches the expected value according -// to the provided checker. If they do not match, an error is logged, the -// test is marked as failed, and the test execution stops. -// -// Some checkers may not need the expected argument (e.g. IsNil). -// -// Extra arguments provided to the function are logged next to the reported -// problem when the matching fails. -func (c *C) Assert(obtained interface{}, checker Checker, args ...interface{}) { - if !c.internalCheck("Assert", obtained, checker, args...) { - c.stopNow() - } -} - -func (c *C) internalCheck(funcName string, obtained interface{}, checker Checker, args ...interface{}) bool { - if checker == nil { - c.logCaller(2) - c.logString(fmt.Sprintf("%s(obtained, nil!?, ...):", funcName)) - c.logString("Oops.. you've provided a nil checker!") - c.logNewLine() - c.Fail() - return false - } - - // If the last argument is a bug info, extract it out. - var comment CommentInterface - if len(args) > 0 { - if c, ok := args[len(args)-1].(CommentInterface); ok { - comment = c - args = args[:len(args)-1] - } - } - - params := append([]interface{}{obtained}, args...) - info := checker.Info() - - if len(params) != len(info.Params) { - names := append([]string{info.Params[0], info.Name}, info.Params[1:]...) - c.logCaller(2) - c.logString(fmt.Sprintf("%s(%s):", funcName, strings.Join(names, ", "))) - c.logString(fmt.Sprintf("Wrong number of parameters for %s: want %d, got %d", info.Name, len(names), len(params)+1)) - c.logNewLine() - c.Fail() - return false - } - - // Copy since it may be mutated by Check. - names := append([]string{}, info.Params...) - - // Do the actual check. - result, error := checker.Check(params, names) - if !result { - c.logCaller(2) - for i := 0; i != len(params); i++ { - c.logValue(names[i], params[i]) - } - if comment != nil { - c.logString(comment.CheckCommentString()) - } - if error != "" { - c.logString(error) - } - c.logNewLine() - c.Fail() - return false - } - return true -} diff --git a/vendor/github.com/go-check/check/printer.go b/vendor/github.com/go-check/check/printer.go deleted file mode 100644 index e0f7557b5..000000000 --- a/vendor/github.com/go-check/check/printer.go +++ /dev/null @@ -1,168 +0,0 @@ -package check - -import ( - "bytes" - "go/ast" - "go/parser" - "go/printer" - "go/token" - "os" -) - -func indent(s, with string) (r string) { - eol := true - for i := 0; i != len(s); i++ { - c := s[i] - switch { - case eol && c == '\n' || c == '\r': - case c == '\n' || c == '\r': - eol = true - case eol: - eol = false - s = s[:i] + with + s[i:] - i += len(with) - } - } - return s -} - -func printLine(filename string, line int) (string, error) { - fset := token.NewFileSet() - file, err := os.Open(filename) - if err != nil { - return "", err - } - fnode, err := parser.ParseFile(fset, filename, file, parser.ParseComments) - if err != nil { - return "", err - } - config := &printer.Config{Mode: printer.UseSpaces, Tabwidth: 4} - lp := &linePrinter{fset: fset, fnode: fnode, line: line, config: config} - ast.Walk(lp, fnode) - result := lp.output.Bytes() - // Comments leave \n at the end. - n := len(result) - for n > 0 && result[n-1] == '\n' { - n-- - } - return string(result[:n]), nil -} - -type linePrinter struct { - config *printer.Config - fset *token.FileSet - fnode *ast.File - line int - output bytes.Buffer - stmt ast.Stmt -} - -func (lp *linePrinter) emit() bool { - if lp.stmt != nil { - lp.trim(lp.stmt) - lp.printWithComments(lp.stmt) - lp.stmt = nil - return true - } - return false -} - -func (lp *linePrinter) printWithComments(n ast.Node) { - nfirst := lp.fset.Position(n.Pos()).Line - nlast := lp.fset.Position(n.End()).Line - for _, g := range lp.fnode.Comments { - cfirst := lp.fset.Position(g.Pos()).Line - clast := lp.fset.Position(g.End()).Line - if clast == nfirst-1 && lp.fset.Position(n.Pos()).Column == lp.fset.Position(g.Pos()).Column { - for _, c := range g.List { - lp.output.WriteString(c.Text) - lp.output.WriteByte('\n') - } - } - if cfirst >= nfirst && cfirst <= nlast && n.End() <= g.List[0].Slash { - // The printer will not include the comment if it starts past - // the node itself. Trick it into printing by overlapping the - // slash with the end of the statement. - g.List[0].Slash = n.End() - 1 - } - } - node := &printer.CommentedNode{n, lp.fnode.Comments} - lp.config.Fprint(&lp.output, lp.fset, node) -} - -func (lp *linePrinter) Visit(n ast.Node) (w ast.Visitor) { - if n == nil { - if lp.output.Len() == 0 { - lp.emit() - } - return nil - } - first := lp.fset.Position(n.Pos()).Line - last := lp.fset.Position(n.End()).Line - if first <= lp.line && last >= lp.line { - // Print the innermost statement containing the line. - if stmt, ok := n.(ast.Stmt); ok { - if _, ok := n.(*ast.BlockStmt); !ok { - lp.stmt = stmt - } - } - if first == lp.line && lp.emit() { - return nil - } - return lp - } - return nil -} - -func (lp *linePrinter) trim(n ast.Node) bool { - stmt, ok := n.(ast.Stmt) - if !ok { - return true - } - line := lp.fset.Position(n.Pos()).Line - if line != lp.line { - return false - } - switch stmt := stmt.(type) { - case *ast.IfStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.SwitchStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.TypeSwitchStmt: - stmt.Body = lp.trimBlock(stmt.Body) - case *ast.CaseClause: - stmt.Body = lp.trimList(stmt.Body) - case *ast.CommClause: - stmt.Body = lp.trimList(stmt.Body) - case *ast.BlockStmt: - stmt.List = lp.trimList(stmt.List) - } - return true -} - -func (lp *linePrinter) trimBlock(stmt *ast.BlockStmt) *ast.BlockStmt { - if !lp.trim(stmt) { - return lp.emptyBlock(stmt) - } - stmt.Rbrace = stmt.Lbrace - return stmt -} - -func (lp *linePrinter) trimList(stmts []ast.Stmt) []ast.Stmt { - for i := 0; i != len(stmts); i++ { - if !lp.trim(stmts[i]) { - stmts[i] = lp.emptyStmt(stmts[i]) - break - } - } - return stmts -} - -func (lp *linePrinter) emptyStmt(n ast.Node) *ast.ExprStmt { - return &ast.ExprStmt{&ast.Ellipsis{n.Pos(), nil}} -} - -func (lp *linePrinter) emptyBlock(n ast.Node) *ast.BlockStmt { - p := n.Pos() - return &ast.BlockStmt{p, []ast.Stmt{lp.emptyStmt(n)}, p} -} diff --git a/vendor/github.com/go-check/check/reporter.go b/vendor/github.com/go-check/check/reporter.go deleted file mode 100644 index fb04f76f6..000000000 --- a/vendor/github.com/go-check/check/reporter.go +++ /dev/null @@ -1,88 +0,0 @@ -package check - -import ( - "fmt" - "io" - "sync" -) - -// ----------------------------------------------------------------------- -// Output writer manages atomic output writing according to settings. - -type outputWriter struct { - m sync.Mutex - writer io.Writer - wroteCallProblemLast bool - Stream bool - Verbose bool -} - -func newOutputWriter(writer io.Writer, stream, verbose bool) *outputWriter { - return &outputWriter{writer: writer, Stream: stream, Verbose: verbose} -} - -func (ow *outputWriter) Write(content []byte) (n int, err error) { - ow.m.Lock() - n, err = ow.writer.Write(content) - ow.m.Unlock() - return -} - -func (ow *outputWriter) WriteCallStarted(label string, c *C) { - if ow.Stream { - header := renderCallHeader(label, c, "", "\n") - ow.m.Lock() - ow.writer.Write([]byte(header)) - ow.m.Unlock() - } -} - -func (ow *outputWriter) WriteCallProblem(label string, c *C) { - var prefix string - if !ow.Stream { - prefix = "\n-----------------------------------" + - "-----------------------------------\n" - } - header := renderCallHeader(label, c, prefix, "\n\n") - ow.m.Lock() - ow.wroteCallProblemLast = true - ow.writer.Write([]byte(header)) - if !ow.Stream { - c.logb.WriteTo(ow.writer) - } - ow.m.Unlock() -} - -func (ow *outputWriter) WriteCallSuccess(label string, c *C) { - if ow.Stream || (ow.Verbose && c.kind == testKd) { - // TODO Use a buffer here. - var suffix string - if c.reason != "" { - suffix = " (" + c.reason + ")" - } - if c.status() == succeededSt { - suffix += "\t" + c.timerString() - } - suffix += "\n" - if ow.Stream { - suffix += "\n" - } - header := renderCallHeader(label, c, "", suffix) - ow.m.Lock() - // Resist temptation of using line as prefix above due to race. - if !ow.Stream && ow.wroteCallProblemLast { - header = "\n-----------------------------------" + - "-----------------------------------\n" + - header - } - ow.wroteCallProblemLast = false - ow.writer.Write([]byte(header)) - ow.m.Unlock() - } -} - -func renderCallHeader(label string, c *C, prefix, suffix string) string { - pc := c.method.PC() - return fmt.Sprintf("%s%s: %s: %s%s", prefix, label, niceFuncPath(pc), - niceFuncName(pc), suffix) -} diff --git a/vendor/github.com/go-check/check/run.go b/vendor/github.com/go-check/check/run.go deleted file mode 100644 index 2923e9490..000000000 --- a/vendor/github.com/go-check/check/run.go +++ /dev/null @@ -1,195 +0,0 @@ -package check - -import ( - "bufio" - "flag" - "fmt" - "os" - "testing" - "time" -) - -// ----------------------------------------------------------------------- -// Test suite registry. - -var allSuites []interface{} - -// Suite registers the given value as a test suite to be run. Any methods -// starting with the Test prefix in the given value will be considered as -// a test method. -func Suite(suite interface{}) interface{} { - allSuites = append(allSuites, suite) - return suite -} - -// ----------------------------------------------------------------------- -// Public running interface. - -var ( - oldFilterFlag = flag.String("gocheck.f", "", "Regular expression selecting which tests and/or suites to run") - oldVerboseFlag = flag.Bool("gocheck.v", false, "Verbose mode") - oldStreamFlag = flag.Bool("gocheck.vv", false, "Super verbose mode (disables output caching)") - oldBenchFlag = flag.Bool("gocheck.b", false, "Run benchmarks") - oldBenchTime = flag.Duration("gocheck.btime", 1*time.Second, "approximate run time for each benchmark") - oldListFlag = flag.Bool("gocheck.list", false, "List the names of all tests that will be run") - oldWorkFlag = flag.Bool("gocheck.work", false, "Display and do not remove the test working directory") - - newFilterFlag = flag.String("check.f", "", "Regular expression selecting which tests and/or suites to run") - newVerboseFlag = flag.Bool("check.v", false, "Verbose mode") - newStreamFlag = flag.Bool("check.vv", false, "Super verbose mode (disables output caching)") - newBenchFlag = flag.Bool("check.b", false, "Run benchmarks") - newBenchTime = flag.Duration("check.btime", 1*time.Second, "approximate run time for each benchmark") - newBenchMem = flag.Bool("check.bmem", false, "Report memory benchmarks") - newListFlag = flag.Bool("check.list", false, "List the names of all tests that will be run") - newWorkFlag = flag.Bool("check.work", false, "Display and do not remove the test working directory") - abort = flag.Bool("check.abort", true, "Stop testing the suite if a test has failed") -) - -// TestingT runs all test suites registered with the Suite function, -// printing results to stdout, and reporting any failures back to -// the "testing" package. -func TestingT(testingT *testing.T) { - benchTime := *newBenchTime - if benchTime == 1*time.Second { - benchTime = *oldBenchTime - } - conf := &RunConf{ - Filter: *oldFilterFlag + *newFilterFlag, - Verbose: *oldVerboseFlag || *newVerboseFlag, - Stream: *oldStreamFlag || *newStreamFlag, - Benchmark: *oldBenchFlag || *newBenchFlag, - BenchmarkTime: benchTime, - BenchmarkMem: *newBenchMem, - KeepWorkDir: *oldWorkFlag || *newWorkFlag, - Abort: *abort, - } - if *oldListFlag || *newListFlag { - w := bufio.NewWriter(os.Stdout) - for _, name := range ListAll(conf) { - fmt.Fprintln(w, name) - } - w.Flush() - return - } - result := RunAll(conf) - println(result.String()) - if !result.Passed() { - testingT.Fail() - } -} - -// RunAll runs all test suites registered with the Suite function, using the -// provided run configuration. -func RunAll(runConf *RunConf) *Result { - result := Result{} - skipTests := false - for _, suite := range allSuites { - var res *Result - if skipTests { - // Count missed tests. - res = skipSuite(suite, runConf) - } else { - res = Run(suite, runConf) - } - - result.Add(res) - if runConf.Abort && (res.Failed > 0 || res.Panicked > 0) { - skipTests = true - continue - } - } - return &result -} - -// Run runs the provided test suite using the provided run configuration. -func Run(suite interface{}, runConf *RunConf) *Result { - runner := newSuiteRunner(suite, runConf) - return runner.run() -} - -func skipSuite(suite interface{}, runConf *RunConf) *Result { - runner := newSuiteRunner(suite, runConf) - return runner.skip() -} - -// ListAll returns the names of all the test functions registered with the -// Suite function that will be run with the provided run configuration. -func ListAll(runConf *RunConf) []string { - var names []string - for _, suite := range allSuites { - names = append(names, List(suite, runConf)...) - } - return names -} - -// List returns the names of the test functions in the given -// suite that will be run with the provided run configuration. -func List(suite interface{}, runConf *RunConf) []string { - var names []string - runner := newSuiteRunner(suite, runConf) - for _, t := range runner.tests { - names = append(names, t.String()) - } - return names -} - -// ----------------------------------------------------------------------- -// Result methods. - -func (r *Result) Add(other *Result) { - r.Succeeded += other.Succeeded - r.Skipped += other.Skipped - r.Failed += other.Failed - r.Panicked += other.Panicked - r.FixturePanicked += other.FixturePanicked - r.ExpectedFailures += other.ExpectedFailures - r.Missed += other.Missed - if r.WorkDir != "" && other.WorkDir != "" { - r.WorkDir += ":" + other.WorkDir - } else if other.WorkDir != "" { - r.WorkDir = other.WorkDir - } -} - -func (r *Result) Passed() bool { - return (r.Failed == 0 && r.Panicked == 0 && - r.FixturePanicked == 0 && r.Missed == 0 && - r.RunError == nil) -} - -func (r *Result) String() string { - if r.RunError != nil { - return "ERROR: " + r.RunError.Error() - } - - var value string - if r.Failed == 0 && r.Panicked == 0 && r.FixturePanicked == 0 && - r.Missed == 0 { - value = "OK: " - } else { - value = "OOPS: " - } - value += fmt.Sprintf("%d passed", r.Succeeded) - if r.Skipped != 0 { - value += fmt.Sprintf(", %d skipped", r.Skipped) - } - if r.ExpectedFailures != 0 { - value += fmt.Sprintf(", %d expected failures", r.ExpectedFailures) - } - if r.Failed != 0 { - value += fmt.Sprintf(", %d FAILED", r.Failed) - } - if r.Panicked != 0 { - value += fmt.Sprintf(", %d PANICKED", r.Panicked) - } - if r.FixturePanicked != 0 { - value += fmt.Sprintf(", %d FIXTURE-PANICKED", r.FixturePanicked) - } - if r.Missed != 0 { - value += fmt.Sprintf(", %d MISSED", r.Missed) - } - if r.WorkDir != "" { - value += "\nWORK=" + r.WorkDir - } - return value -} diff --git a/vendor/github.com/go-errors/errors/LICENSE.MIT b/vendor/github.com/go-errors/errors/LICENSE.MIT deleted file mode 100644 index c9a5b2eeb..000000000 --- a/vendor/github.com/go-errors/errors/LICENSE.MIT +++ /dev/null @@ -1,7 +0,0 @@ -Copyright (c) 2015 Conrad Irwin - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/go-errors/errors/error.go b/vendor/github.com/go-errors/errors/error.go deleted file mode 100644 index 60062a437..000000000 --- a/vendor/github.com/go-errors/errors/error.go +++ /dev/null @@ -1,217 +0,0 @@ -// Package errors provides errors that have stack-traces. -// -// This is particularly useful when you want to understand the -// state of execution when an error was returned unexpectedly. -// -// It provides the type *Error which implements the standard -// golang error interface, so you can use this library interchangably -// with code that is expecting a normal error return. -// -// For example: -// -// package crashy -// -// import "github.com/go-errors/errors" -// -// var Crashed = errors.Errorf("oh dear") -// -// func Crash() error { -// return errors.New(Crashed) -// } -// -// This can be called as follows: -// -// package main -// -// import ( -// "crashy" -// "fmt" -// "github.com/go-errors/errors" -// ) -// -// func main() { -// err := crashy.Crash() -// if err != nil { -// if errors.Is(err, crashy.Crashed) { -// fmt.Println(err.(*errors.Error).ErrorStack()) -// } else { -// panic(err) -// } -// } -// } -// -// This package was original written to allow reporting to Bugsnag, -// but after I found similar packages by Facebook and Dropbox, it -// was moved to one canonical location so everyone can benefit. -package errors - -import ( - "bytes" - "fmt" - "reflect" - "runtime" -) - -// The maximum number of stackframes on any error. -var MaxStackDepth = 50 - -// Error is an error with an attached stacktrace. It can be used -// wherever the builtin error interface is expected. -type Error struct { - Err error - stack []uintptr - frames []StackFrame - prefix string -} - -// New makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The stacktrace will point to the line of code that -// called New. -func New(e interface{}) *Error { - var err error - - switch e := e.(type) { - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// Wrap makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The skip parameter indicates how far up the stack -// to start the stacktrace. 0 is from the current call, 1 from its caller, etc. -func Wrap(e interface{}, skip int) *Error { - var err error - - switch e := e.(type) { - case *Error: - return e - case error: - err = e - default: - err = fmt.Errorf("%v", e) - } - - stack := make([]uintptr, MaxStackDepth) - length := runtime.Callers(2+skip, stack[:]) - return &Error{ - Err: err, - stack: stack[:length], - } -} - -// WrapPrefix makes an Error from the given value. If that value is already an -// error then it will be used directly, if not, it will be passed to -// fmt.Errorf("%v"). The prefix parameter is used to add a prefix to the -// error message when calling Error(). The skip parameter indicates how far -// up the stack to start the stacktrace. 0 is from the current call, -// 1 from its caller, etc. -func WrapPrefix(e interface{}, prefix string, skip int) *Error { - - err := Wrap(e, 1+skip) - - if err.prefix != "" { - prefix = fmt.Sprintf("%s: %s", prefix, err.prefix) - } - - return &Error{ - Err: err.Err, - stack: err.stack, - prefix: prefix, - } - -} - -// Is detects whether the error is equal to a given error. Errors -// are considered equal by this function if they are the same object, -// or if they both contain the same error inside an errors.Error. -func Is(e error, original error) bool { - - if e == original { - return true - } - - if e, ok := e.(*Error); ok { - return Is(e.Err, original) - } - - if original, ok := original.(*Error); ok { - return Is(e, original.Err) - } - - return false -} - -// Errorf creates a new error with the given message. You can use it -// as a drop-in replacement for fmt.Errorf() to provide descriptive -// errors in return values. -func Errorf(format string, a ...interface{}) *Error { - return Wrap(fmt.Errorf(format, a...), 1) -} - -// Error returns the underlying error's message. -func (err *Error) Error() string { - - msg := err.Err.Error() - if err.prefix != "" { - msg = fmt.Sprintf("%s: %s", err.prefix, msg) - } - - return msg -} - -// Stack returns the callstack formatted the same way that go does -// in runtime/debug.Stack() -func (err *Error) Stack() []byte { - buf := bytes.Buffer{} - - for _, frame := range err.StackFrames() { - buf.WriteString(frame.String()) - } - - return buf.Bytes() -} - -// Callers satisfies the bugsnag ErrorWithCallerS() interface -// so that the stack can be read out. -func (err *Error) Callers() []uintptr { - return err.stack -} - -// ErrorStack returns a string that contains both the -// error message and the callstack. -func (err *Error) ErrorStack() string { - return err.TypeName() + " " + err.Error() + "\n" + string(err.Stack()) -} - -// StackFrames returns an array of frames containing information about the -// stack. -func (err *Error) StackFrames() []StackFrame { - if err.frames == nil { - err.frames = make([]StackFrame, len(err.stack)) - - for i, pc := range err.stack { - err.frames[i] = NewStackFrame(pc) - } - } - - return err.frames -} - -// TypeName returns the type this error. e.g. *errors.stringError. -func (err *Error) TypeName() string { - if _, ok := err.Err.(uncaughtPanic); ok { - return "panic" - } - return reflect.TypeOf(err.Err).String() -} diff --git a/vendor/github.com/go-errors/errors/parse_panic.go b/vendor/github.com/go-errors/errors/parse_panic.go deleted file mode 100644 index cc37052d7..000000000 --- a/vendor/github.com/go-errors/errors/parse_panic.go +++ /dev/null @@ -1,127 +0,0 @@ -package errors - -import ( - "strconv" - "strings" -) - -type uncaughtPanic struct{ message string } - -func (p uncaughtPanic) Error() string { - return p.message -} - -// ParsePanic allows you to get an error object from the output of a go program -// that panicked. This is particularly useful with https://github.com/mitchellh/panicwrap. -func ParsePanic(text string) (*Error, error) { - lines := strings.Split(text, "\n") - - state := "start" - - var message string - var stack []StackFrame - - for i := 0; i < len(lines); i++ { - line := lines[i] - - if state == "start" { - if strings.HasPrefix(line, "panic: ") { - message = strings.TrimPrefix(line, "panic: ") - state = "seek" - } else { - return nil, Errorf("bugsnag.panicParser: Invalid line (no prefix): %s", line) - } - - } else if state == "seek" { - if strings.HasPrefix(line, "goroutine ") && strings.HasSuffix(line, "[running]:") { - state = "parsing" - } - - } else if state == "parsing" { - if line == "" { - state = "done" - break - } - createdBy := false - if strings.HasPrefix(line, "created by ") { - line = strings.TrimPrefix(line, "created by ") - createdBy = true - } - - i++ - - if i >= len(lines) { - return nil, Errorf("bugsnag.panicParser: Invalid line (unpaired): %s", line) - } - - frame, err := parsePanicFrame(line, lines[i], createdBy) - if err != nil { - return nil, err - } - - stack = append(stack, *frame) - if createdBy { - state = "done" - break - } - } - } - - if state == "done" || state == "parsing" { - return &Error{Err: uncaughtPanic{message}, frames: stack}, nil - } - return nil, Errorf("could not parse panic: %v", text) -} - -// The lines we're passing look like this: -// -// main.(*foo).destruct(0xc208067e98) -// /0/go/src/github.com/bugsnag/bugsnag-go/pan/main.go:22 +0x151 -func parsePanicFrame(name string, line string, createdBy bool) (*StackFrame, error) { - idx := strings.LastIndex(name, "(") - if idx == -1 && !createdBy { - return nil, Errorf("bugsnag.panicParser: Invalid line (no call): %s", name) - } - if idx != -1 { - name = name[:idx] - } - pkg := "" - - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - - if !strings.HasPrefix(line, "\t") { - return nil, Errorf("bugsnag.panicParser: Invalid line (no tab): %s", line) - } - - idx = strings.LastIndex(line, ":") - if idx == -1 { - return nil, Errorf("bugsnag.panicParser: Invalid line (no line number): %s", line) - } - file := line[1:idx] - - number := line[idx+1:] - if idx = strings.Index(number, " +"); idx > -1 { - number = number[:idx] - } - - lno, err := strconv.ParseInt(number, 10, 32) - if err != nil { - return nil, Errorf("bugsnag.panicParser: Invalid line (bad line number): %s", line) - } - - return &StackFrame{ - File: file, - LineNumber: int(lno), - Package: pkg, - Name: name, - }, nil -} diff --git a/vendor/github.com/go-errors/errors/stackframe.go b/vendor/github.com/go-errors/errors/stackframe.go deleted file mode 100644 index 750ab9a52..000000000 --- a/vendor/github.com/go-errors/errors/stackframe.go +++ /dev/null @@ -1,102 +0,0 @@ -package errors - -import ( - "bytes" - "fmt" - "io/ioutil" - "runtime" - "strings" -) - -// A StackFrame contains all necessary information about to generate a line -// in a callstack. -type StackFrame struct { - // The path to the file containing this ProgramCounter - File string - // The LineNumber in that file - LineNumber int - // The Name of the function that contains this ProgramCounter - Name string - // The Package that contains this function - Package string - // The underlying ProgramCounter - ProgramCounter uintptr -} - -// NewStackFrame popoulates a stack frame object from the program counter. -func NewStackFrame(pc uintptr) (frame StackFrame) { - - frame = StackFrame{ProgramCounter: pc} - if frame.Func() == nil { - return - } - frame.Package, frame.Name = packageAndName(frame.Func()) - - // pc -1 because the program counters we use are usually return addresses, - // and we want to show the line that corresponds to the function call - frame.File, frame.LineNumber = frame.Func().FileLine(pc - 1) - return - -} - -// Func returns the function that contained this frame. -func (frame *StackFrame) Func() *runtime.Func { - if frame.ProgramCounter == 0 { - return nil - } - return runtime.FuncForPC(frame.ProgramCounter) -} - -// String returns the stackframe formatted in the same way as go does -// in runtime/debug.Stack() -func (frame *StackFrame) String() string { - str := fmt.Sprintf("%s:%d (0x%x)\n", frame.File, frame.LineNumber, frame.ProgramCounter) - - source, err := frame.SourceLine() - if err != nil { - return str - } - - return str + fmt.Sprintf("\t%s: %s\n", frame.Name, source) -} - -// SourceLine gets the line of code (from File and Line) of the original source if possible. -func (frame *StackFrame) SourceLine() (string, error) { - data, err := ioutil.ReadFile(frame.File) - - if err != nil { - return "", New(err) - } - - lines := bytes.Split(data, []byte{'\n'}) - if frame.LineNumber <= 0 || frame.LineNumber >= len(lines) { - return "???", nil - } - // -1 because line-numbers are 1 based, but our array is 0 based - return string(bytes.Trim(lines[frame.LineNumber-1], " \t")), nil -} - -func packageAndName(fn *runtime.Func) (string, string) { - name := fn.Name() - pkg := "" - - // The name includes the path name to the package, which is unnecessary - // since the file name is already included. Plus, it has center dots. - // That is, we see - // runtime/debug.*T·ptrmethod - // and want - // *T.ptrmethod - // Since the package path might contains dots (e.g. code.google.com/...), - // we first remove the path prefix if there is one. - if lastslash := strings.LastIndex(name, "/"); lastslash >= 0 { - pkg += name[:lastslash] + "/" - name = name[lastslash+1:] - } - if period := strings.Index(name, "."); period >= 0 { - pkg += name[:period] - name = name[period+1:] - } - - name = strings.Replace(name, "·", ".", -1) - return pkg, name -} diff --git a/vendor/github.com/go-ini/ini/LICENSE b/vendor/github.com/go-ini/ini/LICENSE deleted file mode 100644 index d361bbcdf..000000000 --- a/vendor/github.com/go-ini/ini/LICENSE +++ /dev/null @@ -1,191 +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: - -You must give any other recipients of the Work or Derivative Works a copy of -this License; and -You must cause any modified files to carry prominent notices stating that You -changed the files; and -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 -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 2014 Unknwon - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/vendor/github.com/go-ini/ini/error.go b/vendor/github.com/go-ini/ini/error.go deleted file mode 100644 index 80afe7431..000000000 --- a/vendor/github.com/go-ini/ini/error.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2016 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "fmt" -) - -type ErrDelimiterNotFound struct { - Line string -} - -func IsErrDelimiterNotFound(err error) bool { - _, ok := err.(ErrDelimiterNotFound) - return ok -} - -func (err ErrDelimiterNotFound) Error() string { - return fmt.Sprintf("key-value delimiter not found: %s", err.Line) -} diff --git a/vendor/github.com/go-ini/ini/file.go b/vendor/github.com/go-ini/ini/file.go deleted file mode 100644 index 0ed0eafd0..000000000 --- a/vendor/github.com/go-ini/ini/file.go +++ /dev/null @@ -1,418 +0,0 @@ -// Copyright 2017 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "os" - "strings" - "sync" -) - -// File represents a combination of a or more INI file(s) in memory. -type File struct { - options LoadOptions - dataSources []dataSource - - // Should make things safe, but sometimes doesn't matter. - BlockMode bool - lock sync.RWMutex - - // To keep data in order. - sectionList []string - // Actual data is stored here. - sections map[string]*Section - - NameMapper - ValueMapper -} - -// newFile initializes File object with given data sources. -func newFile(dataSources []dataSource, opts LoadOptions) *File { - if len(opts.KeyValueDelimiters) == 0 { - opts.KeyValueDelimiters = "=:" - } - return &File{ - BlockMode: true, - dataSources: dataSources, - sections: make(map[string]*Section), - sectionList: make([]string, 0, 10), - options: opts, - } -} - -// Empty returns an empty file object. -func Empty() *File { - // Ignore error here, we sure our data is good. - f, _ := Load([]byte("")) - return f -} - -// NewSection creates a new section. -func (f *File) NewSection(name string) (*Section, error) { - if len(name) == 0 { - return nil, errors.New("error creating new section: empty section name") - } else if f.options.Insensitive && name != DEFAULT_SECTION { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if inSlice(name, f.sectionList) { - return f.sections[name], nil - } - - f.sectionList = append(f.sectionList, name) - f.sections[name] = newSection(f, name) - return f.sections[name], nil -} - -// NewRawSection creates a new section with an unparseable body. -func (f *File) NewRawSection(name, body string) (*Section, error) { - section, err := f.NewSection(name) - if err != nil { - return nil, err - } - - section.isRawSection = true - section.rawBody = body - return section, nil -} - -// NewSections creates a list of sections. -func (f *File) NewSections(names ...string) (err error) { - for _, name := range names { - if _, err = f.NewSection(name); err != nil { - return err - } - } - return nil -} - -// GetSection returns section by given name. -func (f *File) GetSection(name string) (*Section, error) { - if len(name) == 0 { - name = DEFAULT_SECTION - } - if f.options.Insensitive { - name = strings.ToLower(name) - } - - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sec := f.sections[name] - if sec == nil { - return nil, fmt.Errorf("section '%s' does not exist", name) - } - return sec, nil -} - -// Section assumes named section exists and returns a zero-value when not. -func (f *File) Section(name string) *Section { - sec, err := f.GetSection(name) - if err != nil { - // Note: It's OK here because the only possible error is empty section name, - // but if it's empty, this piece of code won't be executed. - sec, _ = f.NewSection(name) - return sec - } - return sec -} - -// Section returns list of Section. -func (f *File) Sections() []*Section { - if f.BlockMode { - f.lock.RLock() - defer f.lock.RUnlock() - } - - sections := make([]*Section, len(f.sectionList)) - for i, name := range f.sectionList { - sections[i] = f.sections[name] - } - return sections -} - -// ChildSections returns a list of child sections of given section name. -func (f *File) ChildSections(name string) []*Section { - return f.Section(name).ChildSections() -} - -// SectionStrings returns list of section names. -func (f *File) SectionStrings() []string { - list := make([]string, len(f.sectionList)) - copy(list, f.sectionList) - return list -} - -// DeleteSection deletes a section. -func (f *File) DeleteSection(name string) { - if f.BlockMode { - f.lock.Lock() - defer f.lock.Unlock() - } - - if len(name) == 0 { - name = DEFAULT_SECTION - } - - for i, s := range f.sectionList { - if s == name { - f.sectionList = append(f.sectionList[:i], f.sectionList[i+1:]...) - delete(f.sections, name) - return - } - } -} - -func (f *File) reload(s dataSource) error { - r, err := s.ReadCloser() - if err != nil { - return err - } - defer r.Close() - - return f.parse(r) -} - -// Reload reloads and parses all data sources. -func (f *File) Reload() (err error) { - for _, s := range f.dataSources { - if err = f.reload(s); err != nil { - // In loose mode, we create an empty default section for nonexistent files. - if os.IsNotExist(err) && f.options.Loose { - f.parse(bytes.NewBuffer(nil)) - continue - } - return err - } - } - return nil -} - -// Append appends one or more data sources and reloads automatically. -func (f *File) Append(source interface{}, others ...interface{}) error { - ds, err := parseDataSource(source) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - for _, s := range others { - ds, err = parseDataSource(s) - if err != nil { - return err - } - f.dataSources = append(f.dataSources, ds) - } - return f.Reload() -} - -func (f *File) writeToBuffer(indent string) (*bytes.Buffer, error) { - equalSign := DefaultFormatLeft + "=" + DefaultFormatRight - - if PrettyFormat || PrettyEqual { - equalSign = " = " - } - - // Use buffer to make sure target is safe until finish encoding. - buf := bytes.NewBuffer(nil) - for i, sname := range f.sectionList { - sec := f.Section(sname) - if len(sec.Comment) > 0 { - // Support multiline comments - lines := strings.Split(sec.Comment, LineBreak) - for i := range lines { - if lines[i][0] != '#' && lines[i][0] != ';' { - lines[i] = "; " + lines[i] - } else { - lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:]) - } - - if _, err := buf.WriteString(lines[i] + LineBreak); err != nil { - return nil, err - } - } - } - - if i > 0 || DefaultHeader { - if _, err := buf.WriteString("[" + sname + "]" + LineBreak); err != nil { - return nil, err - } - } else { - // Write nothing if default section is empty - if len(sec.keyList) == 0 { - continue - } - } - - if sec.isRawSection { - if _, err := buf.WriteString(sec.rawBody); err != nil { - return nil, err - } - - if PrettySection { - // Put a line between sections - if _, err := buf.WriteString(LineBreak); err != nil { - return nil, err - } - } - continue - } - - // Count and generate alignment length and buffer spaces using the - // longest key. Keys may be modifed if they contain certain characters so - // we need to take that into account in our calculation. - alignLength := 0 - if PrettyFormat { - for _, kname := range sec.keyList { - keyLength := len(kname) - // First case will surround key by ` and second by """ - if strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters) { - keyLength += 2 - } else if strings.Contains(kname, "`") { - keyLength += 6 - } - - if keyLength > alignLength { - alignLength = keyLength - } - } - } - alignSpaces := bytes.Repeat([]byte(" "), alignLength) - - KEY_LIST: - for _, kname := range sec.keyList { - key := sec.Key(kname) - if len(key.Comment) > 0 { - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - // Support multiline comments - lines := strings.Split(key.Comment, LineBreak) - for i := range lines { - if lines[i][0] != '#' && lines[i][0] != ';' { - lines[i] = "; " + strings.TrimSpace(lines[i]) - } else { - lines[i] = lines[i][:1] + " " + strings.TrimSpace(lines[i][1:]) - } - - if _, err := buf.WriteString(lines[i] + LineBreak); err != nil { - return nil, err - } - } - } - - if len(indent) > 0 && sname != DEFAULT_SECTION { - buf.WriteString(indent) - } - - switch { - case key.isAutoIncrement: - kname = "-" - case strings.Contains(kname, "\"") || strings.ContainsAny(kname, f.options.KeyValueDelimiters): - kname = "`" + kname + "`" - case strings.Contains(kname, "`"): - kname = `"""` + kname + `"""` - } - - for _, val := range key.ValueWithShadows() { - if _, err := buf.WriteString(kname); err != nil { - return nil, err - } - - if key.isBooleanType { - if kname != sec.keyList[len(sec.keyList)-1] { - buf.WriteString(LineBreak) - } - continue KEY_LIST - } - - // Write out alignment spaces before "=" sign - if PrettyFormat { - buf.Write(alignSpaces[:alignLength-len(kname)]) - } - - // In case key value contains "\n", "`", "\"", "#" or ";" - if strings.ContainsAny(val, "\n`") { - val = `"""` + val + `"""` - } else if !f.options.IgnoreInlineComment && strings.ContainsAny(val, "#;") { - val = "`" + val + "`" - } - if _, err := buf.WriteString(equalSign + val + LineBreak); err != nil { - return nil, err - } - } - - for _, val := range key.nestedValues { - if _, err := buf.WriteString(indent + " " + val + LineBreak); err != nil { - return nil, err - } - } - } - - if PrettySection { - // Put a line between sections - if _, err := buf.WriteString(LineBreak); err != nil { - return nil, err - } - } - } - - return buf, nil -} - -// WriteToIndent writes content into io.Writer with given indention. -// If PrettyFormat has been set to be true, -// it will align "=" sign with spaces under each section. -func (f *File) WriteToIndent(w io.Writer, indent string) (int64, error) { - buf, err := f.writeToBuffer(indent) - if err != nil { - return 0, err - } - return buf.WriteTo(w) -} - -// WriteTo writes file content into io.Writer. -func (f *File) WriteTo(w io.Writer) (int64, error) { - return f.WriteToIndent(w, "") -} - -// SaveToIndent writes content to file system with given value indention. -func (f *File) SaveToIndent(filename, indent string) error { - // Note: Because we are truncating with os.Create, - // so it's safer to save to a temporary file location and rename afte done. - buf, err := f.writeToBuffer(indent) - if err != nil { - return err - } - - return ioutil.WriteFile(filename, buf.Bytes(), 0666) -} - -// SaveTo writes content to file system. -func (f *File) SaveTo(filename string) error { - return f.SaveToIndent(filename, "") -} diff --git a/vendor/github.com/go-ini/ini/ini.go b/vendor/github.com/go-ini/ini/ini.go deleted file mode 100644 index 93424f671..000000000 --- a/vendor/github.com/go-ini/ini/ini.go +++ /dev/null @@ -1,217 +0,0 @@ -// +build go1.6 - -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -// Package ini provides INI file read and write functionality in Go. -package ini - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "regexp" - "runtime" -) - -const ( - // Name for default section. You can use this constant or the string literal. - // In most of cases, an empty string is all you need to access the section. - DEFAULT_SECTION = "DEFAULT" - - // Maximum allowed depth when recursively substituing variable names. - _DEPTH_VALUES = 99 - _VERSION = "1.41.0" -) - -// Version returns current package version literal. -func Version() string { - return _VERSION -} - -var ( - // Delimiter to determine or compose a new line. - // This variable will be changed to "\r\n" automatically on Windows - // at package init time. - LineBreak = "\n" - - // Place custom spaces when PrettyFormat and PrettyEqual are both disabled - DefaultFormatLeft = "" - DefaultFormatRight = "" - - // Variable regexp pattern: %(variable)s - varPattern = regexp.MustCompile(`%\(([^\)]+)\)s`) - - // Indicate whether to align "=" sign with spaces to produce pretty output - // or reduce all possible spaces for compact format. - PrettyFormat = true - - // Place spaces around "=" sign even when PrettyFormat is false - PrettyEqual = false - - // Explicitly write DEFAULT section header - DefaultHeader = false - - // Indicate whether to put a line between sections - PrettySection = true -) - -func init() { - if runtime.GOOS == "windows" { - LineBreak = "\r\n" - } -} - -func inSlice(str string, s []string) bool { - for _, v := range s { - if str == v { - return true - } - } - return false -} - -// dataSource is an interface that returns object which can be read and closed. -type dataSource interface { - ReadCloser() (io.ReadCloser, error) -} - -// sourceFile represents an object that contains content on the local file system. -type sourceFile struct { - name string -} - -func (s sourceFile) ReadCloser() (_ io.ReadCloser, err error) { - return os.Open(s.name) -} - -// sourceData represents an object that contains content in memory. -type sourceData struct { - data []byte -} - -func (s *sourceData) ReadCloser() (io.ReadCloser, error) { - return ioutil.NopCloser(bytes.NewReader(s.data)), nil -} - -// sourceReadCloser represents an input stream with Close method. -type sourceReadCloser struct { - reader io.ReadCloser -} - -func (s *sourceReadCloser) ReadCloser() (io.ReadCloser, error) { - return s.reader, nil -} - -func parseDataSource(source interface{}) (dataSource, error) { - switch s := source.(type) { - case string: - return sourceFile{s}, nil - case []byte: - return &sourceData{s}, nil - case io.ReadCloser: - return &sourceReadCloser{s}, nil - default: - return nil, fmt.Errorf("error parsing data source: unknown type '%s'", s) - } -} - -type LoadOptions struct { - // Loose indicates whether the parser should ignore nonexistent files or return error. - Loose bool - // Insensitive indicates whether the parser forces all section and key names to lowercase. - Insensitive bool - // IgnoreContinuation indicates whether to ignore continuation lines while parsing. - IgnoreContinuation bool - // IgnoreInlineComment indicates whether to ignore comments at the end of value and treat it as part of value. - IgnoreInlineComment bool - // SkipUnrecognizableLines indicates whether to skip unrecognizable lines that do not conform to key/value pairs. - SkipUnrecognizableLines bool - // AllowBooleanKeys indicates whether to allow boolean type keys or treat as value is missing. - // This type of keys are mostly used in my.cnf. - AllowBooleanKeys bool - // AllowShadows indicates whether to keep track of keys with same name under same section. - AllowShadows bool - // AllowNestedValues indicates whether to allow AWS-like nested values. - // Docs: http://docs.aws.amazon.com/cli/latest/topic/config-vars.html#nested-values - AllowNestedValues bool - // AllowPythonMultilineValues indicates whether to allow Python-like multi-line values. - // Docs: https://docs.python.org/3/library/configparser.html#supported-ini-file-structure - // Relevant quote: Values can also span multiple lines, as long as they are indented deeper - // than the first line of the value. - AllowPythonMultilineValues bool - // SpaceBeforeInlineComment indicates whether to allow comment symbols (\# and \;) inside value. - // Docs: https://docs.python.org/2/library/configparser.html - // Quote: Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names. - // In the latter case, they need to be preceded by a whitespace character to be recognized as a comment. - SpaceBeforeInlineComment bool - // UnescapeValueDoubleQuotes indicates whether to unescape double quotes inside value to regular format - // when value is surrounded by double quotes, e.g. key="a \"value\"" => key=a "value" - UnescapeValueDoubleQuotes bool - // UnescapeValueCommentSymbols indicates to unescape comment symbols (\# and \;) inside value to regular format - // when value is NOT surrounded by any quotes. - // Note: UNSTABLE, behavior might change to only unescape inside double quotes but may noy necessary at all. - UnescapeValueCommentSymbols bool - // UnparseableSections stores a list of blocks that are allowed with raw content which do not otherwise - // conform to key/value pairs. Specify the names of those blocks here. - UnparseableSections []string - // KeyValueDelimiters is the sequence of delimiters that are used to separate key and value. By default, it is "=:". - KeyValueDelimiters string -} - -func LoadSources(opts LoadOptions, source interface{}, others ...interface{}) (_ *File, err error) { - sources := make([]dataSource, len(others)+1) - sources[0], err = parseDataSource(source) - if err != nil { - return nil, err - } - for i := range others { - sources[i+1], err = parseDataSource(others[i]) - if err != nil { - return nil, err - } - } - f := newFile(sources, opts) - if err = f.Reload(); err != nil { - return nil, err - } - return f, nil -} - -// Load loads and parses from INI data sources. -// Arguments can be mixed of file name with string type, or raw data in []byte. -// It will return error if list contains nonexistent files. -func Load(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{}, source, others...) -} - -// LooseLoad has exactly same functionality as Load function -// except it ignores nonexistent files instead of returning error. -func LooseLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Loose: true}, source, others...) -} - -// InsensitiveLoad has exactly same functionality as Load function -// except it forces all section and key names to be lowercased. -func InsensitiveLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{Insensitive: true}, source, others...) -} - -// ShadowLoad has exactly same functionality as Load function -// except it allows have shadow keys. -func ShadowLoad(source interface{}, others ...interface{}) (*File, error) { - return LoadSources(LoadOptions{AllowShadows: true}, source, others...) -} diff --git a/vendor/github.com/go-ini/ini/key.go b/vendor/github.com/go-ini/ini/key.go deleted file mode 100644 index 0fee0dc7e..000000000 --- a/vendor/github.com/go-ini/ini/key.go +++ /dev/null @@ -1,752 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "strconv" - "strings" - "time" -) - -// Key represents a key under a section. -type Key struct { - s *Section - Comment string - name string - value string - isAutoIncrement bool - isBooleanType bool - - isShadow bool - shadows []*Key - - nestedValues []string -} - -// newKey simply return a key object with given values. -func newKey(s *Section, name, val string) *Key { - return &Key{ - s: s, - name: name, - value: val, - } -} - -func (k *Key) addShadow(val string) error { - if k.isShadow { - return errors.New("cannot add shadow to another shadow key") - } else if k.isAutoIncrement || k.isBooleanType { - return errors.New("cannot add shadow to auto-increment or boolean key") - } - - shadow := newKey(k.s, k.name, val) - shadow.isShadow = true - k.shadows = append(k.shadows, shadow) - return nil -} - -// AddShadow adds a new shadow key to itself. -func (k *Key) AddShadow(val string) error { - if !k.s.f.options.AllowShadows { - return errors.New("shadow key is not allowed") - } - return k.addShadow(val) -} - -func (k *Key) addNestedValue(val string) error { - if k.isAutoIncrement || k.isBooleanType { - return errors.New("cannot add nested value to auto-increment or boolean key") - } - - k.nestedValues = append(k.nestedValues, val) - return nil -} - -func (k *Key) AddNestedValue(val string) error { - if !k.s.f.options.AllowNestedValues { - return errors.New("nested value is not allowed") - } - return k.addNestedValue(val) -} - -// ValueMapper represents a mapping function for values, e.g. os.ExpandEnv -type ValueMapper func(string) string - -// Name returns name of key. -func (k *Key) Name() string { - return k.name -} - -// Value returns raw value of key for performance purpose. -func (k *Key) Value() string { - return k.value -} - -// ValueWithShadows returns raw values of key and its shadows if any. -func (k *Key) ValueWithShadows() []string { - if len(k.shadows) == 0 { - return []string{k.value} - } - vals := make([]string, len(k.shadows)+1) - vals[0] = k.value - for i := range k.shadows { - vals[i+1] = k.shadows[i].value - } - return vals -} - -// NestedValues returns nested values stored in the key. -// It is possible returned value is nil if no nested values stored in the key. -func (k *Key) NestedValues() []string { - return k.nestedValues -} - -// transformValue takes a raw value and transforms to its final string. -func (k *Key) transformValue(val string) string { - if k.s.f.ValueMapper != nil { - val = k.s.f.ValueMapper(val) - } - - // Fail-fast if no indicate char found for recursive value - if !strings.Contains(val, "%") { - return val - } - for i := 0; i < _DEPTH_VALUES; i++ { - vr := varPattern.FindString(val) - if len(vr) == 0 { - break - } - - // Take off leading '%(' and trailing ')s'. - noption := vr[2 : len(vr)-2] - - // Search in the same section. - nk, err := k.s.GetKey(noption) - if err != nil || k == nk { - // Search again in default section. - nk, _ = k.s.f.Section("").GetKey(noption) - } - - // Substitute by new value and take off leading '%(' and trailing ')s'. - val = strings.Replace(val, vr, nk.value, -1) - } - return val -} - -// String returns string representation of value. -func (k *Key) String() string { - return k.transformValue(k.value) -} - -// Validate accepts a validate function which can -// return modifed result as key value. -func (k *Key) Validate(fn func(string) string) string { - return fn(k.String()) -} - -// parseBool returns the boolean value represented by the string. -// -// It accepts 1, t, T, TRUE, true, True, YES, yes, Yes, y, ON, on, On, -// 0, f, F, FALSE, false, False, NO, no, No, n, OFF, off, Off. -// Any other value returns an error. -func parseBool(str string) (value bool, err error) { - switch str { - case "1", "t", "T", "true", "TRUE", "True", "YES", "yes", "Yes", "y", "ON", "on", "On": - return true, nil - case "0", "f", "F", "false", "FALSE", "False", "NO", "no", "No", "n", "OFF", "off", "Off": - return false, nil - } - return false, fmt.Errorf("parsing \"%s\": invalid syntax", str) -} - -// Bool returns bool type value. -func (k *Key) Bool() (bool, error) { - return parseBool(k.String()) -} - -// Float64 returns float64 type value. -func (k *Key) Float64() (float64, error) { - return strconv.ParseFloat(k.String(), 64) -} - -// Int returns int type value. -func (k *Key) Int() (int, error) { - v, err := strconv.ParseInt(k.String(), 0, 64) - return int(v), err -} - -// Int64 returns int64 type value. -func (k *Key) Int64() (int64, error) { - return strconv.ParseInt(k.String(), 0, 64) -} - -// Uint returns uint type valued. -func (k *Key) Uint() (uint, error) { - u, e := strconv.ParseUint(k.String(), 0, 64) - return uint(u), e -} - -// Uint64 returns uint64 type value. -func (k *Key) Uint64() (uint64, error) { - return strconv.ParseUint(k.String(), 0, 64) -} - -// Duration returns time.Duration type value. -func (k *Key) Duration() (time.Duration, error) { - return time.ParseDuration(k.String()) -} - -// TimeFormat parses with given format and returns time.Time type value. -func (k *Key) TimeFormat(format string) (time.Time, error) { - return time.Parse(format, k.String()) -} - -// Time parses with RFC3339 format and returns time.Time type value. -func (k *Key) Time() (time.Time, error) { - return k.TimeFormat(time.RFC3339) -} - -// MustString returns default value if key value is empty. -func (k *Key) MustString(defaultVal string) string { - val := k.String() - if len(val) == 0 { - k.value = defaultVal - return defaultVal - } - return val -} - -// MustBool always returns value without error, -// it returns false if error occurs. -func (k *Key) MustBool(defaultVal ...bool) bool { - val, err := k.Bool() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatBool(defaultVal[0]) - return defaultVal[0] - } - return val -} - -// MustFloat64 always returns value without error, -// it returns 0.0 if error occurs. -func (k *Key) MustFloat64(defaultVal ...float64) float64 { - val, err := k.Float64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatFloat(defaultVal[0], 'f', -1, 64) - return defaultVal[0] - } - return val -} - -// MustInt always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt(defaultVal ...int) int { - val, err := k.Int() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(int64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustInt64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustInt64(defaultVal ...int64) int64 { - val, err := k.Int64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatInt(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustUint always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint(defaultVal ...uint) uint { - val, err := k.Uint() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(uint64(defaultVal[0]), 10) - return defaultVal[0] - } - return val -} - -// MustUint64 always returns value without error, -// it returns 0 if error occurs. -func (k *Key) MustUint64(defaultVal ...uint64) uint64 { - val, err := k.Uint64() - if len(defaultVal) > 0 && err != nil { - k.value = strconv.FormatUint(defaultVal[0], 10) - return defaultVal[0] - } - return val -} - -// MustDuration always returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustDuration(defaultVal ...time.Duration) time.Duration { - val, err := k.Duration() - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].String() - return defaultVal[0] - } - return val -} - -// MustTimeFormat always parses with given format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTimeFormat(format string, defaultVal ...time.Time) time.Time { - val, err := k.TimeFormat(format) - if len(defaultVal) > 0 && err != nil { - k.value = defaultVal[0].Format(format) - return defaultVal[0] - } - return val -} - -// MustTime always parses with RFC3339 format and returns value without error, -// it returns zero value if error occurs. -func (k *Key) MustTime(defaultVal ...time.Time) time.Time { - return k.MustTimeFormat(time.RFC3339, defaultVal...) -} - -// In always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) In(defaultVal string, candidates []string) string { - val := k.String() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InFloat64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InFloat64(defaultVal float64, candidates []float64) float64 { - val := k.MustFloat64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt(defaultVal int, candidates []int) int { - val := k.MustInt() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InInt64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InInt64(defaultVal int64, candidates []int64) int64 { - val := k.MustInt64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint(defaultVal uint, candidates []uint) uint { - val := k.MustUint() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InUint64 always returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InUint64(defaultVal uint64, candidates []uint64) uint64 { - val := k.MustUint64() - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTimeFormat always parses with given format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTimeFormat(format string, defaultVal time.Time, candidates []time.Time) time.Time { - val := k.MustTimeFormat(format) - for _, cand := range candidates { - if val == cand { - return val - } - } - return defaultVal -} - -// InTime always parses with RFC3339 format and returns value without error, -// it returns default value if error occurs or doesn't fit into candidates. -func (k *Key) InTime(defaultVal time.Time, candidates []time.Time) time.Time { - return k.InTimeFormat(time.RFC3339, defaultVal, candidates) -} - -// RangeFloat64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeFloat64(defaultVal, min, max float64) float64 { - val := k.MustFloat64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt(defaultVal, min, max int) int { - val := k.MustInt() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeInt64 checks if value is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeInt64(defaultVal, min, max int64) int64 { - val := k.MustInt64() - if val < min || val > max { - return defaultVal - } - return val -} - -// RangeTimeFormat checks if value with given format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTimeFormat(format string, defaultVal, min, max time.Time) time.Time { - val := k.MustTimeFormat(format) - if val.Unix() < min.Unix() || val.Unix() > max.Unix() { - return defaultVal - } - return val -} - -// RangeTime checks if value with RFC3339 format is in given range inclusively, -// and returns default value if it's not. -func (k *Key) RangeTime(defaultVal, min, max time.Time) time.Time { - return k.RangeTimeFormat(time.RFC3339, defaultVal, min, max) -} - -// Strings returns list of string divided by given delimiter. -func (k *Key) Strings(delim string) []string { - str := k.String() - if len(str) == 0 { - return []string{} - } - - runes := []rune(str) - vals := make([]string, 0, 2) - var buf bytes.Buffer - escape := false - idx := 0 - for { - if escape { - escape = false - if runes[idx] != '\\' && !strings.HasPrefix(string(runes[idx:]), delim) { - buf.WriteRune('\\') - } - buf.WriteRune(runes[idx]) - } else { - if runes[idx] == '\\' { - escape = true - } else if strings.HasPrefix(string(runes[idx:]), delim) { - idx += len(delim) - 1 - vals = append(vals, strings.TrimSpace(buf.String())) - buf.Reset() - } else { - buf.WriteRune(runes[idx]) - } - } - idx += 1 - if idx == len(runes) { - break - } - } - - if buf.Len() > 0 { - vals = append(vals, strings.TrimSpace(buf.String())) - } - - return vals -} - -// StringsWithShadows returns list of string divided by given delimiter. -// Shadows will also be appended if any. -func (k *Key) StringsWithShadows(delim string) []string { - vals := k.ValueWithShadows() - results := make([]string, 0, len(vals)*2) - for i := range vals { - if len(vals) == 0 { - continue - } - - results = append(results, strings.Split(vals[i], delim)...) - } - - for i := range results { - results[i] = k.transformValue(strings.TrimSpace(results[i])) - } - return results -} - -// Float64s returns list of float64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Float64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), true, false) - return vals -} - -// Ints returns list of int divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Ints(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), true, false) - return vals -} - -// Int64s returns list of int64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Int64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), true, false) - return vals -} - -// Uints returns list of uint divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), true, false) - return vals -} - -// Uint64s returns list of uint64 divided by given delimiter. Any invalid input will be treated as zero value. -func (k *Key) Uint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), true, false) - return vals -} - -// TimesFormat parses with given format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) TimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), true, false) - return vals -} - -// Times parses with RFC3339 format and returns list of time.Time divided by given delimiter. -// Any invalid input will be treated as zero value (0001-01-01 00:00:00 +0000 UTC). -func (k *Key) Times(delim string) []time.Time { - return k.TimesFormat(time.RFC3339, delim) -} - -// ValidFloat64s returns list of float64 divided by given delimiter. If some value is not float, then -// it will not be included to result list. -func (k *Key) ValidFloat64s(delim string) []float64 { - vals, _ := k.parseFloat64s(k.Strings(delim), false, false) - return vals -} - -// ValidInts returns list of int divided by given delimiter. If some value is not integer, then it will -// not be included to result list. -func (k *Key) ValidInts(delim string) []int { - vals, _ := k.parseInts(k.Strings(delim), false, false) - return vals -} - -// ValidInt64s returns list of int64 divided by given delimiter. If some value is not 64-bit integer, -// then it will not be included to result list. -func (k *Key) ValidInt64s(delim string) []int64 { - vals, _ := k.parseInt64s(k.Strings(delim), false, false) - return vals -} - -// ValidUints returns list of uint divided by given delimiter. If some value is not unsigned integer, -// then it will not be included to result list. -func (k *Key) ValidUints(delim string) []uint { - vals, _ := k.parseUints(k.Strings(delim), false, false) - return vals -} - -// ValidUint64s returns list of uint64 divided by given delimiter. If some value is not 64-bit unsigned -// integer, then it will not be included to result list. -func (k *Key) ValidUint64s(delim string) []uint64 { - vals, _ := k.parseUint64s(k.Strings(delim), false, false) - return vals -} - -// ValidTimesFormat parses with given format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimesFormat(format, delim string) []time.Time { - vals, _ := k.parseTimesFormat(format, k.Strings(delim), false, false) - return vals -} - -// ValidTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter. -func (k *Key) ValidTimes(delim string) []time.Time { - return k.ValidTimesFormat(time.RFC3339, delim) -} - -// StrictFloat64s returns list of float64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictFloat64s(delim string) ([]float64, error) { - return k.parseFloat64s(k.Strings(delim), false, true) -} - -// StrictInts returns list of int divided by given delimiter or error on first invalid input. -func (k *Key) StrictInts(delim string) ([]int, error) { - return k.parseInts(k.Strings(delim), false, true) -} - -// StrictInt64s returns list of int64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictInt64s(delim string) ([]int64, error) { - return k.parseInt64s(k.Strings(delim), false, true) -} - -// StrictUints returns list of uint divided by given delimiter or error on first invalid input. -func (k *Key) StrictUints(delim string) ([]uint, error) { - return k.parseUints(k.Strings(delim), false, true) -} - -// StrictUint64s returns list of uint64 divided by given delimiter or error on first invalid input. -func (k *Key) StrictUint64s(delim string) ([]uint64, error) { - return k.parseUint64s(k.Strings(delim), false, true) -} - -// StrictTimesFormat parses with given format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimesFormat(format, delim string) ([]time.Time, error) { - return k.parseTimesFormat(format, k.Strings(delim), false, true) -} - -// StrictTimes parses with RFC3339 format and returns list of time.Time divided by given delimiter -// or error on first invalid input. -func (k *Key) StrictTimes(delim string) ([]time.Time, error) { - return k.StrictTimesFormat(time.RFC3339, delim) -} - -// parseFloat64s transforms strings to float64s. -func (k *Key) parseFloat64s(strs []string, addInvalid, returnOnInvalid bool) ([]float64, error) { - vals := make([]float64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseFloat(str, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInts transforms strings to ints. -func (k *Key) parseInts(strs []string, addInvalid, returnOnInvalid bool) ([]int, error) { - vals := make([]int, 0, len(strs)) - for _, str := range strs { - valInt64, err := strconv.ParseInt(str, 0, 64) - val := int(valInt64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseInt64s transforms strings to int64s. -func (k *Key) parseInt64s(strs []string, addInvalid, returnOnInvalid bool) ([]int64, error) { - vals := make([]int64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseInt(str, 0, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseUints transforms strings to uints. -func (k *Key) parseUints(strs []string, addInvalid, returnOnInvalid bool) ([]uint, error) { - vals := make([]uint, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 0, 0) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, uint(val)) - } - } - return vals, nil -} - -// parseUint64s transforms strings to uint64s. -func (k *Key) parseUint64s(strs []string, addInvalid, returnOnInvalid bool) ([]uint64, error) { - vals := make([]uint64, 0, len(strs)) - for _, str := range strs { - val, err := strconv.ParseUint(str, 0, 64) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// parseTimesFormat transforms strings to times in given format. -func (k *Key) parseTimesFormat(format string, strs []string, addInvalid, returnOnInvalid bool) ([]time.Time, error) { - vals := make([]time.Time, 0, len(strs)) - for _, str := range strs { - val, err := time.Parse(format, str) - if err != nil && returnOnInvalid { - return nil, err - } - if err == nil || addInvalid { - vals = append(vals, val) - } - } - return vals, nil -} - -// SetValue changes key value. -func (k *Key) SetValue(v string) { - if k.s.f.BlockMode { - k.s.f.lock.Lock() - defer k.s.f.lock.Unlock() - } - - k.value = v - k.s.keysHash[k.name] = v -} diff --git a/vendor/github.com/go-ini/ini/parser.go b/vendor/github.com/go-ini/ini/parser.go deleted file mode 100644 index 24cf11c73..000000000 --- a/vendor/github.com/go-ini/ini/parser.go +++ /dev/null @@ -1,486 +0,0 @@ -// Copyright 2015 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bufio" - "bytes" - "fmt" - "io" - "regexp" - "strconv" - "strings" - "unicode" -) - -var pythonMultiline = regexp.MustCompile("^(\\s+)([^\n]+)") - -type tokenType int - -const ( - _TOKEN_INVALID tokenType = iota - _TOKEN_COMMENT - _TOKEN_SECTION - _TOKEN_KEY -) - -type parser struct { - buf *bufio.Reader - isEOF bool - count int - comment *bytes.Buffer -} - -func newParser(r io.Reader) *parser { - return &parser{ - buf: bufio.NewReader(r), - count: 1, - comment: &bytes.Buffer{}, - } -} - -// BOM handles header of UTF-8, UTF-16 LE and UTF-16 BE's BOM format. -// http://en.wikipedia.org/wiki/Byte_order_mark#Representations_of_byte_order_marks_by_encoding -func (p *parser) BOM() error { - mask, err := p.buf.Peek(2) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 2 { - return nil - } - - switch { - case mask[0] == 254 && mask[1] == 255: - fallthrough - case mask[0] == 255 && mask[1] == 254: - p.buf.Read(mask) - case mask[0] == 239 && mask[1] == 187: - mask, err := p.buf.Peek(3) - if err != nil && err != io.EOF { - return err - } else if len(mask) < 3 { - return nil - } - if mask[2] == 191 { - p.buf.Read(mask) - } - } - return nil -} - -func (p *parser) readUntil(delim byte) ([]byte, error) { - data, err := p.buf.ReadBytes(delim) - if err != nil { - if err == io.EOF { - p.isEOF = true - } else { - return nil, err - } - } - return data, nil -} - -func cleanComment(in []byte) ([]byte, bool) { - i := bytes.IndexAny(in, "#;") - if i == -1 { - return nil, false - } - return in[i:], true -} - -func readKeyName(delimiters string, in []byte) (string, int, error) { - line := string(in) - - // Check if key name surrounded by quotes. - var keyQuote string - if line[0] == '"' { - if len(line) > 6 && string(line[0:3]) == `"""` { - keyQuote = `"""` - } else { - keyQuote = `"` - } - } else if line[0] == '`' { - keyQuote = "`" - } - - // Get out key name - endIdx := -1 - if len(keyQuote) > 0 { - startIdx := len(keyQuote) - // FIXME: fail case -> """"""name"""=value - pos := strings.Index(line[startIdx:], keyQuote) - if pos == -1 { - return "", -1, fmt.Errorf("missing closing key quote: %s", line) - } - pos += startIdx - - // Find key-value delimiter - i := strings.IndexAny(line[pos+startIdx:], delimiters) - if i < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - endIdx = pos + i - return strings.TrimSpace(line[startIdx:pos]), endIdx + startIdx + 1, nil - } - - endIdx = strings.IndexAny(line, delimiters) - if endIdx < 0 { - return "", -1, ErrDelimiterNotFound{line} - } - return strings.TrimSpace(line[0:endIdx]), endIdx + 1, nil -} - -func (p *parser) readMultilines(line, val, valQuote string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := string(data) - - pos := strings.LastIndex(next, valQuote) - if pos > -1 { - val += next[:pos] - - comment, has := cleanComment([]byte(next[pos:])) - if has { - p.comment.Write(bytes.TrimSpace(comment)) - } - break - } - val += next - if p.isEOF { - return "", fmt.Errorf("missing closing key quote from '%s' to '%s'", line, next) - } - } - return val, nil -} - -func (p *parser) readContinuationLines(val string) (string, error) { - for { - data, err := p.readUntil('\n') - if err != nil { - return "", err - } - next := strings.TrimSpace(string(data)) - - if len(next) == 0 { - break - } - val += next - if val[len(val)-1] != '\\' { - break - } - val = val[:len(val)-1] - } - return val, nil -} - -// hasSurroundedQuote check if and only if the first and last characters -// are quotes \" or \'. -// It returns false if any other parts also contain same kind of quotes. -func hasSurroundedQuote(in string, quote byte) bool { - return len(in) >= 2 && in[0] == quote && in[len(in)-1] == quote && - strings.IndexByte(in[1:], quote) == len(in)-2 -} - -func (p *parser) readValue(in []byte, - parserBufferSize int, - ignoreContinuation, ignoreInlineComment, unescapeValueDoubleQuotes, unescapeValueCommentSymbols, allowPythonMultilines, spaceBeforeInlineComment bool) (string, error) { - - line := strings.TrimLeftFunc(string(in), unicode.IsSpace) - if len(line) == 0 { - return "", nil - } - - var valQuote string - if len(line) > 3 && string(line[0:3]) == `"""` { - valQuote = `"""` - } else if line[0] == '`' { - valQuote = "`" - } else if unescapeValueDoubleQuotes && line[0] == '"' { - valQuote = `"` - } - - if len(valQuote) > 0 { - startIdx := len(valQuote) - pos := strings.LastIndex(line[startIdx:], valQuote) - // Check for multi-line value - if pos == -1 { - return p.readMultilines(line, line[startIdx:], valQuote) - } - - if unescapeValueDoubleQuotes && valQuote == `"` { - return strings.Replace(line[startIdx:pos+startIdx], `\"`, `"`, -1), nil - } - return line[startIdx : pos+startIdx], nil - } - - lastChar := line[len(line)-1] - // Won't be able to reach here if value only contains whitespace - line = strings.TrimSpace(line) - trimmedLastChar := line[len(line)-1] - - // Check continuation lines when desired - if !ignoreContinuation && trimmedLastChar == '\\' { - return p.readContinuationLines(line[:len(line)-1]) - } - - // Check if ignore inline comment - if !ignoreInlineComment { - var i int - if spaceBeforeInlineComment { - i = strings.Index(line, " #") - if i == -1 { - i = strings.Index(line, " ;") - } - - } else { - i = strings.IndexAny(line, "#;") - } - - if i > -1 { - p.comment.WriteString(line[i:]) - line = strings.TrimSpace(line[:i]) - } - - } - - // Trim single and double quotes - if hasSurroundedQuote(line, '\'') || - hasSurroundedQuote(line, '"') { - line = line[1 : len(line)-1] - } else if len(valQuote) == 0 && unescapeValueCommentSymbols { - if strings.Contains(line, `\;`) { - line = strings.Replace(line, `\;`, ";", -1) - } - if strings.Contains(line, `\#`) { - line = strings.Replace(line, `\#`, "#", -1) - } - } else if allowPythonMultilines && lastChar == '\n' { - parserBufferPeekResult, _ := p.buf.Peek(parserBufferSize) - peekBuffer := bytes.NewBuffer(parserBufferPeekResult) - - val := line - - for { - peekData, peekErr := peekBuffer.ReadBytes('\n') - if peekErr != nil { - if peekErr == io.EOF { - return val, nil - } - return "", peekErr - } - - peekMatches := pythonMultiline.FindStringSubmatch(string(peekData)) - if len(peekMatches) != 3 { - return val, nil - } - - // NOTE: Return if not a python-ini multi-line value. - currentIdentSize := len(peekMatches[1]) - if currentIdentSize <= 0 { - return val, nil - } - - // NOTE: Just advance the parser reader (buffer) in-sync with the peek buffer. - _, err := p.readUntil('\n') - if err != nil { - return "", err - } - - val += fmt.Sprintf("\n%s", peekMatches[2]) - } - } - - return line, nil -} - -// parse parses data through an io.Reader. -func (f *File) parse(reader io.Reader) (err error) { - p := newParser(reader) - if err = p.BOM(); err != nil { - return fmt.Errorf("BOM: %v", err) - } - - // Ignore error because default section name is never empty string. - name := DEFAULT_SECTION - if f.options.Insensitive { - name = strings.ToLower(DEFAULT_SECTION) - } - section, _ := f.NewSection(name) - - // This "last" is not strictly equivalent to "previous one" if current key is not the first nested key - var isLastValueEmpty bool - var lastRegularKey *Key - - var line []byte - var inUnparseableSection bool - - // NOTE: Iterate and increase `currentPeekSize` until - // the size of the parser buffer is found. - // TODO(unknwon): When Golang 1.10 is the lowest version supported, replace with `parserBufferSize := p.buf.Size()`. - parserBufferSize := 0 - // NOTE: Peek 1kb at a time. - currentPeekSize := 1024 - - if f.options.AllowPythonMultilineValues { - for { - peekBytes, _ := p.buf.Peek(currentPeekSize) - peekBytesLength := len(peekBytes) - - if parserBufferSize >= peekBytesLength { - break - } - - currentPeekSize *= 2 - parserBufferSize = peekBytesLength - } - } - - for !p.isEOF { - line, err = p.readUntil('\n') - if err != nil { - return err - } - - if f.options.AllowNestedValues && - isLastValueEmpty && len(line) > 0 { - if line[0] == ' ' || line[0] == '\t' { - lastRegularKey.addNestedValue(string(bytes.TrimSpace(line))) - continue - } - } - - line = bytes.TrimLeftFunc(line, unicode.IsSpace) - if len(line) == 0 { - continue - } - - // Comments - if line[0] == '#' || line[0] == ';' { - // Note: we do not care ending line break, - // it is needed for adding second line, - // so just clean it once at the end when set to value. - p.comment.Write(line) - continue - } - - // Section - if line[0] == '[' { - // Read to the next ']' (TODO: support quoted strings) - closeIdx := bytes.LastIndexByte(line, ']') - if closeIdx == -1 { - return fmt.Errorf("unclosed section: %s", line) - } - - name := string(line[1:closeIdx]) - section, err = f.NewSection(name) - if err != nil { - return err - } - - comment, has := cleanComment(line[closeIdx+1:]) - if has { - p.comment.Write(comment) - } - - section.Comment = strings.TrimSpace(p.comment.String()) - - // Reset aotu-counter and comments - p.comment.Reset() - p.count = 1 - - inUnparseableSection = false - for i := range f.options.UnparseableSections { - if f.options.UnparseableSections[i] == name || - (f.options.Insensitive && strings.ToLower(f.options.UnparseableSections[i]) == strings.ToLower(name)) { - inUnparseableSection = true - continue - } - } - continue - } - - if inUnparseableSection { - section.isRawSection = true - section.rawBody += string(line) - continue - } - - kname, offset, err := readKeyName(f.options.KeyValueDelimiters, line) - if err != nil { - // Treat as boolean key when desired, and whole line is key name. - if IsErrDelimiterNotFound(err) { - switch { - case f.options.AllowBooleanKeys: - kname, err := p.readValue(line, - parserBufferSize, - f.options.IgnoreContinuation, - f.options.IgnoreInlineComment, - f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols, - f.options.AllowPythonMultilineValues, - f.options.SpaceBeforeInlineComment) - if err != nil { - return err - } - key, err := section.NewBooleanKey(kname) - if err != nil { - return err - } - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - continue - - case f.options.SkipUnrecognizableLines: - continue - } - } - return err - } - - // Auto increment. - isAutoIncr := false - if kname == "-" { - isAutoIncr = true - kname = "#" + strconv.Itoa(p.count) - p.count++ - } - - value, err := p.readValue(line[offset:], - parserBufferSize, - f.options.IgnoreContinuation, - f.options.IgnoreInlineComment, - f.options.UnescapeValueDoubleQuotes, - f.options.UnescapeValueCommentSymbols, - f.options.AllowPythonMultilineValues, - f.options.SpaceBeforeInlineComment) - if err != nil { - return err - } - isLastValueEmpty = len(value) == 0 - - key, err := section.NewKey(kname, value) - if err != nil { - return err - } - key.isAutoIncrement = isAutoIncr - key.Comment = strings.TrimSpace(p.comment.String()) - p.comment.Reset() - lastRegularKey = key - } - return nil -} diff --git a/vendor/github.com/go-ini/ini/section.go b/vendor/github.com/go-ini/ini/section.go deleted file mode 100644 index bc32c620d..000000000 --- a/vendor/github.com/go-ini/ini/section.go +++ /dev/null @@ -1,259 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "errors" - "fmt" - "strings" -) - -// Section represents a config section. -type Section struct { - f *File - Comment string - name string - keys map[string]*Key - keyList []string - keysHash map[string]string - - isRawSection bool - rawBody string -} - -func newSection(f *File, name string) *Section { - return &Section{ - f: f, - name: name, - keys: make(map[string]*Key), - keyList: make([]string, 0, 10), - keysHash: make(map[string]string), - } -} - -// Name returns name of Section. -func (s *Section) Name() string { - return s.name -} - -// Body returns rawBody of Section if the section was marked as unparseable. -// It still follows the other rules of the INI format surrounding leading/trailing whitespace. -func (s *Section) Body() string { - return strings.TrimSpace(s.rawBody) -} - -// SetBody updates body content only if section is raw. -func (s *Section) SetBody(body string) { - if !s.isRawSection { - return - } - s.rawBody = body -} - -// NewKey creates a new key to given section. -func (s *Section) NewKey(name, val string) (*Key, error) { - if len(name) == 0 { - return nil, errors.New("error creating new key: empty key name") - } else if s.f.options.Insensitive { - name = strings.ToLower(name) - } - - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - if inSlice(name, s.keyList) { - if s.f.options.AllowShadows { - if err := s.keys[name].addShadow(val); err != nil { - return nil, err - } - } else { - s.keys[name].value = val - s.keysHash[name] = val - } - return s.keys[name], nil - } - - s.keyList = append(s.keyList, name) - s.keys[name] = newKey(s, name, val) - s.keysHash[name] = val - return s.keys[name], nil -} - -// NewBooleanKey creates a new boolean type key to given section. -func (s *Section) NewBooleanKey(name string) (*Key, error) { - key, err := s.NewKey(name, "true") - if err != nil { - return nil, err - } - - key.isBooleanType = true - return key, nil -} - -// GetKey returns key in section by given name. -func (s *Section) GetKey(name string) (*Key, error) { - // FIXME: change to section level lock? - if s.f.BlockMode { - s.f.lock.RLock() - } - if s.f.options.Insensitive { - name = strings.ToLower(name) - } - key := s.keys[name] - if s.f.BlockMode { - s.f.lock.RUnlock() - } - - if key == nil { - // Check if it is a child-section. - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - return sec.GetKey(name) - } else { - break - } - } - return nil, fmt.Errorf("error when getting key of section '%s': key '%s' not exists", s.name, name) - } - return key, nil -} - -// HasKey returns true if section contains a key with given name. -func (s *Section) HasKey(name string) bool { - key, _ := s.GetKey(name) - return key != nil -} - -// Haskey is a backwards-compatible name for HasKey. -// TODO: delete me in v2 -func (s *Section) Haskey(name string) bool { - return s.HasKey(name) -} - -// HasValue returns true if section contains given raw value. -func (s *Section) HasValue(value string) bool { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - for _, k := range s.keys { - if value == k.value { - return true - } - } - return false -} - -// Key assumes named Key exists in section and returns a zero-value when not. -func (s *Section) Key(name string) *Key { - key, err := s.GetKey(name) - if err != nil { - // It's OK here because the only possible error is empty key name, - // but if it's empty, this piece of code won't be executed. - key, _ = s.NewKey(name, "") - return key - } - return key -} - -// Keys returns list of keys of section. -func (s *Section) Keys() []*Key { - keys := make([]*Key, len(s.keyList)) - for i := range s.keyList { - keys[i] = s.Key(s.keyList[i]) - } - return keys -} - -// ParentKeys returns list of keys of parent section. -func (s *Section) ParentKeys() []*Key { - var parentKeys []*Key - sname := s.name - for { - if i := strings.LastIndex(sname, "."); i > -1 { - sname = sname[:i] - sec, err := s.f.GetSection(sname) - if err != nil { - continue - } - parentKeys = append(parentKeys, sec.Keys()...) - } else { - break - } - - } - return parentKeys -} - -// KeyStrings returns list of key names of section. -func (s *Section) KeyStrings() []string { - list := make([]string, len(s.keyList)) - copy(list, s.keyList) - return list -} - -// KeysHash returns keys hash consisting of names and values. -func (s *Section) KeysHash() map[string]string { - if s.f.BlockMode { - s.f.lock.RLock() - defer s.f.lock.RUnlock() - } - - hash := map[string]string{} - for key, value := range s.keysHash { - hash[key] = value - } - return hash -} - -// DeleteKey deletes a key from section. -func (s *Section) DeleteKey(name string) { - if s.f.BlockMode { - s.f.lock.Lock() - defer s.f.lock.Unlock() - } - - for i, k := range s.keyList { - if k == name { - s.keyList = append(s.keyList[:i], s.keyList[i+1:]...) - delete(s.keys, name) - delete(s.keysHash, name) - return - } - } -} - -// ChildSections returns a list of child sections of current section. -// For example, "[parent.child1]" and "[parent.child12]" are child sections -// of section "[parent]". -func (s *Section) ChildSections() []*Section { - prefix := s.name + "." - children := make([]*Section, 0, 3) - for _, name := range s.f.sectionList { - if strings.HasPrefix(name, prefix) { - children = append(children, s.f.sections[name]) - } - } - return children -} diff --git a/vendor/github.com/go-ini/ini/struct.go b/vendor/github.com/go-ini/ini/struct.go deleted file mode 100644 index a9dfed078..000000000 --- a/vendor/github.com/go-ini/ini/struct.go +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2014 Unknwon -// -// Licensed under the Apache License, Version 2.0 (the "License"): you may -// not use this file except in compliance with the License. You may obtain -// a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -// License for the specific language governing permissions and limitations -// under the License. - -package ini - -import ( - "bytes" - "errors" - "fmt" - "reflect" - "strings" - "time" - "unicode" -) - -// NameMapper represents a ini tag name mapper. -type NameMapper func(string) string - -// Built-in name getters. -var ( - // AllCapsUnderscore converts to format ALL_CAPS_UNDERSCORE. - AllCapsUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - } - newstr = append(newstr, unicode.ToUpper(chr)) - } - return string(newstr) - } - // TitleUnderscore converts to format title_underscore. - TitleUnderscore NameMapper = func(raw string) string { - newstr := make([]rune, 0, len(raw)) - for i, chr := range raw { - if isUpper := 'A' <= chr && chr <= 'Z'; isUpper { - if i > 0 { - newstr = append(newstr, '_') - } - chr -= ('A' - 'a') - } - newstr = append(newstr, chr) - } - return string(newstr) - } -) - -func (s *Section) parseFieldName(raw, actual string) string { - if len(actual) > 0 { - return actual - } - if s.f.NameMapper != nil { - return s.f.NameMapper(raw) - } - return raw -} - -func parseDelim(actual string) string { - if len(actual) > 0 { - return actual - } - return "," -} - -var reflectTime = reflect.TypeOf(time.Now()).Kind() - -// setSliceWithProperType sets proper values to slice based on its type. -func setSliceWithProperType(key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - var strs []string - if allowShadow { - strs = key.StringsWithShadows(delim) - } else { - strs = key.Strings(delim) - } - - numVals := len(strs) - if numVals == 0 { - return nil - } - - var vals interface{} - var err error - - sliceOf := field.Type().Elem().Kind() - switch sliceOf { - case reflect.String: - vals = strs - case reflect.Int: - vals, err = key.parseInts(strs, true, false) - case reflect.Int64: - vals, err = key.parseInt64s(strs, true, false) - case reflect.Uint: - vals, err = key.parseUints(strs, true, false) - case reflect.Uint64: - vals, err = key.parseUint64s(strs, true, false) - case reflect.Float64: - vals, err = key.parseFloat64s(strs, true, false) - case reflectTime: - vals, err = key.parseTimesFormat(time.RFC3339, strs, true, false) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - if err != nil && isStrict { - return err - } - - slice := reflect.MakeSlice(field.Type(), numVals, numVals) - for i := 0; i < numVals; i++ { - switch sliceOf { - case reflect.String: - slice.Index(i).Set(reflect.ValueOf(vals.([]string)[i])) - case reflect.Int: - slice.Index(i).Set(reflect.ValueOf(vals.([]int)[i])) - case reflect.Int64: - slice.Index(i).Set(reflect.ValueOf(vals.([]int64)[i])) - case reflect.Uint: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint)[i])) - case reflect.Uint64: - slice.Index(i).Set(reflect.ValueOf(vals.([]uint64)[i])) - case reflect.Float64: - slice.Index(i).Set(reflect.ValueOf(vals.([]float64)[i])) - case reflectTime: - slice.Index(i).Set(reflect.ValueOf(vals.([]time.Time)[i])) - } - } - field.Set(slice) - return nil -} - -func wrapStrictError(err error, isStrict bool) error { - if isStrict { - return err - } - return nil -} - -// setWithProperType sets proper value to field based on its type, -// but it does not return error for failing parsing, -// because we want to use default value that is already assigned to strcut. -func setWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string, allowShadow, isStrict bool) error { - switch t.Kind() { - case reflect.String: - if len(key.String()) == 0 { - return nil - } - field.SetString(key.String()) - case reflect.Bool: - boolVal, err := key.Bool() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetBool(boolVal) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && int64(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - intVal, err := key.Int64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetInt(intVal) - // byte is an alias for uint8, so supporting uint8 breaks support for byte - case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64: - durationVal, err := key.Duration() - // Skip zero value - if err == nil && uint64(durationVal) > 0 { - field.Set(reflect.ValueOf(durationVal)) - return nil - } - - uintVal, err := key.Uint64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetUint(uintVal) - - case reflect.Float32, reflect.Float64: - floatVal, err := key.Float64() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.SetFloat(floatVal) - case reflectTime: - timeVal, err := key.Time() - if err != nil { - return wrapStrictError(err, isStrict) - } - field.Set(reflect.ValueOf(timeVal)) - case reflect.Slice: - return setSliceWithProperType(key, field, delim, allowShadow, isStrict) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -func parseTagOptions(tag string) (rawName string, omitEmpty bool, allowShadow bool) { - opts := strings.SplitN(tag, ",", 3) - rawName = opts[0] - if len(opts) > 1 { - omitEmpty = opts[1] == "omitempty" - } - if len(opts) > 2 { - allowShadow = opts[2] == "allowshadow" - } - return rawName, omitEmpty, allowShadow -} - -func (s *Section) mapTo(val reflect.Value, isStrict bool) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - rawName, _, allowShadow := parseTagOptions(tag) - fieldName := s.parseFieldName(tpField.Name, rawName) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - isAnonymous := tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous - isStruct := tpField.Type.Kind() == reflect.Struct - if isAnonymous { - field.Set(reflect.New(tpField.Type.Elem())) - } - - if isAnonymous || isStruct { - if sec, err := s.f.GetSection(fieldName); err == nil { - if err = sec.mapTo(field, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - continue - } - } - - if key, err := s.GetKey(fieldName); err == nil { - delim := parseDelim(tpField.Tag.Get("delim")) - if err = setWithProperType(tpField.Type, key, field, delim, allowShadow, isStrict); err != nil { - return fmt.Errorf("error mapping field(%s): %v", fieldName, err) - } - } - } - return nil -} - -// MapTo maps section to given struct. -func (s *Section) MapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, false) -} - -// MapTo maps section to given struct in strict mode, -// which returns all possible error including value parsing error. -func (s *Section) StrictMapTo(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot map to non-pointer struct") - } - - return s.mapTo(val, true) -} - -// MapTo maps file to given struct. -func (f *File) MapTo(v interface{}) error { - return f.Section("").MapTo(v) -} - -// MapTo maps file to given struct in strict mode, -// which returns all possible error including value parsing error. -func (f *File) StrictMapTo(v interface{}) error { - return f.Section("").StrictMapTo(v) -} - -// MapTo maps data sources to given struct with name mapper. -func MapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.MapTo(v) -} - -// StrictMapToWithMapper maps data sources to given struct with name mapper in strict mode, -// which returns all possible error including value parsing error. -func StrictMapToWithMapper(v interface{}, mapper NameMapper, source interface{}, others ...interface{}) error { - cfg, err := Load(source, others...) - if err != nil { - return err - } - cfg.NameMapper = mapper - return cfg.StrictMapTo(v) -} - -// MapTo maps data sources to given struct. -func MapTo(v, source interface{}, others ...interface{}) error { - return MapToWithMapper(v, nil, source, others...) -} - -// StrictMapTo maps data sources to given struct in strict mode, -// which returns all possible error including value parsing error. -func StrictMapTo(v, source interface{}, others ...interface{}) error { - return StrictMapToWithMapper(v, nil, source, others...) -} - -// reflectSliceWithProperType does the opposite thing as setSliceWithProperType. -func reflectSliceWithProperType(key *Key, field reflect.Value, delim string) error { - slice := field.Slice(0, field.Len()) - if field.Len() == 0 { - return nil - } - - var buf bytes.Buffer - sliceOf := field.Type().Elem().Kind() - for i := 0; i < field.Len(); i++ { - switch sliceOf { - case reflect.String: - buf.WriteString(slice.Index(i).String()) - case reflect.Int, reflect.Int64: - buf.WriteString(fmt.Sprint(slice.Index(i).Int())) - case reflect.Uint, reflect.Uint64: - buf.WriteString(fmt.Sprint(slice.Index(i).Uint())) - case reflect.Float64: - buf.WriteString(fmt.Sprint(slice.Index(i).Float())) - case reflectTime: - buf.WriteString(slice.Index(i).Interface().(time.Time).Format(time.RFC3339)) - default: - return fmt.Errorf("unsupported type '[]%s'", sliceOf) - } - buf.WriteString(delim) - } - key.SetValue(buf.String()[:buf.Len()-1]) - return nil -} - -// reflectWithProperType does the opposite thing as setWithProperType. -func reflectWithProperType(t reflect.Type, key *Key, field reflect.Value, delim string) error { - switch t.Kind() { - case reflect.String: - key.SetValue(field.String()) - case reflect.Bool: - key.SetValue(fmt.Sprint(field.Bool())) - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - key.SetValue(fmt.Sprint(field.Int())) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - key.SetValue(fmt.Sprint(field.Uint())) - case reflect.Float32, reflect.Float64: - key.SetValue(fmt.Sprint(field.Float())) - case reflectTime: - key.SetValue(fmt.Sprint(field.Interface().(time.Time).Format(time.RFC3339))) - case reflect.Slice: - return reflectSliceWithProperType(key, field, delim) - default: - return fmt.Errorf("unsupported type '%s'", t) - } - return nil -} - -// CR: copied from encoding/json/encode.go with modifications of time.Time support. -// TODO: add more test coverage. -func isEmptyValue(v reflect.Value) bool { - switch v.Kind() { - case reflect.Array, reflect.Map, reflect.Slice, reflect.String: - return v.Len() == 0 - case reflect.Bool: - return !v.Bool() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return v.Int() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return v.Uint() == 0 - case reflect.Float32, reflect.Float64: - return v.Float() == 0 - case reflect.Interface, reflect.Ptr: - return v.IsNil() - case reflectTime: - t, ok := v.Interface().(time.Time) - return ok && t.IsZero() - } - return false -} - -func (s *Section) reflectFrom(val reflect.Value) error { - if val.Kind() == reflect.Ptr { - val = val.Elem() - } - typ := val.Type() - - for i := 0; i < typ.NumField(); i++ { - field := val.Field(i) - tpField := typ.Field(i) - - tag := tpField.Tag.Get("ini") - if tag == "-" { - continue - } - - opts := strings.SplitN(tag, ",", 2) - if len(opts) == 2 && opts[1] == "omitempty" && isEmptyValue(field) { - continue - } - - fieldName := s.parseFieldName(tpField.Name, opts[0]) - if len(fieldName) == 0 || !field.CanSet() { - continue - } - - if (tpField.Type.Kind() == reflect.Ptr && tpField.Anonymous) || - (tpField.Type.Kind() == reflect.Struct && tpField.Type.Name() != "Time") { - // Note: The only error here is section doesn't exist. - sec, err := s.f.GetSection(fieldName) - if err != nil { - // Note: fieldName can never be empty here, ignore error. - sec, _ = s.f.NewSection(fieldName) - } - - // Add comment from comment tag - if len(sec.Comment) == 0 { - sec.Comment = tpField.Tag.Get("comment") - } - - if err = sec.reflectFrom(field); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - continue - } - - // Note: Same reason as secion. - key, err := s.GetKey(fieldName) - if err != nil { - key, _ = s.NewKey(fieldName, "") - } - - // Add comment from comment tag - if len(key.Comment) == 0 { - key.Comment = tpField.Tag.Get("comment") - } - - if err = reflectWithProperType(tpField.Type, key, field, parseDelim(tpField.Tag.Get("delim"))); err != nil { - return fmt.Errorf("error reflecting field (%s): %v", fieldName, err) - } - - } - return nil -} - -// ReflectFrom reflects secion from given struct. -func (s *Section) ReflectFrom(v interface{}) error { - typ := reflect.TypeOf(v) - val := reflect.ValueOf(v) - if typ.Kind() == reflect.Ptr { - typ = typ.Elem() - val = val.Elem() - } else { - return errors.New("cannot reflect from non-pointer struct") - } - - return s.reflectFrom(val) -} - -// ReflectFrom reflects file from given struct. -func (f *File) ReflectFrom(v interface{}) error { - return f.Section("").ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct with name mapper. -func ReflectFromWithMapper(cfg *File, v interface{}, mapper NameMapper) error { - cfg.NameMapper = mapper - return cfg.ReflectFrom(v) -} - -// ReflectFrom reflects data sources from given struct. -func ReflectFrom(cfg *File, v interface{}) error { - return ReflectFromWithMapper(cfg, v, nil) -} diff --git a/vendor/github.com/go-kit/kit/LICENSE b/vendor/github.com/go-kit/kit/LICENSE deleted file mode 100644 index 9d83342ac..000000000 --- a/vendor/github.com/go-kit/kit/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2015 Peter Bourgon - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/go-kit/kit/log/doc.go b/vendor/github.com/go-kit/kit/log/doc.go deleted file mode 100644 index 918c0af46..000000000 --- a/vendor/github.com/go-kit/kit/log/doc.go +++ /dev/null @@ -1,116 +0,0 @@ -// Package log provides a structured logger. -// -// Structured logging produces logs easily consumed later by humans or -// machines. Humans might be interested in debugging errors, or tracing -// specific requests. Machines might be interested in counting interesting -// events, or aggregating information for off-line processing. In both cases, -// it is important that the log messages are structured and actionable. -// Package log is designed to encourage both of these best practices. -// -// Basic Usage -// -// The fundamental interface is Logger. Loggers create log events from -// key/value data. The Logger interface has a single method, Log, which -// accepts a sequence of alternating key/value pairs, which this package names -// keyvals. -// -// type Logger interface { -// Log(keyvals ...interface{}) error -// } -// -// Here is an example of a function using a Logger to create log events. -// -// func RunTask(task Task, logger log.Logger) string { -// logger.Log("taskID", task.ID, "event", "starting task") -// ... -// logger.Log("taskID", task.ID, "event", "task complete") -// } -// -// The keys in the above example are "taskID" and "event". The values are -// task.ID, "starting task", and "task complete". Every key is followed -// immediately by its value. -// -// Keys are usually plain strings. Values may be any type that has a sensible -// encoding in the chosen log format. With structured logging it is a good -// idea to log simple values without formatting them. This practice allows -// the chosen logger to encode values in the most appropriate way. -// -// Contextual Loggers -// -// A contextual logger stores keyvals that it includes in all log events. -// Building appropriate contextual loggers reduces repetition and aids -// consistency in the resulting log output. With and WithPrefix add context to -// a logger. We can use With to improve the RunTask example. -// -// func RunTask(task Task, logger log.Logger) string { -// logger = log.With(logger, "taskID", task.ID) -// logger.Log("event", "starting task") -// ... -// taskHelper(task.Cmd, logger) -// ... -// logger.Log("event", "task complete") -// } -// -// The improved version emits the same log events as the original for the -// first and last calls to Log. Passing the contextual logger to taskHelper -// enables each log event created by taskHelper to include the task.ID even -// though taskHelper does not have access to that value. Using contextual -// loggers this way simplifies producing log output that enables tracing the -// life cycle of individual tasks. (See the Contextual example for the full -// code of the above snippet.) -// -// Dynamic Contextual Values -// -// A Valuer function stored in a contextual logger generates a new value each -// time an event is logged. The Valuer example demonstrates how this feature -// works. -// -// Valuers provide the basis for consistently logging timestamps and source -// code location. The log package defines several valuers for that purpose. -// See Timestamp, DefaultTimestamp, DefaultTimestampUTC, Caller, and -// DefaultCaller. A common logger initialization sequence that ensures all log -// entries contain a timestamp and source location looks like this: -// -// logger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger = log.With(logger, "ts", log.DefaultTimestampUTC, "caller", log.DefaultCaller) -// -// Concurrent Safety -// -// Applications with multiple goroutines want each log event written to the -// same logger to remain separate from other log events. Package log provides -// two simple solutions for concurrent safe logging. -// -// NewSyncWriter wraps an io.Writer and serializes each call to its Write -// method. Using a SyncWriter has the benefit that the smallest practical -// portion of the logging logic is performed within a mutex, but it requires -// the formatting Logger to make only one call to Write per log event. -// -// NewSyncLogger wraps any Logger and serializes each call to its Log method. -// Using a SyncLogger has the benefit that it guarantees each log event is -// handled atomically within the wrapped logger, but it typically serializes -// both the formatting and output logic. Use a SyncLogger if the formatting -// logger may perform multiple writes per log event. -// -// Error Handling -// -// This package relies on the practice of wrapping or decorating loggers with -// other loggers to provide composable pieces of functionality. It also means -// that Logger.Log must return an error because some -// implementations—especially those that output log data to an io.Writer—may -// encounter errors that cannot be handled locally. This in turn means that -// Loggers that wrap other loggers should return errors from the wrapped -// logger up the stack. -// -// Fortunately, the decorator pattern also provides a way to avoid the -// necessity to check for errors every time an application calls Logger.Log. -// An application required to panic whenever its Logger encounters -// an error could initialize its logger as follows. -// -// fmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout)) -// logger := log.LoggerFunc(func(keyvals ...interface{}) error { -// if err := fmtlogger.Log(keyvals...); err != nil { -// panic(err) -// } -// return nil -// }) -package log diff --git a/vendor/github.com/go-kit/kit/log/json_logger.go b/vendor/github.com/go-kit/kit/log/json_logger.go deleted file mode 100644 index 66094b4dd..000000000 --- a/vendor/github.com/go-kit/kit/log/json_logger.go +++ /dev/null @@ -1,89 +0,0 @@ -package log - -import ( - "encoding" - "encoding/json" - "fmt" - "io" - "reflect" -) - -type jsonLogger struct { - io.Writer -} - -// NewJSONLogger returns a Logger that encodes keyvals to the Writer as a -// single JSON object. Each log event produces no more than one call to -// w.Write. The passed Writer must be safe for concurrent use by multiple -// goroutines if the returned Logger will be used concurrently. -func NewJSONLogger(w io.Writer) Logger { - return &jsonLogger{w} -} - -func (l *jsonLogger) Log(keyvals ...interface{}) error { - n := (len(keyvals) + 1) / 2 // +1 to handle case when len is odd - m := make(map[string]interface{}, n) - for i := 0; i < len(keyvals); i += 2 { - k := keyvals[i] - var v interface{} = ErrMissingValue - if i+1 < len(keyvals) { - v = keyvals[i+1] - } - merge(m, k, v) - } - return json.NewEncoder(l.Writer).Encode(m) -} - -func merge(dst map[string]interface{}, k, v interface{}) { - var key string - switch x := k.(type) { - case string: - key = x - case fmt.Stringer: - key = safeString(x) - default: - key = fmt.Sprint(x) - } - - // We want json.Marshaler and encoding.TextMarshaller to take priority over - // err.Error() and v.String(). But json.Marshall (called later) does that by - // default so we force a no-op if it's one of those 2 case. - switch x := v.(type) { - case json.Marshaler: - case encoding.TextMarshaler: - case error: - v = safeError(x) - case fmt.Stringer: - v = safeString(x) - } - - dst[key] = v -} - -func safeString(str fmt.Stringer) (s string) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(str); v.Kind() == reflect.Ptr && v.IsNil() { - s = "NULL" - } else { - panic(panicVal) - } - } - }() - s = str.String() - return -} - -func safeError(err error) (s interface{}) { - defer func() { - if panicVal := recover(); panicVal != nil { - if v := reflect.ValueOf(err); v.Kind() == reflect.Ptr && v.IsNil() { - s = nil - } else { - panic(panicVal) - } - } - }() - s = err.Error() - return -} diff --git a/vendor/github.com/go-kit/kit/log/log.go b/vendor/github.com/go-kit/kit/log/log.go deleted file mode 100644 index 66a9e2fde..000000000 --- a/vendor/github.com/go-kit/kit/log/log.go +++ /dev/null @@ -1,135 +0,0 @@ -package log - -import "errors" - -// Logger is the fundamental interface for all log operations. Log creates a -// log event from keyvals, a variadic sequence of alternating keys and values. -// Implementations must be safe for concurrent use by multiple goroutines. In -// particular, any implementation of Logger that appends to keyvals or -// modifies or retains any of its elements must make a copy first. -type Logger interface { - Log(keyvals ...interface{}) error -} - -// ErrMissingValue is appended to keyvals slices with odd length to substitute -// the missing value. -var ErrMissingValue = errors.New("(MISSING)") - -// With returns a new contextual logger with keyvals prepended to those passed -// to calls to Log. If logger is also a contextual logger created by With or -// WithPrefix, keyvals is appended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func With(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - return &context{ - logger: l.logger, - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - keyvals: kvs[:len(kvs):len(kvs)], - hasValuer: l.hasValuer || containsValuer(keyvals), - } -} - -// WithPrefix returns a new contextual logger with keyvals prepended to those -// passed to calls to Log. If logger is also a contextual logger created by -// With or WithPrefix, keyvals is prepended to the existing context. -// -// The returned Logger replaces all value elements (odd indexes) containing a -// Valuer with their generated value for each call to its Log method. -func WithPrefix(logger Logger, keyvals ...interface{}) Logger { - if len(keyvals) == 0 { - return logger - } - l := newContext(logger) - // Limiting the capacity of the stored keyvals ensures that a new - // backing array is created if the slice must grow in Log or With. - // Using the extra capacity without copying risks a data race that - // would violate the Logger interface contract. - n := len(l.keyvals) + len(keyvals) - if len(keyvals)%2 != 0 { - n++ - } - kvs := make([]interface{}, 0, n) - kvs = append(kvs, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - kvs = append(kvs, l.keyvals...) - return &context{ - logger: l.logger, - keyvals: kvs, - hasValuer: l.hasValuer || containsValuer(keyvals), - } -} - -// context is the Logger implementation returned by With and WithPrefix. It -// wraps a Logger and holds keyvals that it includes in all log events. Its -// Log method calls bindValues to generate values for each Valuer in the -// context keyvals. -// -// A context must always have the same number of stack frames between calls to -// its Log method and the eventual binding of Valuers to their value. This -// requirement comes from the functional requirement to allow a context to -// resolve application call site information for a Caller stored in the -// context. To do this we must be able to predict the number of logging -// functions on the stack when bindValues is called. -// -// Two implementation details provide the needed stack depth consistency. -// -// 1. newContext avoids introducing an additional layer when asked to -// wrap another context. -// 2. With and WithPrefix avoid introducing an additional layer by -// returning a newly constructed context with a merged keyvals rather -// than simply wrapping the existing context. -type context struct { - logger Logger - keyvals []interface{} - hasValuer bool -} - -func newContext(logger Logger) *context { - if c, ok := logger.(*context); ok { - return c - } - return &context{logger: logger} -} - -// Log replaces all value elements (odd indexes) containing a Valuer in the -// stored context with their generated value, appends keyvals, and passes the -// result to the wrapped Logger. -func (l *context) Log(keyvals ...interface{}) error { - kvs := append(l.keyvals, keyvals...) - if len(kvs)%2 != 0 { - kvs = append(kvs, ErrMissingValue) - } - if l.hasValuer { - // If no keyvals were appended above then we must copy l.keyvals so - // that future log events will reevaluate the stored Valuers. - if len(keyvals) == 0 { - kvs = append([]interface{}{}, l.keyvals...) - } - bindValues(kvs[:len(l.keyvals)]) - } - return l.logger.Log(kvs...) -} - -// LoggerFunc is an adapter to allow use of ordinary functions as Loggers. If -// f is a function with the appropriate signature, LoggerFunc(f) is a Logger -// object that calls f. -type LoggerFunc func(...interface{}) error - -// Log implements Logger by calling f(keyvals...). -func (f LoggerFunc) Log(keyvals ...interface{}) error { - return f(keyvals...) -} diff --git a/vendor/github.com/go-kit/kit/log/logfmt_logger.go b/vendor/github.com/go-kit/kit/log/logfmt_logger.go deleted file mode 100644 index a00305298..000000000 --- a/vendor/github.com/go-kit/kit/log/logfmt_logger.go +++ /dev/null @@ -1,62 +0,0 @@ -package log - -import ( - "bytes" - "io" - "sync" - - "github.com/go-logfmt/logfmt" -) - -type logfmtEncoder struct { - *logfmt.Encoder - buf bytes.Buffer -} - -func (l *logfmtEncoder) Reset() { - l.Encoder.Reset() - l.buf.Reset() -} - -var logfmtEncoderPool = sync.Pool{ - New: func() interface{} { - var enc logfmtEncoder - enc.Encoder = logfmt.NewEncoder(&enc.buf) - return &enc - }, -} - -type logfmtLogger struct { - w io.Writer -} - -// NewLogfmtLogger returns a logger that encodes keyvals to the Writer in -// logfmt format. Each log event produces no more than one call to w.Write. -// The passed Writer must be safe for concurrent use by multiple goroutines if -// the returned Logger will be used concurrently. -func NewLogfmtLogger(w io.Writer) Logger { - return &logfmtLogger{w} -} - -func (l logfmtLogger) Log(keyvals ...interface{}) error { - enc := logfmtEncoderPool.Get().(*logfmtEncoder) - enc.Reset() - defer logfmtEncoderPool.Put(enc) - - if err := enc.EncodeKeyvals(keyvals...); err != nil { - return err - } - - // Add newline to the end of the buffer - if err := enc.EndRecord(); err != nil { - return err - } - - // The Logger interface requires implementations to be safe for concurrent - // use by multiple goroutines. For this implementation that means making - // only one call to l.w.Write() for each call to Log. - if _, err := l.w.Write(enc.buf.Bytes()); err != nil { - return err - } - return nil -} diff --git a/vendor/github.com/go-kit/kit/log/nop_logger.go b/vendor/github.com/go-kit/kit/log/nop_logger.go deleted file mode 100644 index 1047d626c..000000000 --- a/vendor/github.com/go-kit/kit/log/nop_logger.go +++ /dev/null @@ -1,8 +0,0 @@ -package log - -type nopLogger struct{} - -// NewNopLogger returns a logger that doesn't do anything. -func NewNopLogger() Logger { return nopLogger{} } - -func (nopLogger) Log(...interface{}) error { return nil } diff --git a/vendor/github.com/go-kit/kit/log/stdlib.go b/vendor/github.com/go-kit/kit/log/stdlib.go deleted file mode 100644 index ff96b5dee..000000000 --- a/vendor/github.com/go-kit/kit/log/stdlib.go +++ /dev/null @@ -1,116 +0,0 @@ -package log - -import ( - "io" - "log" - "regexp" - "strings" -) - -// StdlibWriter implements io.Writer by invoking the stdlib log.Print. It's -// designed to be passed to a Go kit logger as the writer, for cases where -// it's necessary to redirect all Go kit log output to the stdlib logger. -// -// If you have any choice in the matter, you shouldn't use this. Prefer to -// redirect the stdlib log to the Go kit logger via NewStdlibAdapter. -type StdlibWriter struct{} - -// Write implements io.Writer. -func (w StdlibWriter) Write(p []byte) (int, error) { - log.Print(strings.TrimSpace(string(p))) - return len(p), nil -} - -// StdlibAdapter wraps a Logger and allows it to be passed to the stdlib -// logger's SetOutput. It will extract date/timestamps, filenames, and -// messages, and place them under relevant keys. -type StdlibAdapter struct { - Logger - timestampKey string - fileKey string - messageKey string -} - -// StdlibAdapterOption sets a parameter for the StdlibAdapter. -type StdlibAdapterOption func(*StdlibAdapter) - -// TimestampKey sets the key for the timestamp field. By default, it's "ts". -func TimestampKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.timestampKey = key } -} - -// FileKey sets the key for the file and line field. By default, it's "caller". -func FileKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.fileKey = key } -} - -// MessageKey sets the key for the actual log message. By default, it's "msg". -func MessageKey(key string) StdlibAdapterOption { - return func(a *StdlibAdapter) { a.messageKey = key } -} - -// NewStdlibAdapter returns a new StdlibAdapter wrapper around the passed -// logger. It's designed to be passed to log.SetOutput. -func NewStdlibAdapter(logger Logger, options ...StdlibAdapterOption) io.Writer { - a := StdlibAdapter{ - Logger: logger, - timestampKey: "ts", - fileKey: "caller", - messageKey: "msg", - } - for _, option := range options { - option(&a) - } - return a -} - -func (a StdlibAdapter) Write(p []byte) (int, error) { - result := subexps(p) - keyvals := []interface{}{} - var timestamp string - if date, ok := result["date"]; ok && date != "" { - timestamp = date - } - if time, ok := result["time"]; ok && time != "" { - if timestamp != "" { - timestamp += " " - } - timestamp += time - } - if timestamp != "" { - keyvals = append(keyvals, a.timestampKey, timestamp) - } - if file, ok := result["file"]; ok && file != "" { - keyvals = append(keyvals, a.fileKey, file) - } - if msg, ok := result["msg"]; ok { - keyvals = append(keyvals, a.messageKey, msg) - } - if err := a.Logger.Log(keyvals...); err != nil { - return 0, err - } - return len(p), nil -} - -const ( - logRegexpDate = `(?P[0-9]{4}/[0-9]{2}/[0-9]{2})?[ ]?` - logRegexpTime = `(?P